出于解放双手的想法,使用pyautogui对屏幕软件进行操作,静态图片识别很准确,但是对于实时运动的界面,图片识别就不稳定了。
一、解决思路:
获取屏幕截图后,使用像素对比实现两个图片找出相同的坐标,然后返回中心坐标。
下面开始代码实现。
二、实现思路:
需要的库PIL以及pyautogui
安装教程网上都有。。。
举例图片:左图为原图,右图为需要找的动态运动的图:
1.获取两张图的所有像素点的rgb
2.从左边途中找到右边图的左上角
3.以此为起点对比两张图的全部像素点是否相同(或者偏差在固定范围内)
4.符合条件返回中心坐标
代码如下:
# -*- coding: utf-8 -*-
"""
@Created: 2018/9/29 11:17
@AUTH: MeLeQ
@Used: pass
"""
import pyautogui
from PIL import Image
import timeit
aim_image = './pictures/aim_image.png' # 被找的小图
current_screen = './pictures/current_screen.png' # 原始大图
def to_position(file_name2):
# pyautogui找图速率做对比
res = pyautogui.locateCenterOnScreen(file_name2)
print(res)
return res
def get_position(file_name1, file_name2):
"""
:param file_name1: 原始大图
:param file_name2: 目标小图
:return:
"""
im1 = Image.open(file_name1)
im2 = Image.open(file_name2)
pix1 = im1.load()
pix2 = im2.load()
width1 = im1.size[0]
height1 = im1.size[1]
width2 = im2.size[0]
height2 = im2.size[1]
print(width1, height1)
print(width2, height2)
rgb2 = pix2[0, 0][:3] # 左上角起始点
for x in range(width1-width2):
for y in range(height1-height2):
rgb1 = pix1[x, y][:3]
if rgb1 == rgb2:
# 判断剩下的点是否相同
status = 0
# 图二的坐标是(s, j) --- (s-x, j-y)
# for s in range(x, x + width2): # 比对所有的点
for s in range(x, x + width2, 2): # 优化速度 每隔一个点检查一次
for j in range(y, y + height2, 2):
# 设置阈值范围
if abs(pix2[s - x, j - y][0] - pix1[s, j][0]) > 40 and abs(
pix2[s - x, j - y][1] - pix1[s, j][:3][1]) > 40 and abs(
pix2[s - x, j - y][2] - pix1[s, j][:3][2]) > 40:
status = 1
if status:
continue
else:
print(x + round(0.5 * width2), y + round(0.5 * height2))
return x + round(0.5 * width2), y + round(0.5 * height2)
return None
if __name__ == '__main__':
print(timeit.Timer(lambda: get_position(current_screen, aim_image)).timeit(5))
print("*****************")
print(timeit.Timer(lambda: to_position(aim_image)).timeit(5))
通过测试,发现动图可以精确的找到坐标,而且速度略胜与直接调用pyautogui的找坐标方法。
如果有更好的思路,希望可以一起交流~