python坐标定位_如何利用Python识别并定位图片中某一个色块的坐标?
依賴python包|opencv、numpy、aircv
第一步:查找圖片在原始圖片上的坐標(biāo)點(diǎn)
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
說(shuō)明:通過aircv的find_template()方法,來(lái)返回匹配圖片的坐標(biāo)結(jié)果
1.入?yún)?#xff1a;
find_template(原始圖像imsrc,待查找的圖片imobj,最低相似度confidence)
2.返回結(jié)果:
{'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)
confidence:匹配相似率
rectangle:匹配圖片在原始圖像上四邊形的坐標(biāo)
result:匹配圖片在原始圖片上的中心坐標(biāo)點(diǎn),也就是我們要找的點(diǎn)擊點(diǎn)
注意:如果結(jié)果匹配到的confidence小于入?yún)鬟f的相似度confidence,則會(huì)返回None,不返回字典
第二步:將圖片匹配的坐標(biāo)點(diǎn),轉(zhuǎn)換為手機(jī)屏幕上實(shí)際的坐標(biāo)點(diǎn)
因?yàn)榻貓D后在PC上的分辨率,和在手機(jī)上分辨率不一樣,而我們通過第一步求出的坐標(biāo)點(diǎn)是PC上截圖的坐標(biāo)點(diǎn),一般比手機(jī)上大很多,所以需要轉(zhuǎn)換一下坐標(biāo)
photo_position=self.driver.get_screenshot_as_file(imgfile)#截屏手機(jī)
x = self.driver.get_window_size()['width']
y = self.driver.get_window_size()['height']
size_width,size_height = x,y #獲得手機(jī)d的寬高尺寸
confidencevalue = 0.8 # 定義相似度
position = matchImg(imsrc,imobj,confidence)# 用第一步的方法,實(shí)際就是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)])
思路說(shuō)明:
1.通過appium的方法driver.get_screenshot_as_file(filename)進(jìn)行截圖
2.通過appium的get_window_size獲得寬高的字典,進(jìn)而得到寬和高
3.在PC上通過截圖和獲取到的手機(jī)屏截圖做匹配,返回匹配結(jié)果坐標(biāo)以及PC上原圖的尺寸
4.通過PC上截圖和手機(jī)上屏幕的寬高比,以及在PC上的實(shí)際坐標(biāo)點(diǎn),獲得手機(jī)上實(shí)際的坐標(biāo)點(diǎn)
5.最后通過appium的方法對(duì)手機(jī)上的坐標(biāo)進(jìn)行點(diǎn)擊drive.tap([x,y])
注意:為了匹配結(jié)果的精準(zhǔn)性,截圖最好在PC上原圖1:1下截圖,不要放大后截圖,否則相似度會(huì)差很多
第三步:優(yōu)化,截取手機(jī)上部分區(qū)域圖片,進(jìn)行相似度匹配,提高匹配精度
因?yàn)橛行﹫D片太小了,如果在一張大圖上進(jìn)行匹配,經(jīng)常匹配不到。那如果知道圖片出現(xiàn)的大概位置,可以截圖那個(gè)區(qū)域再進(jìn)行匹配
這里有兩種區(qū)域截圖方法:
1.根據(jù)appium定位到的元素進(jìn)行截圖
driver.find_element(*element).screenshot(imgfile)
2.根據(jù)截圖矩形左上角坐標(biāo)(百分比x,y)和寬高(百分比)截圖
Image.open(imgfile).crop((pc_location_x,pc_location_y,pc_location_x+pc_width,pc_location_y+pc_height)).save(imgfile)
先截取整個(gè)手機(jī)屏幕,然后根據(jù)百分比以及PC上截圖的寬高進(jìn)行計(jì)算,通過PIL的crop()方法截圖,獲得截圖上的坐標(biāo)
然后根據(jù)PC和手機(jī)上圖片的比例獲得手機(jī)上的坐標(biāo)
總結(jié)
以上是生活随笔為你收集整理的python坐标定位_如何利用Python识别并定位图片中某一个色块的坐标?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux系统起来时间,linux 系统
- 下一篇: python 用if判断一个数是不是整数