首先,代码导入了所需的库,包括 OpenCV (cv2
)、NumPy (np
)、PyAutoGUI (pyautogui
) 以及一些标准库如 time
和 os
。接着,定义了模板图片所在文件夹路径 template_dir
、检测阈值 threshold
,以及感兴趣区域(ROI)的坐标和大小。
然后,代码加载了指定文件夹中的所有模板图片,并将其转换为灰度图像,存储在 templates
列表中。在一个无限循环中,通过 pyautogui.screenshot
方法获取屏幕截图,并将其转换为灰度图像进行处理。
接着,对每个模板图片进行模板匹配,使用 cv2.matchTemplate
函数计算匹配结果,并通过阈值判断是否匹配成功。如果匹配值大于等于阈值,则输出匹配成功的信息。
最后,代码通过 time.sleep(0.1)
实现每次迭代之间的短暂延迟,以控制检测的频率。
import cv2
import numpy as np
import pyautogui
import time
import os
# Load the template images
template_dir = './weapon/1440/' # 模板图片所在的文件夹路径
template_files = [f for f in os.listdir(template_dir) if f.endswith('.png')]
# Define the detection threshold
threshold = 0.8
# Define the region of interest (ROI) coordinates
top_left = (2000, 1271)
bottom_right = (2496, 1368)
width = 496
height = 97
templates = []
for template_file in template_files:
template_path = os.path.join(template_dir, template_file)
template = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE)
templates.append((template, template_file))
while True:
screenshot = pyautogui.screenshot(region=(top_left[0], top_left[1], width, height))
screenshot = np.array(screenshot)
screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_RGB2GRAY)
for template, template_file in templates:
# Use template matching to find the template image within the screenshot
result = cv2.matchTemplate(screenshot_gray, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
if max_val >= threshold:
print(f"Checked: {os.path.splitext(template_file)[0]}")
# else:
# print("Not checked")d
time.sleep(0.1) # Wait for 100 milliseconds before the next iteration