Python+opencv实图片定位

# -*- coding: utf-8 -*-
import cv2


file=r'D:/Setting.png'    #大图
temp=r'D:/Battery.png'   #小图

# 弹出图片后 CTRL+S保存图片到本地

method = cv2.TM_SQDIFF_NORMED
# method = cv2.TM_CCOEFF_NORMED

# Read the images from the file
small_image = cv2.imread(temp)
large_image = cv2.imread(file)

result = cv2.matchTemplate(small_image, large_image, method)
# 需要最小平方差
mn,_,mnLoc,_ = cv2.minMaxLoc(result)

# 开始画矩形:
# Extract the coordinates of our best match
MPx,MPy = mnLoc #获得最小坐标的
print(MPx, MPy)

# MPx1,MPy1 = mxLoc #获得最大坐标的
# print(MPx1, MPy1)

# Step 2: Get the size of the template. This is the same size as the match.
trows,tcols = small_image.shape[:2]  #获得图片的宽度

# Step 3: Draw the rectangle on large_image
# 将小图片用红线在大图片圈出来
cv2.rectangle(large_image, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2)

# cv2.rectangle(large_image, (MPx+169,MPy+76),(MPx+719,MPy+117),(0,0,255),2)

# Display the original image with the rectangle around the match.
cv2.imshow('output',large_image)

# The image is only displayed if we call this
cv2.waitKey(0)


#方法不同,获得的坐标不同
# print(MPx, MPy)
# print(MPx1, MPy1)
# 注意看一下两种方法有一个结果是相同的
#cv2.TM_SQDIFF_NORMED
# 结果:
# 96 179
# 70 1122

# cv2.TM_CCOEFF_NORMED
# 结果:
# 72 1631
# 96 179

如下图所示,在背景图片中找到的  搜索的 图标,并用红线圈出来 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值