python - OpenCv Python 颜色检测

标签 python image opencv colors detection

我正在尝试在 python 中使用 opencv 跟踪红色对象。这是我到目前为止的代码:

#Identify red objects in an image

#import OpenCV
import cv2
#Import numpy
import numpy as np

#open webcam
imgcap=cv2.VideoCapture(0)

while(1):

    #view the image from the webcam
    _, frame=imgcap.read()
    #convert the image to HSV
    hsv=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    #lower threshold for red
    lower_red=np.array([0, 100, 75])
    #upper threshold for red
    upper_red=np.array([5, 76, 100])

    mask=cv2.inRange(hsv, lower_red, upper_red)

当我运行它时,出现的错误如下:

OpenCV Error: Sizes of input arguments do not match (The lower bounary is             neither an array of the same size and same type as src, nor a scalar) in       cv::inRange, file ..\..\..\opencv-2.4.12\modules\core\src\arithm.cpp, line 2703
Traceback (most recent call last):
  File "red.py", line 23, in <module>
    mask=cv2.inRange(hsv, lower_red, upper_red)
cv2.error: ..\..\..\opencv-2.4.12\modules\core\src\arithm.cpp:2703: error: (-209) The lower bounary is neither an array of the same size and same type as src, nor a scalar in function cv::inRange

有人可以告诉我我做错了什么吗?我试过了

lower_red=np.array([0, 100, 75], dtype=np.uint8) 

同样如此,但这也没有用。

最佳答案

我猜错误在 hsv=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 行中,根据变量命名我假设你想要一个 HSV 图像,但你错误地使用了 cv2.COLOR_BGR2GRAY 代替 cv2.COLOR_BGR2HSV

由于 cv2.COLOR_BGR2GRAY 将图像转换为灰度并返回单 channel 图像,因此应用 mask=cv2.inRange(hsv, lower_red, upper_red) 其中 hsv 是单 channel 图像(同时使用 cv2.COLOR_BGR2GRAY)和 lower_redupper_red 都有 3 个元素,这导致错误。

关于python - OpenCv Python 颜色检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32384186/

相关文章:

Python argparse 参数 : issue with passing strings containing hyphens

python - 无法获取 Excel ChartObjects 计数

javascript - 了解在 Kinetic.JS 中放置图像?

python - 如何找到旋转图像边界框的新坐标以修改其xml文件以进行Tensorflow数据增强?

python - 循环浏览目录并将所有面孔保存在其他目录中

c++ - 带有 Qt 的 OpenCV : The program has unexpectedly finished

python - 如何正确缩放 QGraphicsScene

python - 如何使用电视马拉松获取特定私有(private) channel 的更新?

java - 如何将图像导入到java类中

css - 图像在悬停时移动 - chrome 不透明度问题