'cv2.cvtColor error. Is it bug?

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?



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 a-Jays
Solution 2 user7658779