Python Forum

Full Version: python opencv grayscale conversion error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I am running below script. I tried with different video files format, avi/mp4 but the error is at line where each video frame is converted into grayscale. I tried this code by providing images from folder it works but when used video. There is error for grayscale conversion. Please advice.

Error:
nframe_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
import numpy as np
import cv2

path = 'file_example_AVI_480_750kB.avi'

# below code works with OpenCV

cap = cv2.VideoCapture(path)

while(cap.isOpened()):
    ret, frame = cap.read()
    frameNum = frameNum+1;
# to implement gray conversion of frame
    nframe_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)


    #Below code, shows each frame in a moving video
    #if ret == True:
        # Display the resulting frame
    #    cv2.imshow('Frame', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
Your code runs well with the below change:

    if ret == True:
        nframe_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)