'Error: !_img.empty() in function 'imwrite'

I want to create frames from the video named project.avi and save them to frameIn folder. But some type of errors are not let me done. How can I solve this problem. Here is the code:

cap = cv2.VideoCapture('project.avi')

currentFrame = 0

while(True):

ret, frame = cap.read()

name = 'frameIn/frame' + str(currentFrame) + '.jpg'
print ("Creating file... " + name)
cv2.imwrite(name, frame)

frames.append(name)

currentFrame += 1

cap.release()
cv2.destroyAllWindows()

The error is:

Traceback (most recent call last):
  File "videoreader.py", line 28, in <module>
    cv2.imwrite(name, frame)
cv2.error: OpenCV(4.4.0) /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-2rx9f0ng/opencv/modules/imgcodecs/src/loadsave.cpp:738: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'


Solution 1:[1]

The cause may be that image is empty, so, You should check weather video is opened correctly before read frames by: cap.isOpened(). Then, after execute ret, frame = cap.read() check ret variable value if true to ensure that frame is grabbed correctly.

The code to be Clear :

cap = cv2.VideoCapture('project.avi')
if cap.isOpened():
    current_frame = 0
    while True:
        ret, frame = cap.read()
        if ret:
            name = f'frameIn/frame{current_frame}.jpg'
            print(f"Creating file... {name}")
            cv2.imwrite(name, frame)
            frames.append(name)
        current_frame += 1
    cap.release()
cv2.destroyAllWindows()

I hope it helped you.

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 aph