-1

I am learning image processing using python and opencv I write this code in python

   import numpy as np
   import cv2
   vidCap=cv2.VideoCapture('output.avi')
   print('before while')
   while(vidCap.isOpened()):
       print('inside while')
       ret, frame=vidCap.read()
       gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
       cv2.imshow('frame',frame)
             if cv2.waitKey(1) & 0xFF==ord('q'):
                  break
print('outside while')
vidCap.release()
cv2.destroyWindow('LoadedVideo')

and it is giving me this error

    Traceback (most recent call last):
     File "D:\Python Image 
Processing\FirstExercise\PlayingVideoFromFile.py", line 12, in <module>
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
error: C:\builds\master_PackSlaveAddon-win32-vc12-
static\opencv\modules\imgproc\src\color.cpp:7456: error: (-215) scn == 3 || 
scn == 4 in function cv::ipp_cvtColor
James Z
  • 12,209
  • 10
  • 24
  • 44
  • 1
    Possible duplicate https://stackoverflow.com/questions/30506126/open-cv-error-215-scn-3-scn-4-in-function-cvtcolor – biniow Feb 24 '18 at 10:56

1 Answers1

1

The code is passing None as the frame to cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) and this is causing the exception.

You should check the return value of vidCap.read(); if it returns False as the first item in the tuple then there was no grabbed frame and you should not call cv2.cvtColor() on it because its value will be None.

vidCap.isOpened() will continue to return True even after all the frames have been consumed, so it should not be used as the condition in the while loop. The loop could be written as:

if vidCap.isOpened():
    while True:     
        ret, frame = vidCap.read()
        if ret:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            cv2.imshow('frame', frame)
            if (cv2.waitKey(1) & 0xFF) == ord('q'):
                break
        else:
            break
    vidCap.release()

Now the loop is exited when there are no more frames to grab from the file or a 'q' key press is detected.

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • Thanks bro for helping me i was trying from about four hours and could not find any solution for this even going through different sites and youtube videos. I don't get the solution but also the reason why it was not working thanks. May Allah bless you in this Dunya as well as in hereafter. – Muhammad Ammar Malik Feb 24 '18 at 12:51
  • Can you tell me me how to interpret this statement. if (cv2.waitKey(1) & 0xFF) == ord('q'): Thanks in advence – Muhammad Ammar Malik Feb 24 '18 at 13:57
  • @MUHAMMADAMWARMALIK: `waitKey(1)` waits for 1 millisecond for a key to be pressed on the keyboard and returns its value. That value is bitwise ANDed with 0xFF to retain the low order byte. Finally that is compared with the integer value of the character `q` which is 0x71. In summary it is checking whether the user has hit the `q` key which indicates that they want to quit. – mhawke Feb 25 '18 at 06:56