如何找到最右边黑色像素的位置

How to find the location of the rightmost black pixel

一张黑白图像,在框架内显示一张笑脸。

我要的是找出笑脸最右边点的位置。 (在这种情况下,黑色应位于图像的“184,91”左右)

我希望通过下面列出图像中的颜色,然后看看可以进一步寻找什么。

from PIL import Image
im = Image.open("face.jpg")
print im.convert('RGB').getcolors() # or print im.getcolors()

但是 returns None,我卡住了。

怎样才能得到脸部最合适的点?

作为一种间接的方式,也许我可以: 1.取下相框 2. trim白

剩下的就是核心图像本身。如果核心图像是规则图案,图像的尺寸可以告诉坐标。

from PIL import Image

img = Image.open("c:\smile.jpg")
img2 = img.crop((30, 26, 218, 165))  # remove the frame
img2.save("c:\cropped-smile.jpg")

Trim whitespace using PIL教如何去掉圆圈的白色部分

def trim(im):
    bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox)

im = Image.open("c:\cropped-smile.jpg")
im = trim(im)
im.save("c:\final-smile.jpg")

现在获取核心图像的尺寸。

im = Image.open("c:\final-sbqcu.jpg")
w, h = im.size

我得到的是 131,132。所以131,66应该是图像最右边的点。

这是我想出的解决方案:

import numpy as np
from skimage import io

img = io.imread('https://i.stack.imgur.com/sbqcu.jpg', as_grey=True)

left, right, top, bottom = 25, 25, 20, 20
crop = img[top: -bottom, left:- right]
threshold = .85
smiley = crop < threshold

rows, cols = np.nonzero(smiley)
rightmost = cols.max()
indices = np.nonzero(cols==rightmost)

for r, c, in zip(rows[indices], cols[indices]):
    print('(%d, %d)' % (r + top, c + left))

上面的代码产生:

(87, 184)
(88, 184)
(89, 184)
(90, 184)
(91, 184)
(92, 184)
(93, 184)
(94, 184)
(95, 184)
(96, 184)
(97, 184)
(98, 184)

这与笑脸最右边有一条垂直直线是一致的

必须仔细选择阈值以避免检测到噪声像素:

threshold = .95
io.imshow(crop < threshold)