当前位置:网站首页>[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
边栏推荐
- Std:: vector batch import fast de duplication method
- Apply lnk306gn-tl converter, non isolated power supply
- Js3day (array operation, JS bubble sort, function, debug window, scope and scope chain, anonymous function, object, Math object)
- What data types does redis have and their application scenarios
- 应用LNK306GN-TL 转换器、非隔离电源
- Bom Dom
- JS iterator generator asynchronous code processing promise+ generator - > await/async
- Do you know all the interface test interview questions?
- Interesting interview questions
- Sensor adxl335bcpz-rl7 3-axis accelerometer complies with rohs/weee
猜你喜欢
js3day(数组操作,js冒泡排序,函数,调试窗口,作用域及作用域链,匿名函数,对象,Math对象)
JS iterator generator asynchronous code processing promise+ generator - > await/async
模数转换器(ADC) ADE7913ARIZ 专为三相电能计量应用而设计
堆 AcWing 838. 堆排序
What is the relationship between NFT and metauniverse? How to view the market? The future market trend of NFT
BOM DOM
js4day(DOM开始:获取DOM元素内容,修改元素样式,修改表单元素属性,setInterval定时器,轮播图案例)
C#运算符
ArrayList与LinkedList效率的对比
上手报告|今天聊聊腾讯目前在用的微服务架构
随机推荐
C#修饰符
spfa AcWing 852. spfa判断负环
阿里初面被两道编程题给干掉,再次内推终上岸(已拿电子offer)
Obtain file copyright information
Oracle从入门到精通(第4版)
线性DP AcWing 895. 最长上升子序列
Five best software architecture patterns that architects must understand
浏览器node事件循环
Rust语言文档精简版(上)——cargo、输出、基础语法、数据类型、所有权、结构体、枚举和模式匹配
About asp Net MVC project in local vs running response time is too long to access, the solution!
. Net wechat message template push
腾讯三面:进程写文件过程中,进程崩溃了,文件数据会丢吗?
3 a VTT terminal regulator ncp51200mntxg data
Linear DP acwing 896 Longest ascending subsequence II
VLAN experiment
js2day(又是i++和++i,if语句,三元运算符,switch、while语句,for循环语句)
趣味 面试题
Js7day (event object, event flow, event capture and bubble, prevent event flow, event delegation, student information table cases)
The coloring method determines the bipartite graph acwing 860 Chromatic judgement bipartite graph
染色法判定二分图 AcWing 860. 染色法判定二分图