PyAutoGUI无法检测卡牌游戏特定卡牌的技术求助
卡牌游戏机器人无法识别oneheart、tenheart卡牌的问题
我正在开发一款自动运行卡牌游戏的机器人,目前仅能检测到shuffle卡牌,无法识别oneheart、tenheart卡牌。代码如下:
def locateandClick(): oneheart = pyautogui.locateOnScreen('oneheart.png', grayscale=False, confidence=0.6) tenheart = pyautogui.locateOnScreen('tenheart.png', grayscale=False, confidence=0.6) shuffle = pyautogui.locateOnScreen('shuffle.png', grayscale=False, confidence=0.6) if oneheart and tenheart: one = pyautogui.center(oneheart) ten = pyautogui.center(tenheart) pyautogui.moveTo(ten[0], ten[1]) pyautogui.mouseDown() pyautogui.mouseUp() pyautogui.moveTo(one[0], one[1]) pyautogui.mouseDown() pyautogui.mouseUp() if not oneheart and not tenheart and shuffle: shufflecenter = pyautogui.center(shuffle) pyautogui.moveTo(shufflecenter[0], shufflecenter[1]) pyautogui.mouseDown() pyautogui.mouseUp() while True: locateandClick()
我已安装OpenCV以支持confidence参数,但问题仍存在。相关卡牌截图:
- shuffle卡牌:

- oneheart卡牌:

- tenheart卡牌:

解决方案
调整匹配参数
- 降低置信度阈值:将
confidence=0.6下调至0.5或更低。oneheart、tenheart卡牌的图案细节更多,屏幕显示时可能存在细微色差或渲染差异,高阈值会直接过滤掉匹配结果。 - 启用灰度匹配:把
grayscale=False改为True,忽略颜色干扰。游戏内卡牌颜色可能因窗口缩放、显卡渲染出现细微变化,灰度匹配能提升兼容性。
优化模板图片
- 重新截取模板:直接从游戏前台截取
oneheart.png和tenheart.png,确保无多余边框、背景,仅保留卡牌核心识别区域(数字+红心图案),避免无关区域影响匹配精度。 - 对齐尺寸:确保模板图片尺寸与游戏内实际显示的卡牌完全一致,窗口缩放会导致卡牌尺寸变化,尺寸不匹配会直接导致locateOnScreen失败。
代码逻辑排查
- 单独验证匹配:编写测试脚本单独验证单卡牌匹配情况,确认是匹配问题还是逻辑判断问题:
import pyautogui # 测试oneheart匹配 result = pyautogui.locateOnScreen('oneheart.png', grayscale=True, confidence=0.5) print("oneheart匹配结果:", result) # 测试tenheart匹配 result = pyautogui.locateOnScreen('tenheart.png', grayscale=True, confidence=0.5) print("tenheart匹配结果:", result)
- 调整条件逻辑:原代码仅在
oneheart和tenheart同时存在时执行点击逻辑,若场景中仅存在其中一张卡牌,会直接跳过。可根据游戏规则调整逻辑,支持单卡牌的识别与操作。
额外注意事项
- 确保游戏窗口处于前台:pyautogui的屏幕识别依赖前台窗口,游戏被遮挡或最小化时无法正常识别。
- 关闭游戏特效:部分游戏的抗锯齿、动态特效会导致卡牌边缘模糊,关闭后可提升模板匹配的准确性。
内容的提问来源于stack exchange,提问作者JorgTV
相关产品推荐
相关产品推荐

