如何从使用python从openCV获得的颜色检测结果区域获取屏幕坐标?

How to get screen coordinates from color detection resultant area obtained from openCV with python?

我正在尝试使用带有绿色笔尖的笔来使用网络摄像头导航鼠标光标,但我如何才能在屏幕上获取笔帽图像的坐标,以便我可以将其作为 pyinput 库移动函数的输入。

提前致谢。

# Python program for Detection of a
# specific color(green here) using OpenCV with Python

import cv2
import numpy as np
import time

cap = cv2.VideoCapture(0)


while (1):
    # Captures the live stream frame-by-frame

    _, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lower_red = np.array([75, 50, 50])
    upper_red = np.array([100, 255, 255])
    mask = cv2.inRange(hsv, lower_red, upper_red)
    res = cv2.bitwise_and(frame, frame, mask=mask)
    cv2.imshow('frame', frame)
    cv2.imshow('mask', mask)
    cv2.imshow('res', res)

    **#code to output coordinates of green pen tip**

    k = cv2.waitKey(5) & 0xff
    if k == 27:
        break

cv2.destroyAllWindows()
cap.release()

您已拥有所需的一切,只需再执行几个步骤:

首先找到你的mask中的非零点,它应该代表tip。

points = cv2.findNonZero(mask)

然后你可以对它们进行平均得到一个 "unique point" 代表小费。

avg = np.mean(points, axis=0)

现在,您可以将其标准化为 0-1 值,以后可以在任何分辨率下使用...或者您可以直接将其标准化为屏幕分辨率...

# assuming the resolutions of the image and screen are the following
resImage = [640, 480]
resScreen = [1920, 1080]

# points are in x,y coordinates
pointInScreen = ((resScreen[0] / resImage[0]) * avg[0], (resScreen[1] / resImage[1]) * avg[1] )

需要考虑的几点,首先记住opencv坐标系原点在左上角,指向右下方。

 ---->
|
|   image
|
v

根据您使用这些点坐标的位置和方式,您可能需要翻转轴....

其次,在 OpenCV 中,点在 x、y 中,并且(至少我手动编写的分辨率)在宽度和高度中……如果需要,您可能必须调整代码来处理这个问题:)

如果您有任何问题,请发表评论