OpenCV之模板匹配

原理和c++实现:https://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html

目的是检测、定位一个物体在一副图像中的位置,主要是通过计算两幅图(待检测图像和图像)的相关性来定位的

OpenCV之模板匹配

OpenCV之模板匹配

用于计算相关性的公式如下:

OpenCV之模板匹配

算法:

  • 在原始图像上移动模板图像
  • 计算每个位置的NCC
  • 当NCC最大时:最佳!

python实现:

import numpy as np
import cv2

def TemplateMatching(src, temp, stepsize): # src: source image, temp: template image, stepsize: the step size for sliding the template
    mean_t = 0;
    var_t = 0;
    location = [0, 0];
    # Calculate the mean and variance of template pixel values
    # ------------------ Put your code below ------------------ 
    mean_t,var_t=cv2.meanStdDev(temp)

    max_corr = 0;
    # Slide window in source image and find the maximum correlation
    for i in np.arange(0, src.shape[0] - temp.shape[0], stepsize):
        for j in np.arange(0, src.shape[1] - temp.shape[1], stepsize):
            mean_s = 0;
            var_s = 0;
            corr = 0;
            # Calculate the mean and variance of source image pixel values inside window
            # ------------------ Put your code below ------------------ 
            mean_window=np.mean(src[i:i+temp.shape[0],j:j+temp.shape[1]])
            var_window=np.var(src[i:i+temp.shape[0],j:j+temp.shape[1]])

            # Calculate normalized correlation coefficient (NCC) between source and template
            # ------------------ Put your code below ------------------ 
            mul=(src[i:i+temp.shape[0],j:j+temp.shape[1]]-mean_t)*(temp-mean_t)
            sum_val=sum(sum(mul[i])for i in range(len(mul)))
            corr=(1/float((temp.shape[0])*(temp.shape[1])))*sum_val/((var_t)*(var_window))
            if corr > max_corr:
                max_corr = corr;
            location = [i, j];
    return location


# load source and template images
source_img = cv2.imread('/Users/wangmengxi/Documents/mercy/ec601/openCV/source.jpg',0) # read image in grayscale
temp = cv2.imread('/Users/wangmengxi/Documents/mercy/ec601/openCV/template.jpg',0) # read image in grayscale
location = TemplateMatching(source_img, temp, 20);
print(location)
match_img = cv2.cvtColor(source_img, cv2.COLOR_GRAY2RGB)
# Draw a red rectangle on match_img to show the template matching result
# ------------------ Put your code below ------------------ 
cv2.rectangle(match_img,(location[1]-temp.shape[1]/2,location[0]-temp.shape[0]/2),(location[1]+temp.shape[1]/2,location[0]+temp.shape[0]/2),(0,0,255),3)

# Save the template matching result image (match_img)
# ------------------ Put your code below ------------------ 
cv2.imwrite("/Users/wangmengxi/Documents/mercy/ec601/openCV/match_img.jpg",match_img)

# Display the template image and the matching result
#cv2.namedWindow('TemplateImage', cv2.WINDOW_NORMAL)
#cv2.namedWindow('MyTemplateMatching', cv2.WINDOW_NORMAL)
#cv2.imshow('TemplateImage', temp)
#cv2.imshow('MyTemplateMatching', match_img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()

结果:

source img:

OpenCV之模板匹配

template:

OpenCV之模板匹配

match:

OpenCV之模板匹配

原文链接: https://www.cnblogs.com/x1mercy/p/7865336.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/263805

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 下午4:05
下一篇 2023年2月14日 下午4:06

相关推荐