当前位置:网站首页>[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 
边栏推荐
- 传感器 ADXL335BCPZ-RL7 3轴 加速度计 符合 RoHS/WEEE
- VLAN experiment
- 软件测试面试题-2022年大厂面试题合集
- About asp Net MVC project in local vs running response time is too long to access, the solution!
- js4day(DOM开始:获取DOM元素内容,修改元素样式,修改表单元素属性,setInterval定时器,轮播图案例)
- Js10day (API phased completion, regular expression introduction, custom attributes, filtering sensitive word cases, registration module verification cases)
- js1day(输入输出语法,数据类型,数据类型转换,var和let区别)
- 正确遍历EntryList方法
- js 迭代器 生成器 异步代码处理 promise+生成器 -> await/async
- Mui WebView down refresh pull-up load implementation
猜你喜欢

Redis bloom filter

Anti shake throttle

LTC3307AHV 符合EMI标准,降压转换器 QCA7005-AL33 PHY
![2.7 binary tree, post order traversal - [FBI tree]](/img/6b/1ded3632cc69329d7b2762ce47fdbc.jpg)
2.7 binary tree, post order traversal - [FBI tree]

传感器 ADXL335BCPZ-RL7 3轴 加速度计 符合 RoHS/WEEE

Does C language srand need to reseed? Should srand be placed in the loop? Pseudo random function Rand

Execute any method of any class through reflection

Js8day (rolling event (scroll family), offset family, client family, carousel map case (to be done))

Deep copy event bus

通过反射执行任意类的任意方法
随机推荐
JS10day(api 阶段性完结,正则表达式简介,自定义属性,过滤敏感词案例,注册模块验证案例)
Docsify deploy IIS
线性DP AcWing 902. 最短编辑距离
FBX import under ue4/ue5 runtime
Browser node event loop
The redis development document released by Alibaba covers all redis operations
Day4 operator, self increasing, self decreasing, logical operator, bit operation, binary conversion decimal, ternary operator, package mechanism, document comment
Efficiency comparison between ArrayList and LinkedList
. Net, C # basic knowledge
计数类DP AcWing 900. 整数划分
spfa AcWing 851. SPFA finding the shortest path
Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?
区间DP AcWing 282. 石子合并
Shutter encapsulated button
Dijkstra AcWing 850. Dijkstra finding the shortest circuit II
Counting class DP acwing 900 Integer partition
阿里初面被两道编程题给干掉,再次内推终上岸(已拿电子offer)
2.6 using recursion and stack - [tower of Hanoi problem]
接口测试面试题目,你都会了吗?
JDBC 预防sql注入问题与解决方法[PreparedStatement]