Python图⽚识别坐标(appium通过识别图⽚点击坐标)
***如果只想了解图⽚相似度识别,直接看第⼀步即可
***如果想了解appium根据图⽚识别点击坐标,需要看第⼀、⼆、三步
背景|在做UI测试时,发现iOS⾃定义的UI控件,appium识别不到。所以考虑通过识别图⽚坐标,进⽽通过点击坐标解决问题
依赖python包|opencv、numpy、aircv
第⼀步:查图⽚在原始图⽚上的坐标点
import aircv as ac
def matchImg(imgsrc,imgobj,confidencevalue=0.5):#imgsrc=原始图像,imgobj=待查的图⽚
imsrc = ac.imread(imgsrc)
imobj = ac.imread(imgobj)
match_result = ac.find_template(imsrc,imobj,confidence)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)} if match_result is not None:
match_result['shape']=(imsrc.shape[1],imsrc.shape[0])#0为⾼,1为宽
return match_result
说明:通过aircv的find_template()⽅法,来返回匹配图⽚的坐标结果
1.⼊参:
find_template(原始图像imsrc,待查的图⽚imobj,最低相似度confidence)
2.返回结果:
{'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)
confidence:匹配相似率
rectangle:匹配图⽚在原始图像上四边形的坐标
result:匹配图⽚在原始图⽚上的中⼼坐标点,也就是我们要的点击点
注意:如果结果匹配到的confidence⼩于⼊参传递的相似度confidence,则会返回None,不返回字典
参考⽂档:
第⼆步:将图⽚匹配的坐标点,转换为⼿机屏幕上实际的坐标点
因为截图后在PC上的分辨率,和在⼿机上分辨率不⼀样,⽽我们通过第⼀步求出的坐标点是PC上截图的坐标点,⼀般⽐⼿机上⼤很多,所以需要转换⼀下坐标
photo_position=_screenshot_as_file(imgfile)#截屏⼿机
x = _window_size()['width']
y = _window_size()['height']
size_width,size_height = x,y #获得⼿机d的宽⾼尺⼨
confidencevalue = 0.8  # 定义相似度
position = matchImg(imsrc,imobj,confidence)# ⽤第⼀步的⽅法,实际就是find_template()⽅法
if position != None:
x, y = position['result']
shape_x, shape_y = tuple(map(int,position['shape']))
position_x,position_y=int(photo_position_x+(photo_width/shape_x*x)),int(photo_position_y+(photo_height/shape_y*y))
self.driver.tap([(position_x, position_y)])
思路说明:
1.通过appium的⽅法_screenshot_as_file(filename)进⾏截图
2.通过appium的get_window_size获得宽⾼的字典,进⽽得到宽和⾼
3.在PC上通过截图和获取到的⼿机屏截图做匹配,返回匹配结果坐标以及PC上原图的尺⼨
4.通过PC上截图和⼿机上屏幕的宽⾼⽐,以及在PC上的实际坐标点,获得⼿机上实际的坐标点
5.最后通过appium的⽅法对⼿机上的坐标进⾏点击drive.tap([x,y])
注意:为了匹配结果的精准性,截图最好在PC上原图1:1下截图,不要放⼤后截图,否则相似度会差很多
第三步:优化,截取⼿机上部分区域图⽚,进⾏相似度匹配,提⾼匹配精度
因为有些图⽚太⼩了,如果在⼀张⼤图上进⾏匹配,经常匹配不到。那如果知道图⽚出现的⼤概位置,可以截图那个区域再进⾏匹配这⾥有两种区域截图⽅法:
1.根据appium定位到的元素进⾏截图
python能在手机上运行吗driver.find_element(*element).screenshot(imgfile)
2.根据截图矩形左上⾓坐标(百分⽐x,y)和宽⾼(百分⽐)截图
Image.open(imgfile).crop((pc_location_x,pc_location_y,pc_location_x+pc_width,pc_location_y+pc_height)).save(imgfile)
先截取整个⼿机屏幕,然后根据百分⽐以及PC上截图的宽⾼进⾏计算,通过PIL的crop()⽅法截图,获得截图上的坐标
然后根据PC和⼿机上图⽚的⽐例获得⼿机上的坐标