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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| import cv2 import numpy as np
COLOR_RANGES = { 'red': (np.array([160, 100, 100]), np.array([180, 255, 255])), 'green': (np.array([40, 70, 70]), np.array([80, 255, 255])), 'blue': (np.array([100, 150, 0]), np.array([140, 255, 255])) }
cap = cv2.VideoCapture(0)
while True: ret, frame = cap.read() if not ret: break
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
for color_name, (lower, upper) in COLOR_RANGES.items(): mask = cv2.inRange(hsv, lower, upper)
kernel = np.ones((5, 5), np.uint8) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
blurred = cv2.GaussianBlur(mask, (15, 15), 0)
contours, _ = cv2.findContours(blurred, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours: area = cv2.contourArea(contour) if area > 50: (x, y), radius = cv2.minEnclosingCircle(contour) center = (int(x), int(y)) radius = int(radius)
distance = 200 / (radius + 1)
if 190 <= distance <= 210: color = (0, 255, 0) if color_name == 'green' else (255, 0, 0) if color_name == 'blue' else (0, 0, 255) cv2.circle(frame, center, radius, color, 2) cv2.putText(frame, f"{color_name.capitalize()} Laser - Distance: {distance:.2f} cm", (center[0] - 20, center[1] - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
cv2.imshow("Laser Pointer Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'): break
cap.release() cv2.destroyAllWindows()
|