import aircv as ac
import cv2
from common.tools import get_project_path, file_sep, get_now_date_time_str
from common.report_add_img import add_img_path_2_report
class FindImg:
def img_imread(self, img_path):
img = ac.imread(img_path)
if img is None:
print(f"未能读取图片: {img_path}")
return img
def is_image_read(self, img):
"""
判断图片是否成功读取
:param img: 图片对象
:return: 成功读取返回 True,否则返回 False
"""
return img is not None
def get_confidence(self, source_path, search_path):
"""
查找图片
:param source_path: 原图路径
:param search_path: 需要查找的图片的路径
:return:
"""
img_src = self.img_imread(source_path)
img_sch = self.img_imread(search_path)
if not self.is_image_read(img_src) or not self.is_image_read(img_sch):
print("图片读取失败,无法进行匹配。")
return None
result = ac.find_template(img_src, img_sch)
print(result)
if result is None:
print("未找到匹配的模板。")
return None
# cv2.rectangle 这个函数的作用是在图像上绘制一个简单的矩形。
cv2.rectangle(
img_src, result["rectangle"][0], result["rectangle"][3], (255, 0, 0), 2
)
diff_img_path = get_project_path() + file_sep(["img", "diff_img", get_now_date_time_str() + "-对比的图.png"],
add_sep_before=True)
cv2.imencode(".png", img_src)[1].tofile(diff_img_path)
add_img_path_2_report(diff_img_path, "查找到的图")
return result["confidence"]
if __name__ == '__main__':
# 项目名:mumu_pytestSelenium
source_path = get_project_path() + file_sep(["img", "source_img", "head_img.png"], add_sep_before=True)
search_path = get_project_path() + file_sep(["img", "assert_img", "head_img.png"], add_sep_before=True)
FindImg().get_confidence(source_path, search_path)
print()
# 使用绝对路径
s = "D:\\Software\python\\test\\mumu_pytestSelenium\\img\\assert_img\\head_img.png"
d = "D:\\Software\python\\test\\mumu_pytestSelenium\img\\source_img\\head_img.png"
FindImg().get_confidence(s, d)
返回结果
D:\Software\python\py_3.11\python.exe D:\Software\python\test\mumu_pytestSelenium\common\find_img.py
None
未找到匹配的模板。
None
未找到匹配的模板。
Process finished with exit code 0
下面的是assert_img下的图片

下面的是source_img的图片

为什么返回的是 None 呢?