dr.*_*dia 6 python opencv python-imaging-library python-3.x
我使用 Python、opencv 和 PIL。
image = cv2.imread('image.jpg')
color = (235, 187, 7)
如果我知道像素颜色,如何获得像素坐标(x,y)?
这是一个 numpythonic 解决方案。Numpy 库尽可能加快操作速度。
color = (235, 187, 7)indices = np.where(img == color)
现在indices返回如下内容:
(array([ 81,  81,  81, ..., 304, 304, 304], dtype=int64),
 array([317, 317, 317, ..., 520, 520, 520], dtype=int64),
 array([0, 1, 2, ..., 0, 1, 2], dtype=int64))
coordinates = zip(indices[0], indices[1]) 
set()方法来完成。unique_coordinates = list(set(list(coordinates)))
尝试类似的方法:
color = (235, 187, 7)
im = Image.open('image.gif')
rgb_im = im.convert('RGB')
for x in range(rgb_im.size()[0]):
    for y in range(rgb_im.size()[1]):
        r, g, b = rgb_im.getpixel((x, y))
        if (r,g,b) == colour:
            print(f"Found {colour} at {x},{y}!")
但getpixel 可能会很慢,因此请考虑使用像素访问对象。
另请注意,返回的值可能取决于图像类型。例如,pix[1, 1]由于 GIF 像素引用 GIF 调色板中的 256 个值之一,因此返回单个值。
另请参阅这篇文章:Python and PIL Pixel Values different for GIF and JPEG,此PIL 参考页面  包含有关该函数的更多信息convert()。
顺便说一句,您的代码对于图像来说效果很好.jpg。
| 归档时间: | 
 | 
| 查看次数: | 13788 次 | 
| 最近记录: |