Reputation: 41
I am trying to keep track of red objects using opencv in python. Here is the code I have so far:
#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)
When I run this, the error that comes up is the following:
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
Can someone please tell me what I am doing wrong? I have tried
lower_red=np.array([0, 100, 75], dtype=np.uint8)
as well, but that didn't work either.
Upvotes: 4
Views: 11297
Reputation: 22964
I guess the error is in line hsv=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
, as per the variable naming I am assuming that you want a HSV image but you have mistakenly used cv2.COLOR_BGR2GRAY
in place of cv2.COLOR_BGR2HSV
.
As cv2.COLOR_BGR2GRAY
converts the image to grayscale and returns a single channel image so applying mask=cv2.inRange(hsv, lower_red, upper_red)
where hsv
is a single channel image(while using cv2.COLOR_BGR2GRAY
) and lower_red
, upper_red
both have 3 elements which results in the error.
Upvotes: 8