此代码的目标是找到与给定颜色阈值匹配的所有对象,然后打印出每个匹配项的x,y坐标。
import cv2
import numpy as np
import pyautogui
# Takes a screen shot and saves the file in the specified location
screenshot = (r'C:\Users\Ian\Pictures\Capture.png')
pyautogui.screenshot(screenshot)
# Reads the screen shot
img = cv2.imread(screenshot)
# convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Range of mask 1 Blue, Green, Red
lower_red = np.array([10, 90, 115])
upper_red = np.array([22, 110, 185])
mask1 = cv2.inRange(hsv,lower_red,upper_red)
# Final Mask
target = cv2.bitwise_and(img,img, mask=mask1)
# Finds location of matched image
points = cv2.findNonZero(mask1)
avg = np.mean(points, axis=0)
avg_array = (avg[0])
print(points)
# Resolution of image and screen
resImage = [640, 480]
resScreen = [1920, 1080]
print(avg)
# moves mouse to center of image to check if image found correctly
loc_image_x = avg_array[0]
loc_image_y = avg_array[1]
pyautogui.moveTo(loc_image_x, loc_image_y,.5)
# Shows image while one key press closes it
cv2.imshow('Image', target)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
这是在我的代码中正确检测到的三个对象(有些杂音)。 如何找到每个对象的x,y坐标?例如[250 380],[453 784],[876、245]