我正在尝试使用OpenCV和python检测对象。这是我试图运行的代码。
import cv2
def diffImg(t0, t1, t2):
d1 = cv2.absdiff(t2, t1)
d2 = cv2.absdiff(t1, t0)
return cv2.bitwise_and(d1, d2)
cam = cv2.VideoCapture(1)
winName = "Movement Indicator"
cv2.namedWindow(winName, cv2.CV_WINDOW_AUTOSIZE)
# Read three images first:
t_minus = cv2.cvtColor(cam.read()[1], cv2.COLOR_BGR2GRAY)
t = cv2.cvtColor(cam.read()[1], cv2.COLOR_BGR2GRAY)
t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_BGR2GRAY)
while True:
cv2.imshow( winName, diffImg(t_minus, t, t_plus) )
# Read next image
t_minus = t
t = t_plus
t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_GRAY2BGR)
key = cv2.waitKey(10)
if key == 27:
cv2.destroyWindow(winName)
break
当我运行此代码时,它会出现以下错误。
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor, file ..\..\..\..\opencv\modules\imgproc\src\color.cpp, line 3739
Traceback (most recent call last):
File "C:/Users/Ravi/PycharmProjects/Test/thread1.py", line 14, in <module>
t_minus = cv2.cvtColor(cam.read()[1], cv2.COLOR_BGR2GRAY)
cv2.error: ..\..\..\..\opencv\modules\imgproc\src\color.cpp:3739: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor
我尝试过改变颜色.BRG2GRAY有几种方式(RGB2GRAY ......等),我尝试使用我的默认网络摄像头和其他USB网络摄像头。但两种方式都给出了同样的错误。我该怎么做才能解决这个问题?
当我在 Ubuntu 平台中运行相同代码时,会出现以下错误。
Traceback (most recent call last):
File "/home/ravi/PycharmProjects/Test/thread1.py", line 11, in <module>
cv2.namedWindow(winName, cv2.CV_WINDOW_AUTOSIZE)
AttributeError: 'module' object has no attribute 'CV_WINDOW_AUTOSIZE'
答案 0 :(得分:0)
cam.read()实际上返回2个值(你可能不需要第一个值)。
所以试试这个:
cam = cv2.VideoCapture(1)
winName = "Movement Indicator"
cv2.namedWindow(winName, cv2.CV_WINDOW_AUTOSIZE)
_,frame1 = cam.read()
_,frame2 = cam.read()
_,frame3 = cam.read()
# Read three images first:
t_minus = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
t = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
t_plus = cv2.cvtColor(frame3, cv2.COLOR_BGR2GRAY)
同样适用于下一部分:
while True:
cv2.imshow( winName, diffImg(t_minus, t, t_plus) )
# Read next image
t_minus = t
t = t_plus
_,frame = cam.read()
t_plus = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
key = cv2.waitKey(10)
if key == 27:
cv2.destroyWindow(winName)
break
答案 1 :(得分:0)
对于Ubuntu平台:只需将属性cv2.CV_WINDOW_AUTOSIZE更改为cv2.WINDOW_NORMAL。这是由于我认为opencv版本
import cv2
def diffImg(t0, t1, t2):
d1 = cv2.absdiff(t2, t1)
d2 = cv2.absdiff(t1, t0)
return cv2.bitwise_and(d1, d2)
cam = cv2.VideoCapture(0)
winName = "Movement Indicator"
cv2.namedWindow(winName, cv2.WINDOW_NORMAL)
# Read three images first:
t_minus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
while True:
cv2.imshow( winName, diffImg(t_minus, t, t_plus) )
# Read next image
t_minus = t
t = t_plus
t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
key = cv2.waitKey(10)
if key == 27:
cv2.destroyWindow(winName)
break