-1

I am trying to run a simple objection detection on webcam using Yolov5 but I keep getting the error below.

zsh: segmentation fault

The camera appears to open then shut off immediately and the code exit with the above error. Here is my code

def object_detector():
    DEVICE = "cuda" if torch.cuda.is_available() else "cpu" 
    model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
    # mmocr = MMOCR(det='TextSnake', recog='SAR')
    cam = cv2.VideoCapture(0)
    
    while(True): 
        ret, frame = cam.read()

        # ocr_result = mmocr.readtext(frame, output='demo/cam.jpg', export='demo/', print_result=True, imshow=True)
        # print("RESULT \n ", ocr_result)

        frame = frame[:, :, [2,1,0]]
        frame = Image.fromarray(frame) 
        frame = cv2.cvtColor(np.array(frame), cv2.COLOR_RGB2BGR)

        # ocr_result = mmocr.readtext(frame, output='demo/cam.jpg', export='demo/', print_result=True, imshow=True)
        # print("RESULT \n ", ocr_result)
        result = model(frame,size=640)
        # Results
        # crops = result.crop(save=True)
        cv2.imshow('YOLO', np.squeeze(result.render()))
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cam.release()
    cv2.destroyAllWindows()

what am i doing wrong and how can i fix it ?

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
e.iluf
  • 1,389
  • 5
  • 27
  • 69

2 Answers2

0

You're not testing the return value from cam.read() ensure that ret is a success code, and that frame is not a nullptr before you proceed.

argmi
  • 21
  • 1
  • 2
0

You need to check that an image is returned in the first place. The first return resulting from cam.read() tells you whether an image has been received. This is how you can make use of it:

...
while(True): 
    ret, frame = cam.read()
    if ret:
        frame = frame[:, :, [2,1,0]] 
        ...
        if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cam.release()
cv2.destroyAllWindows()
    
fabawi
  • 1