gpt4 book ai didi

python - 如果我知道颜色(RGB),如何获得像素坐标?

转载 作者:太空宇宙 更新时间:2023-11-03 21:31:53 25 4
gpt4 key购买 nike

我使用 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)

  • 我使用 numpy.where() 方法检索两个数组的元组索引,其中第一个数组包含颜色像素 (235, 187, 7) 的 x 坐标,第二个数组包含 y 坐标这些像素。

现在 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))
  • 然后我使用 zip() 方法获取包含这些点的元组列表。

坐标 = zip(指数[0], 指数[1])

  • 但是如果您注意到,因为这是一个具有三个 channel 的彩色图像,每个坐标将重复三次。我们必须只保留唯一坐标。这可以使用 set() 方法来完成。

unique_coordinates = list(set(list(coordinates)))

关于python - 如果我知道颜色(RGB),如何获得像素坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51164713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com