Running Object Detection With Python
Running a pretrained YOLO model for object detection using Python.
12 min•By Priygop Team•Updated 2026
Object Detection with OpenCV DNN
Object Detection with OpenCV DNN
import cv2
import numpy as np
# Using OpenCV's DNN module with a pretrained model
# Download: MobileNet SSD pretrained on COCO
def load_coco_detector():
"""Load a MobileNet SSD detector pretrained on COCO."""
# Class names (COCO 80 classes)
coco_classes = [
"background", "person", "bicycle", "car", "motorbike",
"aeroplane", "bus", "train", "truck", "boat",
"traffic light", "fire hydrant", "stop sign", "parking meter", "bench",
"bird", "cat", "dog", "horse", "sheep",
"cow", "elephant", "bear", "zebra", "giraffe",
# ... 80 total classes
]
return coco_classes
def detect_objects_dnn(image_path, confidence_threshold=0.5):
"""
Run object detection using OpenCV DNN.
This uses a Caffe MobileNet SSD model.
Download model files:
- deploy.prototxt
- mobilenet_iter_73000.caffemodel
"""
coco_classes = load_coco_detector()
image = cv2.imread(image_path)
h, w = image.shape[:2]
# Load model (requires downloaded model files)
# net = cv2.dnn.readNetFromCaffe("deploy.prototxt",
# "mobilenet_iter_73000.caffemodel")
# Prepare image for network
blob = cv2.dnn.blobFromImage(
cv2.resize(image, (300, 300)),
scalefactor=0.007843,
size=(300, 300),
mean=127.5
)
# net.setInput(blob)
# detections = net.forward()
# Process detections
# for i in range(detections.shape[2]):
# confidence = detections[0, 0, i, 2]
# if confidence > confidence_threshold:
# class_id = int(detections[0, 0, i, 1])
# box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
# (x1, y1, x2, y2) = box.astype("int")
# label = f"{coco_classes[class_id]}: {confidence:.2f}"
# cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
# cv2.putText(image, label, (x1, y1-10),
# cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
print("Detection pipeline ready")
print("Requires: deploy.prototxt + mobilenet_iter_73000.caffemodel")
return image
detect_objects_dnn("photo.jpg")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment