Practical Segmentation Project
Build a complete object counting system using segmentation.
12 min•By Priygop Team•Updated 2026
Object Counter with Segmentation
Object Counter with Segmentation
import cv2
import numpy as np
def count_and_measure_objects(image_path):
"""
Segments an image and counts distinct objects,
reporting their size and position.
"""
image = cv2.imread(image_path)
if image is None:
print("Could not load image")
return
h, w = image.shape[:2]
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (7, 7), 0)
# Segment
_, binary = cv2.threshold(blurred, 0, 255,
cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
kernel = np.ones((5, 5), np.uint8)
cleaned = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
cleaned = cv2.morphologyEx(cleaned, cv2.MORPH_CLOSE, kernel)
contours, _ = cv2.findContours(
cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
print(f"=== Object Analysis: {image_path} ===")
result = image.copy()
objects = []
for i, contour in enumerate(contours):
area = cv2.contourArea(contour)
if area < 500:
continue
x, y, cw, ch = cv2.boundingRect(contour)
cx = x + cw // 2
cy = y + ch // 2
perimeter = cv2.arcLength(contour, True)
objects.append({"id": i, "area": area, "x": cx, "y": cy, "w": cw, "h": ch})
cv2.rectangle(result, (x,y), (x+cw,y+ch), (0,255,0), 2)
cv2.putText(result, f"#{len(objects)}", (x, y-5),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)
print(f"Objects found: {len(objects)}")
for obj in objects:
print(f" Object {obj['id']}: area={obj['area']:.0f}px, centre=({obj['x']},{obj['y']})")
cv2.imwrite("objects_counted.jpg", result)
return objects
count_and_measure_objects("your_photo.jpg")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment
Key Takeaways from Module 6
- Segmentation divides an image into regions — binary (foreground/background) or multi-class
- Threshold segmentation is the fastest method — use Otsu's threshold when unsure of the correct value
- Colour segmentation with HSV masks is effective for objects with distinctive colours
- Morphological operations (OPEN, CLOSE) clean up segmentation masks before extraction
- Contour-based extraction lets you isolate each object individually into its own image
- GrabCut provides semi-automatic background removal with just a bounding box
- Background subtraction works for video when a clean background frame is available
Key Takeaways
- Build a complete object counting system using segmentation.
- Segmentation divides an image into regions — binary (foreground/background) or multi-class
- Threshold segmentation is the fastest method — use Otsu's threshold when unsure of the correct value
- Colour segmentation with HSV masks is effective for objects with distinctive colours