Skip to main content
 首页 » 编程设计

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

2024年10月17日7fff_TT

在框架内显示笑脸的黑白图像。

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

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

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

但是它返回None,我被卡住了。

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

请您参考如下方法:

这是我想出的解决方案:

import numpy as np 
from skimage import io 
 
img = io.imread('/image/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)