#🔒 Can't figure out how to track green dot.

14 messages · Page 1 of 1 (latest)

misty whale
#

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()

gilded lodgeBOT
#

@misty whale

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

misty whale
#

I had it working with a red dot, but it would confuse it for other things in my room

stable cliff
#

did you change color range for green?

misty whale
#

i’ve never used it before so i don’t know what color range it should be set tt

#

to

stable cliff
#

look up what is HSV color space and how it differs from RGB

misty whale
#

yes i got that but i just cant seem to find the right color

stable cliff
#
import cv2
import matplotlib.pyplot as plt

BGR = cv2.imread(r'e:\relocated\Downloads\Screenshot_2024-03-15_134750.png', flags=cv2.IMREAD_COLOR)
hsv = cv2.cvtColor(BGR, cv2.COLOR_BGR2HSV)

fig, ax = plt.subplots(1,3, figsize = (10,3), facecolor = 'black')

for channel in range(3):
    im = ax[channel].imshow(hsv[:,:,channel], 'gray')
    ax[channel].axis('off')
    ax[channel].set_title(f'channel: {channel}', color = 'white')
plt.colorbar(im)
stable cliff
gilded lodgeBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.