UI 自动化中,我使用 openCV 封装了一个方法用于获取元素坐标,然后使用 appium 的 tap 方法进行点击,运行过程中 imread 的方法出现报错:expected string or Unicode object, bool found,小白尚未找到原因及解决方法,麻烦社区的大大帮忙看下。。。。
话不多说,下面是我的代码:
自定义图片名称,并使用appium的截图方法获取一张截图,返回图片路径
import cv2
import logging
import time
import os
# 封装appium截图的方法
def get_screen_shot(self, name=None):
try:
if name is None:
image = self.driver.save_screenshot('/Users/alex.pan/Documents/test/default.png')
return image
elif name is not None:
image = self.driver.save_screenshot(name)
return image
except Exception:
raise
def get_original_image(self, name):
"""
获取素材原图,返回图片路径
:param name:
:return:
"""
picture_name = self.picture_name(name)
image = self.get_screen_shot(picture_name)
return image
@staticmethod
# 自定义图片名称
def picture_name(name):
data = time.strftime('%Y-%m-%d', time.localtime(time.time()))
tm = time.strftime('%Y-%m-%d_%H_%M_%S', time.localtime(time.time()))
pic_type = '.png'
file_path = '/Users/alex.pan/Documents/test' + '/' + data
if os.path.exists(file_path):
filename = file_path + '/' + name + '_' + tm + pic_type
print filename
return filename
else:
os.makedirs(file_path)
filename = file_path + '/' + name + '_' + tm + pic_type
print filename
return filename
# open cv 获取元素坐标的方法
@staticmethod
def get_coordinates_by_open_cv(original_image_name, temple_img, method=cv2.TM_CCOEFF_NORMED):
# 实时截一张图作为原图
# 调用APPIUM的方法截图,并返回保存路径
original_image = self.get_original_image(original_image_name)
# 输入模板图路径
target_image = temple_img
# 读取图片,并将图片转化为灰度
read_original_image = cv2.imread(original_image, 0)
read_target_image = cv2.imread(target_image, 0)
find_height, find_width = read_target_image.shape[::]
# 进行图像匹配
result = cv2.matchTemplate(read_original_image, read_target_image, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
logging.info(min_val, max_val, min_loc, max_loc)
# 计算点坐标
# point_up_left = max_loc
# point_low_right = (max_loc[0] + find_width, max_loc[1] + find_height)
point_centre = (max_loc[0] + (find_width / 2), max_loc[1] + (find_height / 2))
print point_centre
return point_centre
运行后报错
File "/Users/alex.pan/Documents/test/demo.py", line 144, in get_coordinates_by_open_cv
read_original_image = cv2.imread(original_image_name, 0)
TypeError: expected string or Unicode object, bool found
发现问题:我把 original_image_name 这个参数直接替换成图片路径这个方法是执行成功的,但是使用 appium 实时截图后返回路径的方法后就报错了
read_original_image = cv2.imread(original_image_name, 0)