当前位置:网站首页>cv. Matchtemplate image model matching opencv

cv. Matchtemplate image model matching opencv

2022-06-11 03:03:00 Solitary rest

Template matching is a method to search and find the position of template image in large image ,OpenCV Provides cv.matchTemplate function , Its essence is to match the small image img1 stay img2 Slide up , Calculate match , Get the matching degree of different regions .

cv.matchTemplate() There are many ways to calculate the matching degree , The demonstration results are presented here , But no detailed explanation .

For the original image :

 

 

import cv2.cv2
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

img = cv.imread(r'XXXX')
img2 = img.copy()
template = cv.imread(r'xxxx')

w= template.shape[0]
h= template.shape[1]
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
            'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']
for meth in methods:
    img = img2.copy()
    method = eval(meth)# because meth Is string , So we have to deal with 
    res = cv.matchTemplate(img,template,method)
    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
    if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)
    cv.rectangle(img,top_left, bottom_right, 255, 2)
    plt.subplot(121),plt.imshow(res,cmap = 'gray')
    plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(img,cmap = 'gray')
    plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
    plt.suptitle(meth)
    plt.show()

res It is the distribution of matching degree mentioned above , In some ways , Higher matching , The lower the calculated value , for example cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED, So it needs special treatment .

We make use of cv.minMaxLoc Find the best match , And draw the template in the original image .

 

 

 

 

 

  Multi template matching :

For the original image :

 

 

import cv2.cv2
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

img = cv.imread(r'XXXXX\marry.jpg')
img2 = img.copy()
template = cv.imread(r'XXXXX\marry1.jpg')

w= template.shape[0]
h= template.shape[1]


res = cv.matchTemplate(img2,template,cv.TM_CCOEFF_NORMED)
threshold = 0.8# Set the threshold , Greater than the threshold is considered to be matched 
loc = np.where( res >= threshold)
img = img2.copy()
for pt in zip(*loc[::-1]):
    cv.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv.imwrite(r'XXXX\res.png',img)

 

原网站

版权声明
本文为[Solitary rest]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020555199852.html