find the center between the top left and bottom right coordinates and click there with…
- User
find the center between the top left and bottom right coordinates and click there with the mouse using pyautogui.
import cv2 import numpy as np import os import pyautogui import time
def find_character(character_images_folder): # Load character images from folder character_images = [] character_sizes = [] for filename in os.listdir(character_images_folder): if filename.endswith(".png") or filename.endswith(".jpg"): image_path = os.path.join(character_images_folder, filename) image = cv2.imread(image_path) character_images.append(image) character_sizes.append(image.shape[:2]) time.sleep(2) for i in range(5): # Capture screenshot of the screen screen = pyautogui.screenshot() frame = np.array(screen) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
code# Loop through each character image for character_img, character_size in zip(character_images, character_sizes): character_height, character_width = character_size # Find character in the frame result = cv2.matchTemplate(frame, character_img, cv2.TM_CCORR_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) # Set a threshold for character detection threshold = 0.965 # If character is found if max_val >= threshold: # Draw rectangle around the character top_left = max_loc bottom_right = (top_left[0] + character_width, top_left[1] + character_height) print("Detected Character: ", str(top_left), " / ", str(bottom_right)) cv2.rectangle(frame, top_left, bottom_right, (0, 255, 0), 2) cv2.putText(frame, "Character: " + str(max_val), (top_left[0], top_left[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) # Display the frame cv2.imshow("Character Detection", frame) #time.sleep(0.1) # Press "q" to exit if cv2.waitKey(1) & 0xFF == ord("q"): break - Assistant
To find the center between the top left and bottom right coordinates, you can use the following code after detecting the character:
code# Calculate the center coordinates center_x = (top_left[0] + bottom_right[0]) / 2 center_y = (top_left[1] + bottom_right[1]) / 2 # Click the center coordinates with the mouse pyautogui.click(center_x, center_y)This code will calculate the center coordinates by taking the average of the x and y coordinates of the top left and bottom right points. Then, it will use
pyautogui.click()to click on those coordinates with the mouse.