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

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

Python+opencv实图片定位_第1张图片

你可能感兴趣的:(Python,自动化测试,python,opencv)