src\loadsave.cpp:738: error: (-215:Assertion failed) !_img.empty() in function ‘cv::imwrite‘

cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:738: error: (-215:Assertion failed) !_img.empty() in function ‘cv::imwrite’

yolo检测到目标后,需要将目标剪切出来进行保存的时候报错:
cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp:738: error: (-215:Assertion failed) !_img.empty() in function ‘cv::imwrite’

原因:
如果只是原图剪切保存时:

cropped = im0[int(xyxy[1]) :int(xyxy[3]) , int(xyxy[0]) :int(xyxy[2]) ]

是不会出错的

我的错就错在我保存的图比目标框会大一些:

cropped = im0[int(xyxy[1]) - 100:int(xyxy[3]) + 100, int(xyxy[0]) - 100:int(xyxy[2]) + 100]

导致-100的时候就可能出界了。。。。。

所以保存的时候做个小判断,出界就按照目标框进行保存,

if int(xyxy[1])-100<0 or int(xyxy[0])-100<0:

    cropped = im0[int(xyxy[1]) :int(xyxy[3]) , int(xyxy[0]) :int(xyxy[2]) ]
    cv2.imwrite(
        '保存位置1' + str(label) + str(j) + '.jpg',
        cropped)
else:
    cropped = im0[int(xyxy[1]) - 100:int(xyxy[3]) + 100, int(xyxy[0]) - 100:int(xyxy[2]) + 100]
    cv2.imwrite('保存位置2' +str(label) + str(j) + '.jpg', cropped)                  

你可能感兴趣的:(python,深度学习,pycharm,python,深度学习,opencv)