piekenius' Blog

Code for Winter Hacker

Word count: 368Reading time: 2 min
2024/10/28

This is the code for winter hacker. Also feel free to visit any place of my Blog^^

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 for laser pointers (covering common colors such as red, green, and blue)
COLOR_RANGES = {
'red': (np.array([160, 100, 100]), np.array([180, 255, 255])), # Red
'green': (np.array([40, 70, 70]), np.array([80, 255, 255])), # Green
'blue': (np.array([100, 150, 0]), np.array([140, 255, 255])) # Blue
}

# Initialize the camera
cap = cv2.VideoCapture(0)

while True:
# Read a frame
ret, frame = cap.read()
if not ret:
break

# Convert to HSV color space
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

for color_name, (lower, upper) in COLOR_RANGES.items():
# Apply color thresholds to create a mask
mask = cv2.inRange(hsv, lower, upper)

# Use morphological opening to remove small noise
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

# Apply Gaussian blur to smooth the mask
blurred = cv2.GaussianBlur(mask, (15, 15), 0)

# Find contours
contours, _ = cv2.findContours(blurred, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Iterate through contours
for contour in contours:
area = cv2.contourArea(contour)

# Filter out noise based on area
if area > 50: # Adjust the area threshold based on experimentation to filter out noise
# Get the smallest enclosing circle
(x, y), radius = cv2.minEnclosingCircle(contour)
center = (int(x), int(y))
radius = int(radius)

# Calculate the distance (assuming calibration through actual measurement)
distance = 200 / (radius + 1) # Adjust the formula based on experimental results

# Check if within the valid distance range
if 190 <= distance <= 210:
# Draw different colors for laser spots of different colors
color = (0, 255, 0) if color_name == 'green' else (255, 0, 0) if color_name == 'blue' else (0, 0, 255)

# Draw a circular marker and color label on the frame
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)

# Display the image
cv2.imshow("Laser Pointer Detection", frame)

# Exit on key press
if cv2.waitKey(1) & 0xFF == ord('q'):
break

# Release resources
cap.release()
cv2.destroyAllWindows()
CATALOG