cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-qjdp5db9\opencv\modules\imgcodecs\src\loadsave.cpp:738: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite' code example

Example: cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

Hello Everyone,

I had run into the same problem a few days back. Here's my perspective on why this error came up and how can it be fixed.

The reason behind the error:-
- ```cv2.imread() or cv2.VideoCapture()``` can't find where the file is and hence gives src.empty() since None is returned instead of image or video
- If you are sure that the path specified is correct, then chances are the file being read is corrupted either completely or in a few bits and pieces.

If you got into this problem when working with an image then here is the fix:-
- Change the image, literally. If you don't want to change it then try ```from PIL import Image and Image.open()``` and see if that works and try to display the image by using matplotlib.
- Changing or reproducing the same image is the best option in my opinion.

If you got into this problem when working with a video then here is the fix:- 
- After using ```cv2.VideoCapture('video path')``` Try something like below example.
```
# suppose this was the source 
cap = cv2.VideoCapture('data/input.mpg')
# Get width and height of the frame of video
width  = cap.get(3) # float width
height = cap.get(4) # float height    
# Make a video writer to see if video being taken as input inflict any changes you make
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
out_video = cv2.VideoWriter('result/output.avi', fourcc, 20.0, (int(width), int(height)), True)
# Then try this
while(cap.isOpened()):
        # Read each frame where ret is a return boollean value(True or False)
        ret, frame = cap.read()
        # if return is true continue because if it isn't then frame is of NoneType in that case you cant work on that frame
        if ret:
            # Any preprocessing you want to make on the frame goes here
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            # See if preprocessing is working on the frame it should
            cv2.imshow('frame', gray)
            # finally write your preprocessed frame into your output video
            out_video.write(gray) # write the modifies frame into output video 
            # to forcefully stop the running loop and break out, if it doesnt work use ctlr+c
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
       # break out if frame has return NoneType this means that once script encounters such frame it breaks out 
       # You will get the error otherwise 
        else:
            break
# this will tell you from which frame the video is corrupted and need to be changed 
# this could be due to an empty frame. Empty frame might be a result of mistake made while creating or editing video in tools #like adobe premier pro or other products alike 
# You can check you output video it will contains all frame before the error is encountered
```
I hope this solves your problem and you can better debug your video next time you encounter something similar.

Tags:

Misc Example