pythonopencvframejupyter-labvideo-conversion

Converting video into frames by openCV


while converting video into frames , it does converted but it show this error

4     while success:
     35         success, frame = cap.read()
---> 36         grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
     37         if(success==False and frame==None):
     38             pass

error: OpenCV(3.4.2) c:\miniconda3\conda-bld\opencv suite_1534379934306\work\modules\imgproc\src\color.hpp:253: error: (-215:Assertion failed) VScn::contains(scn) && VDcn::contains(dcn) && VDepth::contains(depth) in function 'cv::CvtHelper<struct cv::Set<3,4,-1>,struct cv::Set<1,-1,-1>,struct cv::Set<0,2,5>,2>::CvtHelper'

Solution

  • Instead of using success variable twice, check whether the camera or video is opened:

    while cap.isOpened():
    

    Then get the read outputs.

    ret, frame = cap.read()
    

    If the frame is returned successfully, write it to the folder:

    if ret:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        cv2.imwrite("output_frames/gray.png", gray)
    

    Since you'll have multiple frames, you can use a counter to save each frame.

    count = 0
    
    while cap.isOpened():
        ret, frame = cap.read()
    
        if ret:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            cv2.imwrite("output_frames/gray_{}.png".format(count), gray)
            count += 1
    

    Full code:

    import cv2
    
    cap = cv2.VideoCapture("video.mp4")
    
    count = 0
    
    while cap.isOpened():
        ret, frame = cap.read()
    
        if ret:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            cv2.imwrite("output_frames/gray_{}.png".format(count), gray)
            cv2.imshow("output", gray)
            count += 1
    
        if (cv2.waitKey(1) & 0xFF) == ord('q'):
            break
    
    
    cv2.destroyAllWindows()
    cap.release()