Hello, I am trying to track this green dot in python, I cannot figure out the HSV colors, here's a photo of the dot, and I will attach the script:
import cv2
import numpy as np
import math
Load reference image
ref_img = cv2.imread(r'C:\Users\nicho\PycharmProjects\SpellCaster.venv\Spell Referance\leviosa.png')
Open webcam
cap = cv2.VideoCapture(0)
Create display window
cv2.namedWindow('Webcam')
Initialize line coordinates
line_x = []
line_y = []
while True:
# Read frame
ret, frame = cap.read()
# Convert to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Define green color range
lower_green = np.array([40, 100, 100])
upper_green = np.array([70, 255, 255])
# Threshold image
mask = cv2.inRange(hsv, lower_green, upper_green)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8))
# Find contours and filter
contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)
if len(contours) > 0:
# Get largest contour
c = contours[0]
# Calculate moments and check for zero
M = cv2.moments(c)
if M['m00'] != 0:
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])
# Append center points
line_x.append(cx)
line_y.append(cy)
# Draw line on frame
for i in range(1, len(line_x)):
cv2.line(frame, (line_x[i - 1], line_y[i - 1]), (line_x[i], line_y[i]), (0, 255, 0), 2)
else:
# No contours, skip processing
pass
# Display webcam feed
cv2.imshow('Webcam', frame)
# Check if line matches reference
if len(line_x) > 10:
ref_pts = np.column_stack((line_x, line_y))
ref_pts = ref_pts.astype(np.int32)
ref_dist = cv2.arcLength(ref_pts, True)
sample_pts = np.column_stack((np.linspace(0, ref_img.shape[1], num=len(line_x)),
np.interp(np.linspace(0, ref_img.shape[1], num=len(line_x)), line_x,
line_y))).astype(np.int32)
sample_dist = cv2.arcLength(sample_pts, True)
deviation = abs(ref_dist - sample_dist) / ref_dist
if deviation < 0.1:
print("Spell cast!")
break
# Check for ESC key to exit
k = cv2.waitKey(1)
if k % 256 == 27:
break
Release resources
cap.release()
cv2.destroyAllWindows()