1- #!/usr/bin/env python3
1+ #!/usr/bin/env python3
2+
3+ import cv2
4+ import numpy as np
5+
6+ def detect_colors ():
7+ # Initialize Pi Camera (0 is usually the ribbon cable camera)
8+ cap = cv2 .VideoCapture (0 )
9+
10+ # Define HSV color ranges
11+ # Note: Hue ranges from 0-180 in OpenCV
12+ colors = {
13+ "RED" : {"lower" : [0 , 120 , 70 ], "upper" : [10 , 255 , 255 ]},
14+ "YELLOW" : {"lower" : [20 , 100 , 100 ], "upper" : [30 , 255 , 255 ]},
15+ "GREEN" : {"lower" : [35 , 100 , 100 ], "upper" : [85 , 255 , 255 ]},
16+ "CYAN" : {"lower" : [85 , 100 , 100 ], "upper" : [100 , 255 , 255 ]},
17+ "BLUE" : {"lower" : [100 , 150 , 0 ], "upper" : [140 , 255 , 255 ]},
18+ "PINK" : {"lower" : [140 , 100 , 100 ], "upper" : [170 , 255 , 255 ]}
19+ }
20+
21+ print ("KIDA Vision System Active. Press 'q' to exit." )
22+
23+ while True :
24+ ret , frame = cap .read ()
25+ if not ret :
26+ break
27+
28+ # Blur to reduce noise and convert to HSV
29+ blurred = cv2 .GaussianBlur (frame , (11 , 11 ), 0 )
30+ hsv = cv2 .cvtColor (blurred , cv2 .COLOR_BGR2HSV )
31+
32+ for color_name , range_val in colors .items ():
33+ lower = np .array (range_val ["lower" ])
34+ upper = np .array (range_val ["upper" ])
35+
36+ # Create a mask for the specific color
37+ mask = cv2 .inRange (hsv , lower , upper )
38+
39+ # Find contours (blobs) of that color
40+ contours , _ = cv2 .findContours (mask , cv2 .RETR_EXTERNAL , cv2 .CHAIN_APPROX_SIMPLE )
41+
42+ for cnt in contours :
43+ area = cv2 .contourArea (cnt )
44+ if area > 500 : # Only detect large enough objects
45+ x , y , w , h = cv2 .boundingRect (cnt )
46+ cv2 .rectangle (frame , (x , y ), (x + w , y + h ), (0 , 255 , 0 ), 2 )
47+ cv2 .putText (frame , color_name , (x , y - 10 ),
48+ cv2 .FONT_HERSHEY_SIMPLEX , 0.6 , (255 , 255 , 255 ), 2 )
49+
50+ # Show the output
51+ cv2 .imshow ("KIDA Vision - Color Detection" , frame )
52+
53+ if cv2 .waitKey (1 ) & 0xFF == ord ('q' ):
54+ break
55+
56+ cap .release ()
57+ cv2 .destroyAllWindows ()
58+
59+ if __name__ == "__main__" :
60+ detect_colors ()
0 commit comments