Python如何实现图片特征点匹配

Python018

Python如何实现图片特征点匹配,第1张

python-opencv-特征点匹配连线(画线)drawMatches

Python 没有OpenCV 2.4.13版本的cv2.drawMatches(),无法直接使用,故可参看本文第2节的drawMatches函数使用

Python 有OpenCV 3.0.0版本的cv2.drawMatches(),可以直接使用

1、drawMatches数据结构(opencv2.4.13)

Draws the found matches of keypoints from two images.

C++:

void drawMatches(const Mat&img1, const vector<KeyPoint>&keypoints1, const Mat&img2, const vector<KeyPoint>&keypoints2, const vector<vector<DMatch>>&matches1to2, Mat&outImg, const Scalar&matchColor=Scalar::all(-1), const Scalar&singlePointColor=Scalar::all(-1), const vector<vector<char>>&matchesMask=vector<vector<char>>(), int flags=DrawMatchesFlags::DEFAULT )1

Parameters: 

img1 – First source image.

keypoints1 – Keypoints from the first source image.

img2 – Second source image.

keypoints2 – Keypoints from the second source image.

matches1to2 – Matches from the first image to the second one, which means that keypoints1[i] has a corresponding point in keypoints2[matches[i]] . 

outImg – Output image. Its content depends on the flags value defining what is drawn in the output image. See possible flags bit values below.

matchColor – Color of matches (lines and connected keypoints). If matchColor==Scalar::all(-1) , the color is generated randomly. 

singlePointColor – Color of single keypoints (circles), which means that keypoints do not have the matches. If singlePointColor==Scalar::all(-1) , the color is generated randomly.

matchesMask – Mask determining which matches are drawn. If the mask is empty, all matches are drawn.

flags – Flags setting drawing features. Possible flags bit values are defined by DrawMatchesFlags. 

This function draws matches of keypoints from two images in the output image. Match is a line connecting two keypoints (circles). The structure DrawMatchesFlags is defined as follows:

struct DrawMatchesFlags

{

   enum

   {

       DEFAULT = 0, // Output image matrix will be created (Mat::create),

                    // i.e. existing memory of output image may be reused.

                    // Two source images, matches, and single keypoints

                    // will be drawn.

                    // For each keypoint, only the center point will be

                    // drawn (without a circle around the keypoint with the

                    // keypoint size and orientation).

       DRAW_OVER_OUTIMG = 1, // Output image matrix will not be

                      // created (using Mat::create). Matches will be drawn

                      // on existing content of output image.

       NOT_DRAW_SINGLE_POINTS = 2, // Single keypoints will not be drawn.

       DRAW_RICH_KEYPOINTS = 4 // For each keypoint, the circle around

                      // keypoint with keypoint size and orientation will

                      // be drawn.

   }}1234567891011121314151617181920

2、drawMatches(python实现)

# -*- coding: utf-8 -*-"""

Created on Tue Dec 27 09:32:02 2016

@author: http://blog.csdn.net/lql0716

"""def drawMatches(img1, kp1, img2, kp2, matches):

   """

   My own implementation of cv2.drawMatches as OpenCV 2.4.9

   does not have this function available but it's supported in

   OpenCV 3.0.0

   This function takes in two images with their associated

   keypoints, as well as a list of DMatch data structure (matches)

   that contains which keypoints matched in which images.

   An image will be produced where a montage is shown with

   the first image followed by the second image beside it.

   Keypoints are delineated with circles, while lines are connected

   between matching keypoints.

   img1,img2 - Grayscale images

   kp1,kp2 - Detected list of keypoints through any of the OpenCV keypoint

             detection algorithms

   matches - A list of matches of corresponding keypoints through any

             OpenCV keypoint matching algorithm

   """

   # Create a new output image that concatenates the two images together

   # (a.k.a) a montage

   rows1 = img1.shape[0]

   cols1 = img1.shape[1]

   rows2 = img2.shape[0]

   cols2 = img2.shape[1]

   out = np.zeros((max([rows1,rows2]),cols1+cols2,3), dtype='uint8')    # Place the first image to the left

   out[:rows1,:cols1] = np.dstack([img1, img1, img1])    # Place the next image to the right of it

   out[:rows2,cols1:] = np.dstack([img2, img2, img2])    # For each pair of points we have between both images

   # draw circles, then connect a line between them

   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

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

       (x2,y2) = kp2[img2_idx].pt        # Draw a small circle at both co-ordinates

       # radius 4

       # colour blue

       # thickness = 1

       a = np.random.randint(0,256)

       b = np.random.randint(0,256)

       c = np.random.randint(0,256)

       cv2.circle(out, (int(np.round(x1)),int(np.round(y1))), 2, (a, b, c), 1)      #画圆,cv2.circle()参考官方文档

       cv2.circle(out, (int(np.round(x2)+cols1),int(np.round(y2))), 2, (a, b, c), 1)        # Draw a line in between the two points

       # thickness = 1

       # colour blue

       cv2.line(out, (int(np.round(x1)),int(np.round(y1))), (int(np.round(x2)+cols1),int(np.round(y2))), (a, b, c), 1, lineType=cv2.CV_AA, shift=0)  #画线,cv2.line()参考官方文档

   # Also return the image if you'd like a copy

   return out

1. re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

import re

line="this hdr-biz 123 model server 456"

pattern=r"123"

matchObj = re.match( pattern, line)

2. re.search 扫描整个字符串并返回第一个成功的匹配。

import re

line="this hdr-biz model server"

pattern=r"hdr-biz"

m = re.search(pattern, line)

3. Python 的re模块提供了re.sub用于替换字符串中的匹配项。

import re

line="this hdr-biz model args= server"

patt=r'args='

name = re.sub(patt, "", line)

4. compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。

import re

pattern = re.compile(r'\d+')

5. re.findall 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。

import re

line="this hdr-biz model args= server"

patt=r'server'

pattern = re.compile(patt)

result = pattern.findall(line)

6. re.finditer 和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。

import re

it = re.finditer(r"\d+","12a32bc43jf3")

for match in it:

print (match.group() )

关于Python字符串匹配6种方法的使用,青藤小编就和您分享到这里了。如果您对python编程有浓厚的兴趣,希望这篇文章可以为您提供帮助。如果您还想了解更多关于python编程的技巧及素材等内容,可以点击本站的其他文章进行学习。

以上是小编为大家分享的关于Python字符串匹配6种方法的使用的相关内容,更多信息可以关注环球青藤分享更多干货