Tahsin Alpaydın
Tahsin Alpaydın

Reputation: 71

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'

Upvotes: 7

Views: 59813

Answers (2)

Tanveer Singh
Tanveer Singh

Reputation: 1

The error message you provided is from OpenCV's imwrite function. It indicates that the function encountered an assertion failure because the input image _img is empty.

In your code snippet, it seems that you are trying to download an image from a URL using wget and then load and save it using OpenCV's imwrite function. However, the error suggests that the image could not be downloaded or read properly, resulting in an empty image.

The error message also includes the line: code---> Resolving $image_url ($image_url)... failed: Name or service not known. This suggests that the variable $image_url has not been properly defined or resolved to a valid URL. Make sure that you have assigned a valid URL to the variable before using it in the wget command.

Additionally, verify that the image was successfully downloaded and that the path to the image file is correct before attempting to load it with OpenCV.

If you provide more details or share the relevant code snippet, I can help you further in troubleshooting the issue.

Upvotes: -2

Ali Alnadous
Ali Alnadous

Reputation: 334

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.

Upvotes: 11

Related Questions