使用Python从OpenCV中获取颜色检测结果区域来获取屏幕坐标的步骤如下:
完整代码示例:
import cv2
import numpy as np
from pyautogui import position
# 读取屏幕截图并转换为HSV颜色空间
screenshot = cv2.imread('screenshot.png')
hsv = cv2.cvtColor(screenshot, cv2.COLOR_BGR2HSV)
# 定义颜色范围并创建掩膜
lower_color = np.array([0, 100, 100]) # 设置颜色下限
upper_color = np.array([10, 255, 255]) # 设置颜色上限
mask = cv2.inRange(hsv, lower_color, upper_color) # 创建掩膜
# 对掩膜进行形态学操作以去除噪点
kernel = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
# 寻找颜色区域的轮廓
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 遍历轮廓并获取其边界框
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(screenshot, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 获取屏幕坐标
screen_x, screen_y = position()
# 显示结果
cv2.imshow('Result', screenshot)
cv2.waitKey(0)
cv2.destroyAllWindows()
注意:在运行代码之前,需要先安装OpenCV和pyautogui库。
领取专属 10元无门槛券
手把手带您无忧上云