0

I need to use some motion detection code, then I use following code, provided by this link: http://www.steinm.com/blog/motion-detection-webcam-python-opencv-differential-images/ . Here is the code:

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.CV_WINDOW_AUTOSIZE)

# 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) )
    #diff = 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)

    #cv2.imshow(winName, diff)
    key = cv2.waitKey(10)
    if key == 27:
       cv2.destroyWindow(winName)
       break

print "Goodbye"

At first, it run smoothly, but now, it gives me error :

cv2.error: ........\opencv\modules\imgproc\src\color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

i found various solutions in stackoverflow, but still the error occured. It has been said that the error occured because the source doesn’t have the right color format that the code (third argument in the function call) indicates it should. Can anyone give me ideas why the error occured? Or is that opencv bug and there's no solution for that?

rizkie
  • 121
  • 1
  • 2
  • 7
  • please paste the code used *here*, not a link to some blog. also add the problematic image – berak Oct 11 '14 at 09:37
  • I'm sorry for my mistake. I already had edit my question. The image comes from camera--it is a real-time capture from camera. Can you help me? – rizkie Oct 11 '14 at 13:34
  • 1
    cam.read() returns : err, img. you should *not* discard the err value. you capture probably got some kind of hiccup, and can't deliver a frame temporarily. (i suspect, the img is just *empty*) – berak Oct 11 '14 at 14:56

2 Answers2

0

The problem is t_minus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)

# ^

When you're accessing the [1] index of an BGR image, it's no longer a colour image to be converted using cv2.COLOR_RGB2GRAY. Instead, just write cam.read(). Also note, OpenCV uses BGR by default, not RGB.

a-Jays
  • 1,182
  • 9
  • 20
0

I met this trouble also, after i read above answers i tried it but have not solved it, and finally i find the path of my image was wrong, so u had better check the real path firstly.