0

enter image description hereI have a code here that tracks a laser dot.What I want is to get the x and y coordinates of the laser dot and store it to separate variables. Here is the code:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while (1):

    # Take each frame
    ret, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    lower_red = np.array([0, 0, 255])
    upper_red = np.array([255, 255, 255])
    mask = cv2.inRange(hsv, lower_red, upper_red)
    cv2.imshow('mask', mask)
    cv2.imshow('Track Laser', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
jomsamago
  • 27
  • 1
  • 8

1 Answers1

1

For multiple points or noisier data, you might want to consider clustering algorithms.

However, the image you attached is quite clear. All you need to do is find the center of it. That corresponds the the first geometrical moment (aka mean):

moments = cv2.moments(hsv[:, :, 2])
x = int(moments['m10'] / moments['m00'])
y = int(moments['m01'] / moments['m00'])

This lets us find the center fairly accurately, provided there are no outliers (e.g. noise or other circles) affecting the distribution.

enter image description here


Perhaps a more robust method (to noise and number of circles) would make use of Hough circles.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135