import os
import numpy as np
import cv2
from PIL import Image
from loguru import logger
from config import ScreenshotDir
import uiautomator2
class Base(object):
def __init__(self, device: uiautomator2.Device, timeout: int):
logger.info("Base 类初始化")
self.Device = device
self.TIMEOUT = timeout
def get_current_screenshot(self, filename="current.png") -> str:
filename = os.path.join(ScreenshotDir, filename)
logger.info(f"获取当前截图,路径:{filename}")
self.Device.screenshot(filename)
return filename
def image_rect_match(self, image1, image2, rect) -> float:
"""
对比两张图片指定矩形区域内容是否一样, 返回匹配系数
矩形区域((y1,x1),(y2,x2))
"""
(y1, x1), (y2, x2) = rect
img1 = self.cv_read(image1)[y1:y2, x1:x2]
img2 = self.cv_read(image2)[y1:y2, x1:x2]
# 使用模板函数进行匹配,归一化操作
res = cv2.matchTemplate(img1, img2, cv2.TM_CCOEFF_NORMED)
# 获取匹配结果
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
logger.info(f"匹配度:{max_val} rect:{rect} {image1} {image2}")
return max_val
def image_exists(self, image1, image2, compatibility=0.99) -> bool:
"""
判断image1 是否存在 image2中,返回bool值
:param image1:
:param image2:
:param compatibility:
:return:
"""
logger.debug(f"image1={image1} image2={image2}")
img1 = self.cv_read(image1)
img2 = self.cv_read(image2)
# 使用模板函数进行匹配,归一化操作
res = cv2.matchTemplate(img2, img1, cv2.TM_CCOEFF_NORMED)
# 获取匹配结果
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
logger.info(f"相似度:【{max_val}】 【{image1}】在图片中的【{image2}】")
return max_val > compatibility
def image_loc(self, image1, image2) -> tuple:
"""
获取image1,在image2中的中间位置
:param image1:
:param image2:
:param compatibility:
:return:
"""
logger.debug(f"image1={image1} image2={image2}")
img1 = self.cv_read(image1)
img2 = self.cv_read(image2)
# 使用模板函数进行匹配,归一化操作
res = cv2.matchTemplate(img2, img1, cv2.TM_CCOEFF_NORMED)
# 获取匹配结果
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# 获取image1的中心坐标
w, h = Image.open(image1).size
x, y = max_loc[0] + int(w / 2), max_loc[1] + int(h / 2)
logger.info(f"返回坐标:【{x, y}】 【{image1}】在【{image2}】的位置")
return x, y
@staticmethod
def image_draw_rect(image, rect):
"""
画出目标图片中的,指定区域,主要用于调试
:param image:
:param rect:
:return:
"""
(y1, x1), (y2, x2) = rect
image = cv2.imread(image, cv2.IMREAD_COLOR)
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 5)
cv2.imwrite("Test.png", image)
def cv_read(self, image):
"""
opencv无法识别中文路径图片,使用此方法读
:param image:
:return:
"""
# target = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
return cv2.imdecode(np.fromfile(image, dtype=np.uint8), -1)
def cv_write(self, img, filename):
"""
opencv无法读取中文路径图片,使用此方法写
:param img:
:param filename: 完整路径 如:C:\1 保存:C:\1.png
:return:
"""
cv2.imencode('.png', img)[1].tofile(filename)
opencv-图片识别参考代码
最新推荐文章于 2024-05-03 04:54:24 发布