当前位置:网站首页>[opencv learning] [template matching]
[opencv learning] [template matching]
2022-07-02 12:52:00 【A sea of stars】
Learn template matching today
Template image 
Target image 
import cv2
import matplotlib.pyplot as plt
# The principle of template matching :
# A template image slides on the target image from left to right and from top to bottom , The matching degree is calculated for each sliding position ( Mean square deviation or correlation coefficient )
# After traversing the target image , Find the best matching unknown region .
# Show the image , Encapsulate as a function
def cv_show_image(name, img):
cv2.imshow(name, img)
cv2.waitKey(0) # Waiting time , In milliseconds ,0 Represents any key termination
cv2.destroyAllWindows()
# Read the template
template = cv2.imread('images/template.jpg') # Turn to grayscale
print('template Image dimension is :', template.shape)
h, w, c = template.shape
print(h)
print(w)
cv_show_image('template', template)
# Read the target image
dst_img = cv2.imread('images/saoge2.jpg') # Turn to grayscale
print(' The target image dimension is :', dst_img.shape)
cv_show_image('dst_img', dst_img)
# The measurement method of matching degree
methords = ['cv2.TM_SQDIFF', # Calculate the mean square deviation of each pixel , The smaller the value, the more relevant
'cv2.TM_CCORR', # Calculate correlation , The larger the value, the more relevant
'cv2.TM_CCOEFF', # Calculate the correlation coefficient , The larger the value, the more relevant
'cv2.TM_SQDIFF_NORMED', # Calculate the mean square deviation of each pixel , The smaller the value, the more relevant , With normalization
'cv2.TM_CCORR_NORMED', # Calculate correlation , The larger the value, the more relevant , With normalization
'cv2.TM_CCOEFF_NORMED' # Calculate the correlation coefficient , The larger the value, the more relevant , With normalization
]
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255), (255, 0, 255)]
thickness = [12, 10, 8, 6, 4, 2]
img_result = dst_img.copy()
for i in range(len(methords)):
img_tmp = dst_img.copy() # Show the current frame temporarily
methord = eval(methords[i]) # Get the specific template matching method
print('current methord is: {}'.format(methords[i]))
# Actual template matching
res = cv2.matchTemplate(dst_img, template, methord) # Incoming target image 、 Template image 、 Match metrics
print(res.shape) # Get is (dst_img.H - template.H + 1, dst_img.W - template.W + 1) Dimension data of
print(type(res)) # <class 'numpy.ndarray'>
print(res.dtype) # The type of each element is float32
# Analysis results , Obtain the maximum and minimum values of the measurements in the matching process respectively , And the location of its distribution pixels , according to methord Different , Take the appropriate value
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if methord in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
print(' The location information that the template matches is ', top_left, bottom_right)
# Draw a rectangle on the image to indicate the matching position
cv2.rectangle(img_result, top_left, bottom_right, colors[i], thickness[i])
cv2.rectangle(img_tmp, top_left, bottom_right, colors[i], thickness[i])
plt.subplot(1, 2, 1), plt.imshow(res, 'gray') # Draw each pixel ( Representing one (h, w) Region ) The matching degree of
plt.xticks([]), plt.yticks([]) # Hide axis
plt.subplot(1, 2, 2), plt.imshow(img_tmp, 'gray') # Draw the matching position on the original image
plt.xticks([]), plt.yticks([]) # Hide axis
plt.title(methords[i])
plt.show()
# Finally, check all the frames together
cv_show_image('img_result', img_result)
The effect is as follows :
‘cv2.TM_SQDIFF’, # Calculate the mean square deviation of each pixel , The smaller the value, the more relevant 
‘cv2.TM_CCORR’, # Calculate correlation , The larger the value, the more relevant 
‘cv2.TM_CCOEFF’, # Calculate the correlation coefficient , The larger the value, the more relevant 
‘cv2.TM_SQDIFF_NORMED’, # Calculate the mean square deviation of each pixel , The smaller the value, the more relevant , With normalization 
‘cv2.TM_CCORR_NORMED’, # Calculate correlation , The larger the value, the more relevant , With normalization 
‘cv2.TM_CCOEFF_NORMED’ # Calculate the correlation coefficient , The larger the value, the more relevant , With normalization 
The final result is 
边栏推荐
- Redis avalanche, penetration, breakdown
- 一些突然迸发出的程序思想(模块化处理)
- About the loading of layer web spring layer components, the position of the layer is centered
- Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?
- async/await 异步函数
- How can attribute mapping of entity classes be without it?
- Oracle from entry to mastery (4th Edition)
- ArrayList与LinkedList效率的对比
- Floyd AcWing 854. Floyd求最短路
- Ltc3307ahv meets EMI standard, step-down converter qca7005-al33 phy
猜你喜欢

The coloring method determines the bipartite graph acwing 860 Chromatic judgement bipartite graph

async/await 异步函数

深拷貝 事件總線

LTC3307AHV 符合EMI标准,降压转换器 QCA7005-AL33 PHY

Heap acwing 839 Simulated reactor

Redis sentinel mechanism and configuration

应用LNK306GN-TL 转换器、非隔离电源

线性DP AcWing 896. 最长上升子序列 II

C operator

Linear DP acwing 897 Longest common subsequence
随机推荐
线性DP AcWing 898. 数字三角形
Get started REPORT | today, talk about the microservice architecture currently used by Tencent
Package management tools
Deep Copy Event bus
JDBC prevent SQL injection problems and solutions [preparedstatement]
难忘阿里,4面技术5面HR附加笔试面,走的真艰难真心酸
spfa AcWing 851. spfa求最短路
Day4 operator, self increasing, self decreasing, logical operator, bit operation, binary conversion decimal, ternary operator, package mechanism, document comment
To bypass obregistercallbacks, you need to drive the signature method
模块化 CommonJS ES Module
线性DP AcWing 902. 最短编辑距离
bellman-ford AcWing 853. 有边数限制的最短路
Window10 upgrade encountered a big hole error code: 0xc000000e perfect solution
ASP. Net MVC default configuration, if any, jumps to the corresponding program in the specified area
Heap acwing 839 Simulated reactor
NTMFS4C05NT1G N-CH 30V 11.9A MOS管,PDF
Browser storage scheme
JS6day(DOM结点的查找、增加、删除。实例化时间,时间戳,时间戳的案例,重绘和回流)
Visual studio efficient and practical extension tools and plug-ins
阿里发布的Redis开发文档,涵盖了所有的redis操作