我试图在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
将图像转换为灰度并返回单通道图像,因此应用 mask=cv2.inRange(hsv, lower_red, upper_red)
哪儿 hsv
是单通道图像(而使用 cv2.COLOR_BGR2GRAY
)和 lower_red
, upper_red
两者都有3个元素,导致错误。