Save detected images error

for i in range(len(boxes)):
        if i in indexes:
            x, y, w, h = boxes[i]
            label = str(classes[class_ids[i]])
            color = colors[class_ids[i]]
            cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
            cv2.putText(img, label, (x, y + 30), font, 3, color, 2)
            crop_img = img[y: y + h, x: x + w]
            if label == 'wearing':
                wearing = wearing+1
                wearing_count = wearing_count+1
                cv2.imwrite(os.path.join(output_crop_wearing,str(x)+'.jpg'),crop_img)
            elif label == 'notwearing':
                notwearing = notwearing+1
                notwearing_count = notwearing_count+1
                cv2.imwrite(os.path.join(output_crop_notwearing,str(x)+'.jpg'),crop_img)
Traceback (most recent call last):
  File "/model/test_yolo_object_detection.py", line 143, in <module>
    cv2.imwrite(os.path.join(output_crop_wearing,str(x)+'.jpg'),crop_img)
cv2.error: OpenCV(4.5.1) /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-39p1qqfs/opencv/modules/imgcodecs/src/loadsave.cpp:753: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'

I looped through the input images folder and there are some folder that show the error like this

I tried print the value of x,y,w,h
everytime loop stop at when x= -1, y= 193, w= 8, h= 12
I thought that it because the negative x
so I set the condition if any of them is negative I will set that value to 1
but the error still occur as the same

please update your question code, then

(and yes, YOLO networks can return out-of-bounds coords, so it’s a good idea to be cautious)

if x < 0:
                    x = 1
                if y < 0:
                    y = 1
                if w < 0:
                    w = 1
                if h < 0:
                    h = 1
                print("x= "+str(x)+" y= "+str(y)+" w= "+str(w)+" h= "+str(h))

I just set things like this in each if condition ‘wearing’ and ‘notwearing’

even the value is no longer negative but it still shown error

x= 1 y= 193 w= 8 h= 12
Traceback (most recent call last):
  File "/Users/khemakorn/Desktop/model/test_yolo_object_detection.py", line 152, in <module>
    cv2.imwrite(os.path.join(output_crop_wearing,str(x)+'.jpg'),crop_img)
cv2.error: OpenCV(4.5.1) /private/var/folders/nz/vv4_9tw56nv9k3tkvyszvwg80000gn/T/pip-req-build-39p1qqfs/opencv/modules/imgcodecs/src/loadsave.cpp:753: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'

that’s too late (and no need to duplicate that)
you have to check bounds before cropping the image
please also check, if your crop is valid

Oh it works correctly now, Thanks.