Skip to content

Instantly share code, notes, and snippets.

@saharshg29
Created October 4, 2023 20:19
Show Gist options
  • Save saharshg29/f1133d8e8d86666294229e405e698ea0 to your computer and use it in GitHub Desktop.
Save saharshg29/f1133d8e8d86666294229e405e698ea0 to your computer and use it in GitHub Desktop.
My first realtime object detection using OpenCV
import cv2
import numpy as np
def detect_boxes(image):
# Convert image to HSV color space
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Define range for brown color in HSV
lower_brown = np.array([10, 50, 50])
upper_brown = np.array([20, 255, 255])
mask = cv2.inRange(hsv, lower_brown, upper_brown)
# Morphological operations to clean the mask
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
epsilon = 0.02 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
if len(approx) == 4 and cv2.contourArea(contour) > 500:
cv2.drawContours(image, [approx], -1, (0, 255, 0), 2)
cv2.putText(image, "Box", (approx[0][0][0], approx[0][0][1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
return image
cap = cv2.VideoCapture(2)
while True:
ret, frame = cap.read()
if not ret:
break
result = detect_boxes(frame)
cv2.imshow("Box Detection", result)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment