[Solved] python error: (-215:Assertion failed)

The problem is in these two lines:

crop_img = img[y1:y2, x1:x2]
cv2.imwrite(os.path.join(save_dir, new_jpg_name), crop_img)

Complete error:

cv2.error: OpenCV(4.5.4-dev) D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:799: error: (-215:Assertion failed) !_img.empty() in function 'cv::imwrite'

In addition to the Chinese path problem mentioned in other blogs, the problem here is because the coordinates of the target frame (x1,y1), (x2,y2) are not in the picture, greater than width and height or less than 0.

For example, I printed (x1,y1), (x2,y2), and found that the coordinate y1 of the target frame in a picture was less than 0, so an error was reported.

Solution: Just change the out-of-bounds coordinates to boundary values:
(My image width and height are 1024 and 500)