24
11月
2021
def gui_wait_image(img_path, region=None, timeout=5, confidence=None, raise_error=True):
"""
:param timeOut:图片查找超时时间
:param img_path:图片路径
:param region:格式 region=(0, 0, 810, 630) 限制搜索图片的区域
:param confidence:模糊匹配相似度 不传值为默认相似度 数据类型为数字,范围为0到1
:return:成功:True 失败:False
"""
status = False
try:
print("开始识别图片 {}".format(img_path))
search_count = 0
while search_count < timeout:
search_count += 1
print('当前第{}次查找图片'.format(search_count))
if confidence: # 如果confidence传值了 则相似度使用confidence的值
img_pos_center = pyautogui.locateCenterOnScreen(img_path, region=region, confidence=confidence)
else: # 如果confidence未传值 则使用默认相似度
img_pos_center = pyautogui.locateCenterOnScreen(img_path, region=region, )
if img_pos_center: # 搜索到图片位置
status = True
print('识别图片成功 {}'.format(img_path))
break
time.sleep(1)
if not status:
print('执行{}秒内没有找到图片'.format(timeout, img_path))
if raise_error:
raise Exception('执行{}秒内没有找到图片:{}'.format(timeout, img_path))
except Exception as e:
if raise_error:
raise e
status = False
return status
def gui_wait_image_click(img_path, OffsetX=0, OffsetY=0, region=None, timeout=5, sign=False, homing=True,
confidence=None,
double_click=False, right_click=False, raise_error=True):
"""
:param img_path:图片路径
:param OffsetX:x偏移
:param OffsetY:y偏移
:param sign: 点击图片后移动到初始坐标后是否点击
:param timeOut:图片查找超时时间
:param region:格式 region=(0, 0, 810, 630) 限制搜索图片的区域
:param confidence:模糊匹配相似度 不传值为默认相似度 数据类型为数字,范围为0到1
:return:成功:True 失败:False
"""
pyautogui.FAILSAFE = False
status = False
try:
print("开始识别图片,并点击 {}".format(img_path))
search_count = 0
while search_count < timeout:
search_count += 1
print('当前第{}次查找图片'.format(search_count))
if confidence: # 如果confidence传值了 则相似度使用confidence的值
img_pos_center = pyautogui.locateCenterOnScreen(img_path, region=region, confidence=confidence)
else: # 如果confidence未传值 则使用默认相似度
img_pos_center = pyautogui.locateCenterOnScreen(img_path, region=region, )
if img_pos_center: # 搜索到图片位置
x = img_pos_center[0] + OffsetX
y = img_pos_center[1] + OffsetY
pyautogui.moveTo(x, y, duration=0.2)
if double_click:
pyautogui.doubleClick()
else:
if right_click:
pyautogui.rightClick()
else:
pyautogui.click()
status = True
print('点击图片成功 {}'.format(img_path))
break
time.sleep(1)
if not status:
print('执行{}秒内没有找到图片'.format(timeout))
if raise_error:
raise Exception('执行{}秒内没有找到图片:{}'.format(timeout, img_path))
time.sleep(0.2)
if homing:
pyautogui.moveTo(160, 10, duration=0.2)
if sign:
pyautogui.click()
except Exception as e:
if raise_error:
raise e
status = False
return status
本文标题: 基于pyautogui的图片识别定位点击操作