【问题标题】:Checking pixel color in OpenCV with Python使用 Python 检查 OpenCV 中的像素颜色
【发布时间】:2016-05-28 03:51:25
【问题描述】:

我目前正在使用 python 和 OpenCV 进行项目。对于项目的一部分,我想检查一个特定像素(特别是坐标为 100、100 的像素)是否不等于黑色。我的代码如下。

import cv2

img = cv2.imread('/Documents/2016.jpg')

if img[100, 100] != [0, 0, 0]:
    print("the pixel is not black")

当我在终端中玩耍时,我得到了这个错误。

File "/Documents/imCam.py", line 5, in <module>
if img[100, 100] != [0, 0, 0]:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我做错了什么?

【问题讨论】:

    标签: python image opencv pixels


    【解决方案1】:

    正如它所说,您将列表与多个条目进行比较,这太不精确了。

    你必须使用 numpy.any 喜欢

    import cv2
    import numpy as np
    
    img = cv2.imread('/Documents/2016.jpg')
    
    if np.any(img[100, 100] != 0):
        print("the pixel is not black")
    

    【讨论】:

    • 此解决方案是否仅适用于所有 B、G 和 R 值相同的颜色?你怎么能和不同的颜色比较?喜欢if img[100, 100] != [222, 12, 127]:
    • img[100, 100] != [222, 12, 127] 返回一个布尔值列表,np.all() 返回True,如果给定列表的每个元素都是True。所以np.all(img[100, 100] == [222, 12, 127]) 会检查两种颜色是否匹配。
    【解决方案2】:
    import cv2
    
    image = cv2.imread('abc.jpg')
    
    if image[50, 50, 0] != 0:
        print("the pixel is not black")
    

    试试这个:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多