OpenCV+Python实现APEX枪械自动识别

本文介绍了如何利用Python的OpenCV、NumPy和PyAutoGUI库,通过读取模板图片并在屏幕截图中进行匹配,实现实时武器检测。代码定义了模板图片路径、阈值和ROI,不断获取屏幕截图并与模板进行比较,输出匹配成功的武器名称。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,代码导入了所需的库,包括 OpenCV (cv2)、NumPy (np)、PyAutoGUI (pyautogui) 以及一些标准库如 timeos。接着,定义了模板图片所在文件夹路径 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值