现在不让篇幅太长了,分开写
我们平时点鼠标肯定都是先看到要打开的文件才去操作的,但我们怎么让程序知道要打开的文件在哪里呢,就需要屏幕截取的功能
pyautogui.screenshot() | 截取全屏 |
pyautogui.position() | 获取鼠标当前坐标 |
getpixel((100, 500)) | 获取指定坐标rpg值(颜色) |
pyautogui.pixelMatchesColor(100,500,(12,120,400)) | 基于坐标匹配颜色 |
import pyautoguiprint(pyautogui.position()) #获取鼠标当前坐标im=pyautogui.screenshot() #截取整个屏幕
im.save("123.png") #图片保存om=im.crop((284,416,302,438)) #选择性截取一段位置的图片
om.save("456.png") #保存截图
我们如果拿到上面的代码直接跑你会发现456.png 的截图是一个莫名其妙的位置,我们需要先给他一个准确的坐标,利用pyautogui.position()获取到准确的坐标后,再去设置截图的位置
技巧:将鼠标放到截图的位置中间最下面ctrl + F5 运行程序
im.crop((188,360,288,460))刚开始不太明白这个值是要怎么写,记录一下
前面两个值是188,360指的是坐标,我们上面不是截图全屏吗,im.crop是基于全屏截图去截取的
这种在这里前两个值(鼠标位置)就是起点,而后面两个值可以理解为我们截图要先点住起点
然后向右下角拖动的过程,我上面的案例就是在前面的坐标 加了100得到 100*100大小的截图
我们现在拿到了图片,剩下的就是从全屏来获取这个图片在那里了
方法 | 作用 |
pyautogui.locateOnScreen('1.png') | 识别单个图片坐标 |
pyautogui.locateAllOnScreen('1.png') | 识别多个图片坐标 |
import pyautogui# 图像识别(一个)
oneLocation = pyautogui.locateOnScreen('456.png')
print(oneLocation)# 图像识别(多个)
allLocation = pyautogui.locateAllOnScreen('456.png')
print(list(allLocation))
这里我们直接用上面案例截图出来的456.png图片
返回
Box(left=188, top=360, width=100, height=100)
[Box(left=188, top=360, width=100, height=100)]
可以看到和我们上面截图的坐标、大小是一致的
pyautogui自带的识别有时候不准,而且用截图工具的图片有时候也不好使,在网上找了个好使的备份一下
pip install numpy
pip install opencv-python
pip install opencv-contrib-python
#定义主类,
class ImageMatch:def __init__(self,Src,Srctempl):self.src = Srcself.srctempl = Srctempl#当前类的入口函数def main(self):result, imagebase, imagetempl = self.match(self.src, self.srctempl)X,Y=self.GetPoint(result,imagebase,imagetempl)return X,Y#获取匹配结果def match(self,src,srctempl):method=5#cv::TM_CCOEFF_NORMED = 5 标准相关匹配imagebase=cv2.imread(src)#self.show(imagebase ,"imagebase")# imagetempl = imagebase[15:137,134:183].copy()imagetempl=cv2.imread(srctempl)#self.show(imagetempl ,"imagetempl")print('imagetempl.shape:',imagetempl.shape)shape=imagetempl.shaperesult=cv2.matchTemplate(imagebase,imagetempl,method)print('result.shape:',result.shape)print('result.dtype:',result.dtype)return result,imagebase,imagetempl#获取匹配结果2#计算中心点位置def GetPoint(self,result,imagebase,imagetempl):method=5min_max = cv2.minMaxLoc(result)if method == 0 or method == 1: #根据不同的模式最佳匹配位置取值方法不同match_loc = min_max[2]else:match_loc = min_max[3]right_bottom = (match_loc[0] + imagetempl.shape[1], match_loc[1] + imagetempl.shape[0])print('result.min_max:',min_max,'method=',method)X=int(match_loc[0])+int((right_bottom[0]-match_loc[0])/2)Y=int(match_loc[1])+int((right_bottom[1]-match_loc[1])/2)print(X,Y)if method==5 and float(min_max[1])< 0.5:X=0Y=0#标注位置img_disp = imagebase.copy()cv2.rectangle(img_disp, match_loc,right_bottom, (0,255,0), 5, 8, 0 )cv2.normalize( result, result, 0, 255, cv2.NORM_MINMAX, -1 )cv2.circle(result, match_loc, 10, (255,0,0), 2 )return X,Ydef jietu(select_image):#截图是先截取当前页面的一张大图im = pyautogui.screenshot()im.save("global.png")src="./global.png"srctempl=select_imageimageMatch= ImageMatch(src,srctempl) #需要获取的小图X,Y = ImageMatch.main(imageMatch)return X,Y