使用opencv模板匹配方式。
这种方式针对从原始图片中直接扣小图情况比较好。
import cv2 as cv2
def find_positions(image_path, small_image_path):
# 读取大图和小图
large_image = cv2.imread(image_path)
small_image = cv2.imread(small_image_path)
# 小图规格
small_image_h, small_image_w = small_image.shape[:2]
# 对比大图与小图
# 匹配模板
res = cv2.matchTemplate(large_image, small_image, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# 计算矩形左边
top_left = max_loc
# 适用于小图长度>高度情况
# bottom_right = (max_loc[0] + small_image_h, max_loc[1] + small_image_w)
# 适用于小图长度<高度情况
bottom_right = (max_loc[0] + small_image_w, max_loc[1] + small_image_h)
# 画矩形
cv2.rectangle(large_image, top_left, bottom_right, (0, 0, 255), 3)
# 展示结果
cv2.imshow('large_image', large_image)
cv2.waitKey(0)
pass
image_path = "D:/Desktop/big.png"
small_image_path = "D:/Desktop/small.png"
find_positions(image_path, small_image_path)
大图:
小图:
最后结果: