python获取小图在大图中的坐标和相似度

python获取小图在大图中的坐标和相似度

模块安装:pip install aircv

大小两个图片:big.jpg,small.jpg

直接上代码

import aircv as ac
from PIL import Image

# 需要当前目录准备两个图片,big.jpg 和 small.jpg

class CompareImage():
    # 可以通过confidencevalue来调节相似程度的阈值,小于阈值不相似
    def matchImg(self, imgsrc, imgobj, phone_x, phone_y, confidencevalue=0):  # imgsrc=原始图像,imgobj=待查找的小图片
        imsrc = ac.imread(imgsrc)
        imobj = ac.imread(imgobj)
        match_result = ac.find_template(imsrc, imobj, confidencevalue)
        print(match_result,type(match_result),end="*****\n")
        if match_result is not None:
            match_result['shape'] = (imsrc.shape[1], imsrc.shape[0])  # 0为高,1为宽
            x, y = match_result['result']  # 标准图中小图位置x,y
            shape_x, shape_y = tuple(map(int, match_result['shape']))  # 标准图中x,y
            position_x, position_y = int(phone_x * (x / shape_x)), int(phone_y * (y / shape_y))
        else:
            return None,None,None,None
        # print(match_result)
        # return match_result
        return position_x, position_y, str(match_result['confidence'])[:4], match_result

    def fixed_size(self, width, height, infile, outfile):
        """按照固定尺寸处理图片"""
        im = Image.open(infile)
        out = im.resize((width, height), Image.ANTIALIAS)
        out.save(outfile)

    def get_picture_size(self, imgsrc):
        '''获取图片长,宽'''
        imsrc = ac.imread(imgsrc)
        y, x, z = imsrc.shape
        return x, y
if __name__ == '__main__':

    result = CompareImage().matchImg("big.jpg","small.jpg",10,10)
    zuobiao = result[3]["rectangle"]
    xmin = zuobiao[0][0]
    ymin = zuobiao[0][1]
    xmax = zuobiao[2][0]
    ymax = zuobiao[3][1]

    # 在原始图片上绘制相似的区域
    import cv2
    image = cv2.imread('big.jpg')
    cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 0, 255), 2)
    cv2.imwrite('result.jpg', image)

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
非常抱歉,上面的代码我确实遗漏了返回小图大图坐标。下面是修改后的代码,可以返回小图大图的左上角和右下角坐标: ```python import torch import torchvision.models as models import torchvision.transforms as transforms import cv2 import numpy as np vgg = models.vgg16(pretrained=True).features vgg.eval() transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # 加载需要匹配的大图小图 img = cv2.imread('big_image.jpg') template = cv2.imread('small_image.jpg') # 将大图小图转换为PyTorch的Tensor格式 img_tensor = transform(img).unsqueeze(0) # 在第0个维度上增加一个维度 template_tensor = transform(template).unsqueeze(0) # 对大图小图分别进行特征提取 img_features = vgg(img_tensor) template_features = vgg(template_tensor) # 计算大图每个位置与小图相似度 result = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED) # 相似度最高的位置 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) top_left = max_loc # 左上角坐标 bottom_right = (top_left[0] + template.shape[1], top_left[1] + template.shape[0]) # 右下角坐标 # 返回小图大图的左上角和右下角坐标 print("小图大图的左上角坐标:", top_left) print("小图大图的右下角坐标:", bottom_right) # 在大图绘制矩形框 cv2.rectangle(img, top_left, bottom_right, (0, 0, 255), 2) # 显示匹配结果 cv2.imshow('result', img) cv2.waitKey(0) ``` 希望这次回答能够满足您的需求,如果还有其他问题,请随时提出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值