import cv2
import numpy as np
from time import time, sleep
import pyautogui
import os
pyautogui.PAUSE = 0
base_dir = r'C:\Users\ismail sk\Pictures\ship_folder'
templates = []
for i in range(1, 7):
ship_type_dir = os.path.join(base_dir, f'ship_{i}')
if not os.path.exists(ship_type_dir):
continue
for file in os.listdir(ship_type_dir):
if file.endswith('.png'):
templates.append(os.path.join(ship_type_dir, file))
if not templates:
print("No template images found. Exiting...")
exit()
sct = cv2.mss.mss()
monitor = {"top": 204, "left": 728, "width": 370, "height": 712}
fps_time = time()
while True:
start_time = time()
sct_img = sct.grab(monitor)
frame = np.array(sct_img)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
detected = False
for template_path in templates:
template_img = cv2.imread(template_path, 0)
if template_img is None:
continue
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
res = cv2.matchTemplate(gray_frame, template_img, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(res)
if max_val > 0.85:
detected = True
w, h = template_img.shape[::-1]
center_x, center_y = max_loc[0] + w // 2, max_loc[1] + h // 2
pyautogui.moveTo(center_x + monitor["left"], center_y + monitor["top"])
pyautogui.click()
cv2.rectangle(frame, max_loc, (max_loc[0] + w, max_loc[1] + h), (0, 255, 255), 2)
sleep(0.10)
break
cv2.imshow('Screen Shot', frame)
cv2.waitKey(1)
print(f"Frame processing time: {time() - start_time} seconds")
sleep(0.01)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print(f'FPS: {1 / (time() - fps_time):.2f}')
fps_time = time()
cv2.destroyAllWindows()