-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathred_color,py
More file actions
53 lines (41 loc) · 1.53 KB
/
red_color,py
File metadata and controls
53 lines (41 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# Convert to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Define red color range in HSV
lower_red1 = np.array([0, 120, 70])
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([170, 120, 70])
upper_red2 = np.array([180, 255, 255])
# Create masks
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
red_mask = cv2.bitwise_or(mask1, mask2)
# Clean the mask a bit
red_mask = cv2.medianBlur(red_mask, 5)
# Find contours in the mask
contours, _ = cv2.findContours(red_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
detected = False
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 1000: # Ignore small areas (noise)
x, y, w, h = cv2.boundingRect(cnt)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.putText(frame, "Red Object Detected", (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
detected = True
if not detected:
cv2.putText(frame, "No Red Object", (30, 50),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (100, 100, 100), 2)
# Show result
cv2.imshow("Red Object Detection", frame)
cv2.imshow("Red Mask", red_mask) # Optional: show binary red mask
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()