python - 如果我知道颜色(RGB),如何获取像素坐标?
问题描述
我使用 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() 方法检索两个数组的元组索引,其中第一个数组包含颜色像素的 x 坐标 (235, 187, 7),第二个数组包含这些像素的 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() 方法获取包含这些点的元组列表。
coordinates = zip(indices[0], indices[1])
- 但是,如果您注意到这是一个具有三个通道的彩色图像,每个坐标将重复三次。我们必须只保留唯一的坐标。这可以使用
set()
方法来完成。
unique_coordinates = list(set(list(coordinates)))
推荐阅读
- jmeter - 如何在 curl 中将多个 JSON 文件作为 --data-binary 传递到 JMeter?
- python - ASR 纠错以使用 NLP 改进医学转录
- python - 如何构建“嵌套 for 循环生成器”?
- xml - 如何为 OAI-PMH 响应生成 XSLT?
- javascript - 为什么在这里不能将一组材质传递给 THREE.Mesh 构造函数?
- javascript - 如何仅匹配 alpha 版本,例如 1.0.0-alpha.*
- csv - Jenkins - 如何合并来自多个作业的 csv 输出文件
- c++ - 连接调用没有匹配的成员函数
- node.js - Arrow 函数中的变量 this 是 Browser 中的 Window 对象,但是 Node 中为什么是空的呢?
- ontology - 本体和 CLIPS 兼容性