精华内容
下载资源
问答
  • opencv python 模板匹配

    2018-07-21 03:55:58
    模板匹配是一种在较大的图像中搜索和查找模板图像位置的方法。OpenCV带有一个函数cv2.matchTemplate()用于此目的.它只是简单地将模板图像放在输入图像上(就像在2D卷积中那样),并在模板图像下对输入图像的模板和补丁...

    Template Matching

    理论

    模板匹配是一种在较大的图像中搜索和查找模板图像位置的方法。OpenCV带有一个函数cv2.matchTemplate()用于此目的.它只是简单地将模板图像放在输入图像上(就像在2D卷积中那样),并在模板图像下对输入图像的模板和补丁进行比较,在OpenCV中实现了几种比较方法,它返回一个灰度图像,每个像素表示该像素区域与模板的匹配程度.

    如果输入图像的大小(W x H)且模板图像的大小(w x h),则输出图像的大小为(W-w + 1,H-h + 1).获得结果后,可以使用cv.minMaxLoc()函数查找最大/最小值的位置。将其作为矩形的左上角,并将(w,h)作为矩形的宽度和高度.

    OpenCV中的模板匹配

    import cv2
    import numpy as np
    from matplotlib import pyplot as plt
    
    img = cv2.imread('img.jpg',0)
    img2 = img.copy()
    template = cv2.imread('img_roi.png',0)
    w, h = template.shape[::-1]
    
    # All the 6 methods for comparison in a list
    methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
                'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
    
    for meth in methods:
        img = img2.copy()
        method = eval(meth)
    
        # Apply template Matching
        res = cv2.matchTemplate(img,template,method)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    
        # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
        if method 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)
    
        cv2.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()

    clipboard.png

    clipboard.png

    clipboard.png

    clipboard.png

    clipboard.png

    clipboard.png

    与多个对象匹配的模板

    cv.minMaxLoc()将不会提供所有的位置.在这种情况下,我们将使用阈值.

    import cv2
    import numpy as np
    from matplotlib import pyplot as plt
    
    img_rgb = cv2.imread('img5.png')
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    template = cv2.imread('img_roi1.png',0)
    w, h = template.shape[::-1]
    
    res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
    threshold = 0.8
    loc = np.where( res >= threshold)
    for pt in zip(*loc[::-1]):
        cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
    
    cv2.imshow('res',img_rgb)

    clipboard.png

    clipboard.png

    展开全文
  • /usr/bin/python3 # 2018.01.16 21:07:48 CST # 2018.01.16 21:23:47 CST import cv2 import numpy as np import os def findCenter(img): print(img.shape, img.dtype) gray = cv2.cvtColor(img, cv2.COLOR_BGR2...

    I asked before a question which was, maybe, too complex. So here I am with a new one a little bit simplier.

    I have two images:

    What I want to do is to center the second image into the center of the first, like below.

    What I achieved until now was the center of these images.

    The value is a list of two points, X-Y.

    How can I match these points to have a result like desired above ?

    import cv2

    import numpy as np

    import os

    img1 = cv2.imread(os.path.expanduser('~\\Desktop\\c1.png'))

    # ---Read image and obtain threshold---

    img0 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)

    ret, thresh = cv2.threshold(img0, 120, 255, 1)

    # ---Obtain contours---

    image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    cnts = contours

    center = []

    for c in cnts:

    M = cv2.moments(c)

    cX = int(M["m10"] / M["m00"])

    cY = int(M["m01"] / M["m00"])

    print(cX, cY)

    center.append(cX)

    center.append(cY)

    print(center)

    Thanks

    解决方案

    Here is my step:

    Find centers by contours

    Calc the offset between centers

    Do slice-op to paste the object image

    For those two image:

    1fFjnRC.jpg

    dJZlt3M.jpg

    This is my result (with 0.3x for img2):

    zsHM9.png

    #!/usr/bin/python3

    # 2018.01.16 21:07:48 CST

    # 2018.01.16 21:23:47 CST

    import cv2

    import numpy as np

    import os

    def findCenter(img):

    print(img.shape, img.dtype)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)

    #cv2.imshow("threshed", threshed);cv2.waitKey();cv2.destroyAllWindows()

    #_, cnts, hierarchy = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

    M = cv2.moments(cnts[0])

    cX = int(M["m10"] / M["m00"])

    cY = int(M["m01"] / M["m00"])

    return (cX,cY)

    img1 = cv2.imread("img1.jpg")

    img2 = cv2.resize(cv2.imread("img2.jpg"), None, fx=0.3, fy=0.3)

    ## (1) Find centers

    pt1 = findCenter(img1)

    pt2 = findCenter(img2)

    ## (2) Calc offset

    dx = pt1[0] - pt2[0]

    dy = pt1[1] - pt2[1]

    ## (3) do slice-op `paste`

    h,w = img2.shape[:2]

    dst = img1.copy()

    dst[dy:dy+h, dx:dx+w] = img2

    cv2.imwrite("res.png", dst)

    展开全文
  • I need to get the list of the x and y coordinates of the pixels that the feature matcher selects in the code provided... I'm using Python and OpenCV. Can anyone help me?img1=cv2.imread('DSC_0216.jpg',...

    I need to get the list of the x and y coordinates of the pixels that the feature matcher selects in the code provided. I'm using Python and OpenCV. Can anyone help me?

    img1=cv2.imread('DSC_0216.jpg',0)

    img2=cv2.imread('DSC_0217.jpg',0)

    orb=cv2.ORB(nfeatures=100000)

    kp1,des1=orb.detectAndCompute(img1,None)

    kp2,des2=orb.detectAndCompute(img2,None)

    img1kp=cv2.drawKeypoints(img1,kp1,color=(0,255,0),flags=0)

    img2kp=cv2.drawKeypoints(img2,kp2,color=(0,255,0),flags=0)

    cv2.imwrite('m_img1.jpg',img1kp)

    cv2.imwrite('m_img2.jpg',img2kp)

    bf=cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

    matches=bf.match(des1,des2)

    matches=sorted(matches, key= lambda x:x.distance)

    解决方案

    We know that your keypoints are stored in kp1 and kp2 where they are the features matches for the first and second image respectively. In the cv2.ORB perspective, these are 2D matrices where each row is a keypoint that is detected in first image, kp1 and the second image, kp2.

    In your case because you are using cv2.BFMatch, matches returns a list of cv2.DMatch objects where each object contains several members.... among them are two important members:

    queryIdx - The index or row of the kp1 interest point matrix that matches

    trainIdx - The index or row of the kp2 interest point matrix that matches

    Therefore, queryIdx and trainIdx tell you which ORB features match between kp1 and kp2. Therefore, you'd use these to index into kp1 and kp2 and obtain the pt member, which is a tuple of (x,y) coordinates that determine the actual spatial coordinates of the matches.

    All you have to do is iterate through each cv2.DMatch object in matches, append to a list of coordinates for both kp1 and kp2 and you're done.

    Something like this:

    # Initialize lists

    list_kp1 = []

    list_kp2 = []

    # For each match...

    for mat in matches:

    # Get the matching keypoints for each of the images

    img1_idx = mat.queryIdx

    img2_idx = mat.trainIdx

    # x - columns

    # y - rows

    # Get the coordinates

    (x1,y1) = kp1[img1_idx].pt

    (x2,y2) = kp2[img2_idx].pt

    # Append to each list

    list_kp1.append((x1, y1))

    list_kp2.append((x2, y2))

    Note that I could have just done list_kp1.append(kp1[img1_idx].pt) and the same for list_kp2, but I wanted to make it very clear on how to interpret the spatial coordinates. You could also go one step further and do a list comprehension:

    list_kp1 = [kp1[mat.queryIdx].pt for mat in matches]

    list_kp2 = [kp2[mat.trainIdx].pt for mat in matches]

    list_kp1 will contain the spatial coordinates of a feature point that matched with the corresponding position in list_kp2. In other words, element i of list_kp1 contains the spatial coordinates of the feature point from img1 that matched with the corresponding feature point from img2 in list_kp2 whose spatial coordinates are in element i.

    As a minor sidenote, I used this concept when I wrote a workaround for drawMatches because for OpenCV 2.4.x, the Python wrapper to the C++ function does not exist, so I made use of the above concept in locating the spatial coordinates of the matching features between the two images to write my own implementation of it.

    Check it out if you like!

    展开全文
  • OpenCV中的模板匹配2. 多对象的模板匹配3. 小结 目标 通过本篇文章的学习,你将学习到以下内容: 使用模板匹配图像中查找对象 学习到函数:cv.matchTemplate(),cv.minMaxLoc() 前言 模板匹配是一种用于在较大...

    目标

    通过本篇文章的学习,你将学习到以下内容:

    • 使用模板匹配在图像中查找对象
    • 学习到函数:cv.matchTemplate()cv.minMaxLoc()

    前言

    模板匹配是一种用于在较大图像中搜索和查找模板图像位置的方法。为此,OpenCV带有一个函数cv.matchTemplate()。 它只是将模板图像滑动到输入图像上(就像在2D卷积中一样),然后在模板图像下比较模板和输入图像的拼图。OpenCV中实现了几种比较方法,它返回一个灰度图像,其中每个像素表示该像素的邻域与模板匹配的程度。

    如果输入图像的大小为(WxH) ,而模板图像的大小为(wxh) ,则输出图像的大小将为(W-w + 1,H-h + 1) 。得到结果后,可以使用cv.minMaxLoc()函数查找最大/最小值在哪。将其作为矩形的左上角,并以(w,h)作为矩形的宽度和高度,该矩形是模板的区域。

    注意: 如果使用cv.TM_SQDIFF作为比较方法,则最小值提供最佳匹配。

    1. OpenCV中的模板匹配

    作为示例,我们将在lena的照片中搜索他的脸。所以我创建了一个模板,如下所示:
    lena_face

    我们将尝试所有比较方法,以便我们可以看到它们的结果如何:

    import cv2 as cv
    import numpy as np
    from matplotlib import pyplot as plt
    
    img = cv.imread('./data/lena.jpg', 0)
    img2 = img.copy()
    template = cv.imread('./data/lena_face.png', 0)
    w, h = template.shape[::-1]
    # 列表中所有的6种比较方法
    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)
        # 应用模板匹配
        res = cv.matchTemplate(img, template, method)
        min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
        # 如果方法是TM_SQDIFF或TM_SQDIFF_NORMED,则取最小值
        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, 'gray'), plt.title('Matching Result')
        plt.xticks([]), plt.yticks([])
        plt.subplot(122), plt.imshow(img, 'gray'), plt.title('Detect Point')
        plt.xticks([]), plt.yticks([])
        plt.suptitle(meth)
        plt.show()
    

    在这里插入图片描述

    在这里插入图片描述在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    从图中可以看到,使用cv.TM_CCORR的结果并不理想。

    2. 多对象的模板匹配

    在上一节中,我们在图像中搜索了lena的脸,该脸在图像中仅出现一次。假设您正在搜索具有多次出现的对象,则cv.minMaxLoc()不会为您提供所有位置。在这种情况下,我们将使用阈值化。因此,在此示例中,我们将使用著名游戏Mario的屏幕截图,并在其中找到硬币。

    import cv2 as cv
    import numpy as np
    from matplotlib import pyplot as plt
    img_rgb = cv.imread('./data/Mario.png')
    cv.imshow('img', img_rgb)
    img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
    template = cv.imread('./data/Mario_coin.png',0)
    w, h = template.shape[::-1]
    res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)
    threshold = 0.8
    loc = np.where( res >= threshold)
    for pt in zip(*loc[::-1]):
        cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (255, 0, 0), 2)
    cv.imshow('res',img_rgb)
    cv.waitKey()
    

    在这里插入图片描述
    在这里插入图片描述

    3. 小结

    本篇文章主要介绍了OpenCV中模板匹配的内容,分别演示了对单个对象与多个对象的模板匹配,cv.matchTemplate()cv.minMaxLoc()函数的简单使用。

    如果文章对你有帮助,欢迎点赞与关注~~, 谢谢~~

    展开全文
  • python opencv图像匹配 matchTemplate函数

    千次阅读 2019-04-11 13:47:41
    其中计算图像距离的算法有多种:TM_SQDIFF,TM_SQDIFF_NORMED等详细见opencv官网 算法很简单,只用用在图像没有发生变形的情况下 代码 import cv2 def match_image(source, template): # 选择匹配算法 match_...
  • Python OpenCV图像模板匹配

    千次阅读 2017-11-06 16:20:41
    模板匹配的工作方式跟直方图的反向投影基本一样,大致过程是这样的:通过在输入图像上滑动图像块对实际的图像块和输入图像进行匹配。 假设我们有一张100x100的输入图像,有一张10x10的模板图像,查找的过程是这样...
  • 它轻量级而且高效——由一系列 C 函数和少量 C++ 类构成,同时提供了Python、Ruby、MATLAB等语言的接口,实现了图像处理和计算机视觉方面的很多通用算法。 今天我们就是用python学习OpenCV。...
  • 安装命令:pip install opencv-python 1.图像模板匹配 #使用matchTemplate对原始灰度图像图像模板进行匹配 res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) #设定阈值 threshold =0.9 #...
  • 通过使用opencv,使用python语言实现图像模板匹配,从而实现图像的类别分类。
  • 文章目录一、理论介绍二、代码 ...用T表示模板图像,I表示待匹配图像,切模板图像的宽为w高为h,用R表示匹配结果,匹配过程(图示如上): 通过 滑动, 我们的意思是图像块一次移动一个像素 (从左往右,从上往下)....
  • opencv+python实现图像匹配----模板匹配、特征点匹配

    万次阅读 多人点赞 2019-02-12 16:30:46
    文章目录模板匹配与特征匹配python的版本及依赖的库的安装opencv+python模板匹配[^1]匹配材料Template Matchingopencv+python特征匹配[^2]匹配材料BFMatching描述特征点--运行结果不精确基于FLANN的匹配器(FLANN ...
  • 图像特征匹配是什么就不具体介绍了,今天写一下用opencv进行图像特征匹配,一起解读下官方文档,写写代码来实践实践。 Docs: ...
  • 它允许你改变canny过滤器的参数,thresold1和thresold2,因此你将得到一个整体的想法,你可以应用canny过滤器的图像。在import cv2import numpy as npdef nothing(x):pass#image windowcv2.namedWindow('image')#...
  • 原标题:OpenCV-Python图像处理教程(源码及素材)cv即可获取。入门篇简介与安装(了解安装OpenCV-Python) | 番外篇1:代码性能优化基本元素-图片(图片载入/显示/保存) | 番外篇2:无损保存和Matplotlib使用打开...
  • 1、运行python脚本时报错: ...pip install opencv-python 2、运行python脚本时报错: 在使用matchTemplate()时报错: error: (-215:Assertion failed) (depth == CV_8U || depth == CV_32F) && type == _temp
  • 在实际生活中,要搜索的模板图像很有可能在图像中出现多次,这个时候就需要多次匹配结果,上文提到的函数cv2.minMaxLoc()只能找到最值及位置,无法匹配多个信息,因此设计过程进行多次匹配。 二、匹配过程 (1)...
  • 关于透视变换 cv2.warpPerspective 详情请查看: https://blog.csdn.net/dcrmg/article/details/80273818 ...关于FLANN匹配 详情请查看:https://blog.csdn.net/wsp_1138886114/a...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 9,594
精华内容 3,837
关键字:

opencvpython图像匹配

python 订阅