[Solved] [Bug] OpenCV of python:(-215:Assertion failed) !_img.empty() in function ‘imwrite’

1. Problem description: known bbox, crop the image and save it

2. Code details:

...
for bbox_idx, bbox in enumerate(bbox_list):
img_clip = img[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
cv2.imwrite('./{}.png'.format(bbox_idx),img_clip)
...

3. Error: After running a few pictures successfully, an error is reported

cv2.error: OpenCV(4.6.0) /io/opencv/modules/imgcodecs/src/loadsave.cpp:801: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'

4. Problem Analysis:

Analysis: After running a few pictures, it is successful, indicating that a certain picture, or the bbox of a certain picture has a problem; print out the value of each bbox:

...
#for bbox_idx, bbox in enumerate(bbox_list):
# img_clip = img[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
print(bbox)
# cv2.imwrite('./{}.png'.format(bbox_idx),img_clip)
...
...
[144 248 232 423 2]
[144 247 233 425 2]
[142 251 230 428 2]
[0 263 56 441 4]
[140 256 228 432 2]
[0 262 54 442 4]
[0 259 53 445 4]
[ -3 257 48 446 4] ## A negative number occurs
...
cv2.error: OpenCV(4.6.0) /io/opencv/modules/imgcodecs/src/loadsave.cpp:801: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'

5. Cause of the problem:

The bbox is out of the image boundary during the detection process, resulting in a negative number. The visualization is as follows:

Zero out all values less than 0, problem solved:

...
#for bbox_idx, bbox in enumerate(bbox_list):
bbox[bbox < 0] = 0
# img_clip = img[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
# cv2.imwrite('./{}.png'.format(bbox_idx),img_clip)
...

6. Summary:

 This is a problem with cv2.imwrite(), first make sure the path is correct, and then img pay attention to the following issues:
1. The minimum value of the segmentation cannot be less than 0
2. The maximum value of the segmentation cannot be greater than the width and height of the picture
3. The maximum value of the segmentation is greater than the minimum value of the segmentation

Reference: https://xiulian.blog.csdn.net/article/details/106156340