use object detector with camera feed in python

Here's an example code on how to use object detection with camera feed in Python using OpenCV:

main.py
import cv2

#Load the pre-trained model
model = cv2.dnn.readNetFromTensorflow('frozen_inference_graph.pb', 'ssd_mobilenet_v2_coco_2018_03_29.pbtxt')

#Define the classes for object detection
classNames = {0: 'background', 1: 'person', 2: 'bicycle', 3: 'car', 4: 'motorcycle',
              5: 'airplane', 6: 'bus', 7: 'train', 8: 'truck', 9: 'boat'}

#Create a video capture object
cap = cv2.VideoCapture(0)

while True:
    #Read the frames from the camera feed
    ret, frame = cap.read()

    #Create OpenCV blob from the input frame
    blob = cv2.dnn.blobFromImage(frame, size=(300, 300), swapRB=True)

    #Set the input blob to the model
    model.setInput(blob)

    #Perform object detection on the input frame
    detections = model.forward()

    #Loop through the detections and draw the bounding boxes
    for i in range(0, detections.shape[2]):
        confidence = detections[0, 0, i, 2]

        #Filter out weak detections
        if confidence > 0.5:
            classId = int(detections[0, 0, i, 1])
            className = classNames[classId]

            #Get the bounding box coordinates
            box = detections[0, 0, i, 3:7] * numpy.array([frame.shape[1], frame.shape[0], frame.shape[1], frame.shape[0]])
            (startX, startY, endX, endY) = box.astype("int")

            #Draw the bounding box and label on the frame
            cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 2)
            y = startY - 15 if startY - 15 > 15 else startY + 15
            cv2.putText(frame, className, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    #Show the output
    cv2.imshow('Object Detection using OpenCV', frame)

    #Exit on 'q' press
    if cv2.waitKey(1) == ord('q'):
        break

#Release the video capture object and destroy all windows
cap.release()
cv2.destroyAllWindows()
1848 chars
54 lines

This code loads a pre-trained object detection model and applies it to the camera feed. The detections are drawn on the output frame with bounding box and label. Pressing 'q' will exit the program.

gistlibby LogSnag