Object Detection Mini Project
Build a complete object detection and counting system.
12 min•By Priygop Team•Updated 2026
Object Counter and Reporter
Object Counter and Reporter
from ultralytics import YOLO
import cv2
from collections import Counter
def count_objects_in_image(image_path, model_path="yolov8n.pt",
confidence=0.5):
"""
Detect, count, and report all objects in an image.
"""
model = YOLO(model_path)
results = model(image_path, conf=confidence)
image = cv2.imread(image_path)
all_detections = []
for result in results:
for box in result.boxes:
class_name = model.names[int(box.cls[0])]
conf = float(box.conf[0])
x1, y1, x2, y2 = [int(v) for v in box.xyxy[0].tolist()]
all_detections.append({
"class": class_name,
"confidence": conf,
"bbox": (x1, y1, x2-x1, y2-y1)
})
# Count objects by class
class_counts = Counter(d["class"] for d in all_detections)
print(f"=== Object Detection Report: {image_path} ===")
print(f"Total objects detected: {len(all_detections)}")
print()
print("Object counts:")
for cls, count in sorted(class_counts.items(), key=lambda x: -x[1]):
avg_conf = sum(d["confidence"] for d in all_detections if d["class"] == cls) / count
print(f" {cls:15s}: {count} (avg confidence: {avg_conf:.1%})")
print()
print("Individual detections:")
for d in sorted(all_detections, key=lambda x: -x["confidence"]):
print(f" {d['class']:15s}: {d['confidence']:.1%}")
return all_detections, class_counts
count_objects_in_image("street_photo.jpg")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment
Key Takeaways from Module 9
- Object detection outputs: class label + bounding box + confidence score for each detected object
- YOLO (You Only Look Once) processes the entire image in a single pass — enabling real-time detection
- Confidence threshold filters detections — start at 0.5, increase to reduce false positives
- NMS (Non-Maximum Suppression) removes duplicate overlapping boxes for the same object
- YOLOv8 via Ultralytics is the easiest way to run high-quality detection in Python
- OpenCV DNN module can run pretrained Caffe and ONNX models for detection
- COCO dataset provides 80 common classes — person, car, bicycle, dog, chair, and more
Key Takeaways
- Build a complete object detection and counting system.
- Object detection outputs: class label + bounding box + confidence score for each detected object
- YOLO (You Only Look Once) processes the entire image in a single pass — enabling real-time detection
- Confidence threshold filters detections — start at 0.5, increase to reduce false positives