Custom object detection from live webcam feed

Hello, I am using ImageAI for surgical item detection project. So far I could generate custom model to detect objects for offline images. Now I want to extend it for live detection from my PC webcam. Expectation is that I will bring the objects one by one in front of webcam and live predictions with bounding box will be displayed on the screen. I have tried it with custom object detection module and object detection from video codes, feeding my camera input. But it does not turn on webcam in my PC, but generates an AVI file at the end. Could you please help me on this? Is it possible to have video saved in mp4 format instead? Here is my code:

from imageai.Detection.Custom import CustomVideoObjectDetection

import os

import cv2

execution_path = os.getcwd()

camera = cv2.VideoCapture(0)

detector = CustomVideoObjectDetection()

detector.setModelTypeAsYOLOv3()

detector.setModelPath(os.path.join(execution_path , “medical/models/detection_model-ex-018–loss-0004.205.h5”))

detector.setJsonPath(“medical/json/detection_config.json”)

detector.loadModel()

video_path = detector.detectObjectsFromVideo(camera_input=camera,

output_file_path=os.path.join(execution_path, “camera_detected_video”)

, frames_per_second=20, log_progress=True, minimum_percentage_probability=50)

print(video_path)

1 Like

@NASH What operating system are you using?

  • If you on Windows, then camera = cv2.VideoCapture(0) should work fine
  • If you are using Ubuntu OS, kindly change the 0 to -1 , as in camera = cv2.VideoCapture(-1)

Let me know if this solves the problem.

Thank you for your reply. I am using Google Colab and tried changing to
camera = cv2.VideoCapture(-1). It is still same as before, webcam does not turn on and it saves an empty avi file in the directory. I have mounted Colab on my Google drive where the model is saved.

1 Like

@NASH You can’t load your Camera from Google Colab! You have to run your code on your machine.

Thanks so much…I should have though that before. Sorry!