[转][OpenCV实战]19 使用OpenCV实现基于特征的图像对齐(校准—align)

目录

1 背景

1.1 什么是图像对齐或图像对准?

1.2 图像对齐的应用

1.3 图像对齐基础理论

1.4 如何找到对应点

2 OpenCV的图像对齐

2.1 基于特征的图像对齐的步骤

2.2 代码

3 参考


在这篇文章中,我们将学习如何使用OpenCV执行基于特征的图像对齐。我们将使用移动电话拍摄的表格的照片与表格的模板对齐。我们将使用的技术通常被称为“基于特征图像对齐”,因为在该技术中,在一个图像中检测稀疏的特征集并且在另一图像中进行特征匹配。然后基于这些匹配特征将原图像映射到另一个图像,实现图像对齐。如下图所示:

1 背景

1.1 什么是图像对齐或图像对准?

在许多应用程序中,我们有两个相同场景或同一文档的图像,但它们没有对齐。换句话说,如果您在一个图像上选择一个特征(例如白纸的一个边角),则另一个图像中同一个边角的坐标会有很大差异。图像对齐(也称为图像配准)是使一个图像(或两个图像)进行变换的方法,使得两个图像中的特征完美地对齐。入戏

下面是一个例子,中间的表是手机拍摄的表格,左边的表是原始文档。中间的表在经过图像对齐技术处理之后结果如右图所示,可以和左边的模板一样。对齐之后就可以根据模板的格式对用户填写的内容进行分析了。

1.2 图像对齐的应用

图像对齐有许多应用。

在许多文档处理应用程序中,第一步是将扫描或拍摄的文档与模板对齐。例如,如果要编写自动表单阅读器,最好先将表单与其模板对齐,然后根据模板中的固定位置读取字段。

在一些医学应用中,可以把多次拍摄的照片拼接起来。

图像对齐最有趣的应用可能是创建全景图。在这种情况下,两个图像不是平面的图像而是3D场景的图像。通常,3D对齐需要深度信息。然而,当通过围绕其光轴旋转相机拍摄两个图像时(如全景图的情况),我们可以使用本教程中描述的技术来对齐全景图的两张图像。

1.3 图像对齐基础理论

图像对齐技术的核心是一个简单的3×3矩阵,称为Homography(单应性变换)。具体见:

https://blog.csdn.net/LuohenYJ/article/details/89334249

https://en.wikipedia.org/wiki/Homography

https://mp.weixin.qq.com/s/-XrjAjf8ItNMkQyqvcjATQ

我们来看看用法。

C ++

findHomography(points1, points2, h)

python

h, status = cv2.findHomography(points1, points2)

其中,points1和points2是矢量/对应点的阵列,以及ħ是单应性矩阵。

1.4 如何找到对应点

在许多计算机视觉应用中,我们经常需要识别图像中有趣的稳定点。这些点称为关键点或特征点。在OpenCV中实现了几个关键点检测器(例如SIFT,SURF和ORB)。在本教程中,我们将使用ORB特征检测器,因为SIFT和SURF已获得专利,如果您想在实际应用中使用它,则需要支付许可费。ORB快速,准确且无许可证!ORB关键点使用圆圈显示在下图中。

ORB代表Oriented FAST和Rotated BRIEF;让我们看看FAST和BRIEF是什么意思。

特征点检测器有两个部分

(1) 定位器

识别图像上在图像变换下稳定不变的点,如平移(移位),缩放(增大/减小)和旋转。定位器找到这些点的x,y坐标。ORB检测器使用的定位器称为FAST。详细信息见:

https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_fast/py_fast.html

(2) 特征描述子

上述步骤中的定位器只能告诉我们有趣的点在哪里。特征检测器的第二部分是特征描述子,它对点的外观进行编码,以便我们可以分辨不同的特征点。在特征点评估的特征描述只是一个数字数组。理想情况下,两个图像中的相同物理点应具有相同的特征描述。ORB使用名为BRISK的特征描述子。详细信息见:

https://www.robots.ox.ac.uk/~vgg/rg/papers/brisk.pdf

定位器和特征描述子应用很广泛。计算机视觉的许多应用中,我们分两步解决识别问题a)定位;2)识别。例如,为了实现面部识别系统,我们首先需要一个面部检测器,其输出面部所在矩形的坐标。检测器不知道或不关心该人是谁。唯一的工作就是找到一张脸。系统的第二部分是识别算法。原始图像被裁剪为检测到的面部矩形,并且该裁剪的图像反馈送到最终识别该人的面部识别算法。特征检测器的定位器就像面部检测器。描述子类似识别器。

只有当我们知道两个图像中的对应特征时,才能计算出与两个图像相关的单应性。因此,使用匹配算法来查找一个图像中的哪些特征与另一图像中的特征匹配。为此,将一个图像中的每个特征的描述子与第二个图像中的每个特征的描述子进行比较,以找到良好的匹配点。也就是说我们可以通过描述子找到要匹配的特征点,然后根据这些匹配的特征点,计算两个图像相关的单应性,实现图像映射。

ORB其他信息可以见

https://www.jianshu.com/p/387b8ac04c94

2 OpenCV的图像对齐

2.1 基于特征的图像对齐的步骤

现在我们可以总结图像对齐所涉及的步骤。

Step1读图

我们首先在C ++中和Python中读取参考图像(或模板图像)和我们想要与此模板对齐的图像。

Step2寻找特征点

我们检测两个图像中的ORB特征。虽然我们只需要4个特征来计算单应性,但通常在两个图像中检测到数百个特征。我们使用Python和C ++代码中的参数MAX_FEATURES来控制功能的数量。

Step3 特征点匹配

我们在两个图像中找到匹配的特征,按匹配的评分对它们进行排序,并保留一小部分原始匹配。我们使用汉明距离(hamming distance)作为两个特征描述符之间相似性的度量。请注意,我们有许多不正确的匹配。

Step4 计算Homography

当我们在两个图像中有4个或更多对应点时,可以计算单应性。上一节中介绍的自动功能匹配并不总能产生100%准确的匹配。20-30%的比赛不正确并不罕见。幸运的是,findHomography方法利用称为随机抽样一致性算法(RANSAC)的强大估计技术,即使在存在大量不良匹配的情况下也能产生正确的结果。RANSAC具体介绍见:

https://www.cnblogs.com/xingshansi/p/6763668.html

https://blog.csdn.net/zinnc/article/details/52319716

Step5 图像映射

一旦计算出准确的单应性,我可以应用于一个图像中的所有像素,以将其映射到另一个图像。这是使用OpenCV中的warpPerspective函数完成的。

2.2 代码

在本节中,我们将使用OpenCV呈现用于图像对齐的C ++和Python代码。所处理的对象为对本文第二张图所示的三张图。其中第一张图为参考图像,第二张图为用于对齐的图,第三张图为结果图像。第一张图和第二张图特征点匹配的结果如下图所示:

所有代码见:

https://github.com/luohenyueji/OpenCV-Practical-Exercise

C++代码如下:

  1 // OpenCV_Align.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
  2 //
  3  
  4 #include "pch.h"   //opencv4.0要去掉
  5 #include <iostream>
  6  
  7 #include <opencv2/opencv.hpp>
  8 #include "opencv2/xfeatures2d.hpp"
  9 #include "opencv2/features2d.hpp"
 10  
 11 using namespace std;
 12 using namespace cv;
 13 using namespace cv::xfeatures2d;
 14  
 15 //最大特征点数
 16 const int MAX_FEATURES = 500;
 17 //好的特征点数
 18 const float GOOD_MATCH_PERCENT = 0.15f;
 19  
 20 /**
 21  * @brief 图像对齐
 22  *
 23  * @param im1 对齐图像
 24  * @param im2 模板图像
 25  * @param im1Reg 输出图像
 26  * @param h
 27  */
 28 void alignImages(Mat &im1, Mat &im2, Mat &im1Reg, Mat &h)
 29 {
 30     // Convert images to grayscale
 31     Mat im1Gray, im2Gray;
 32     //转换为灰度图
 33     cvtColor(im1, im1Gray, CV_BGR2GRAY);   //opencv4.0这里CV_BGR2GRAY要改成COLOR_BGR2GRAY
 34     cvtColor(im2, im2Gray, CV_BGR2GRAY);
 35  
 36     // Variables to store keypoints and descriptors
 37     //关键点
 38     std::vector<KeyPoint> keypoints1, keypoints2;
 39     //特征描述符
 40     Mat descriptors1, descriptors2;
 41  
 42     // Detect ORB features and compute descriptors. 计算ORB特征和描述子
 43     Ptr<Feature2D> orb = ORB::create(MAX_FEATURES);
 44     orb->detectAndCompute(im1Gray, Mat(), keypoints1, descriptors1);
 45     orb->detectAndCompute(im2Gray, Mat(), keypoints2, descriptors2);
 46  
 47     // Match features. 特征点匹配
 48     std::vector<DMatch> matches;
 49     //汉明距离进行特征点匹配
 50     Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce-Hamming");
 51     matcher->match(descriptors1, descriptors2, matches, Mat());
 52  
 53     // Sort matches by score 按照特征点匹配结果从优到差排列
 54     std::sort(matches.begin(), matches.end());
 55  
 56     // Remove not so good matches 移除不好的特征点
 57     const int numGoodMatches = matches.size() * GOOD_MATCH_PERCENT;
 58     matches.erase(matches.begin() + numGoodMatches, matches.end());
 59  
 60     // Draw top matches
 61     Mat imMatches;
 62     //画出特征点匹配图
 63     drawMatches(im1, keypoints1, im2, keypoints2, matches, imMatches);
 64     imwrite("matches.jpg", imMatches);             //两图之间的特征点匹配关系图
 65  
 66     // Extract location of good matches
 67     std::vector<Point2f> points1, points2;
 68  
 69     //保存对应点
 70     for (size_t i = 0; i < matches.size(); i++)
 71     {
 72         //queryIdx是对齐图像的描述子和特征点的下标。
 73         points1.push_back(keypoints1[matches[i].queryIdx].pt);
 74         //queryIdx是是样本图像的描述子和特征点的下标。
 75         points2.push_back(keypoints2[matches[i].trainIdx].pt);
 76     }
 77  
 78     // Find homography 计算Homography,RANSAC随机抽样一致性算法
 79     h = findHomography(points1, points2, RANSAC);
 80  
 81     // Use homography to warp image 映射
 82     warpPerspective(im1, im1Reg, h, im2.size());
 83 }
 84  
 85 int main()
 86 {
 87     // Read reference image 读取参考图像
 88     string refFilename("./image/form.jpg");        //基准图像
 89     cout << "Reading reference image : " << refFilename << endl;
 90     Mat imReference = imread(refFilename);
 91  
 92     // Read image to be aligned 读取对准图像
 93     string imFilename("./image/scanned-form.jpg");   //待校准图像
 94     cout << "Reading image to align : " << imFilename << endl;
 95     Mat im = imread(imFilename);
 96  
 97     // Registered image will be resotred in imReg.
 98     // The estimated homography will be stored in h.
 99     //结果图像,单应性矩阵
100     Mat imReg, h;
101  
102     // Align images
103     cout << "Aligning images ..." << endl;
104     alignImages(im, imReference, imReg, h);
105  
106     // Write aligned image to disk.
107     string outFilename("aligned.jpg");   //校准图
108     cout << "Saving aligned image : " << outFilename << endl;
109     imwrite(outFilename, imReg);
110  
111     // Print estimated homography
112     cout << "Estimated homography : \n" << h << endl;
113     return 0;
114 }

 

Python代码如下:
 1 from __future__ import print_function
 2 import cv2
 3 import numpy as np
 4  
 5  
 6 MAX_MATCHES = 500
 7 GOOD_MATCH_PERCENT = 0.15
 8  
 9  
10 def alignImages(im1, im2):
11  
12   # Convert images to grayscale
13   im1Gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)
14   im2Gray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)
15   
16   # Detect ORB features and compute descriptors.
17   orb = cv2.ORB_create(MAX_MATCHES)
18   keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None)
19   keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None)
20   
21   # Match features.
22   matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING)
23   matches = matcher.match(descriptors1, descriptors2, None)
24   
25   # Sort matches by score
26   matches.sort(key=lambda x: x.distance, reverse=False)
27  
28   # Remove not so good matches
29   numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT)
30   matches = matches[:numGoodMatches]
31  
32   # Draw top matches
33   imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None)
34   cv2.imwrite("matches.jpg", imMatches)
35   
36   # Extract location of good matches
37   points1 = np.zeros((len(matches), 2), dtype=np.float32)
38   points2 = np.zeros((len(matches), 2), dtype=np.float32)
39  
40   for i, match in enumerate(matches):
41     points1[i, :] = keypoints1[match.queryIdx].pt
42     points2[i, :] = keypoints2[match.trainIdx].pt
43   
44   # Find homography
45   h, mask = cv2.findHomography(points1, points2, cv2.RANSAC)
46  
47   # Use homography
48   height, width, channels = im2.shape
49   im1Reg = cv2.warpPerspective(im1, h, (width, height))
50   
51   return im1Reg, h
52  
53  
54 if __name__ == '__main__':
55   
56   # Read reference image
57   refFilename = "./image/form.jpg"
58   print("Reading reference image : ", refFilename)
59   imReference = cv2.imread(refFilename, cv2.IMREAD_COLOR)
60  
61   # Read image to be aligned
62   imFilename = "./image/scanned-form.jpg"
63   print("Reading image to align : ", imFilename);  
64   im = cv2.imread(imFilename, cv2.IMREAD_COLOR)
65   
66   print("Aligning images ...")
67   # Registered image will be resotred in imReg. 
68   # The estimated homography will be stored in h. 
69   imReg, h = alignImages(im, imReference)
70   
71   # Write aligned image to disk. 
72   outFilename = "aligned.jpg"
73   print("Saving aligned image : ", outFilename); 
74   cv2.imwrite(outFilename, imReg)
75  
76   # Print estimated homography
77   print("Estimated homography : \n",  h) 
 

3 参考https://www.learnopencv.com/image-alignment-feature-based-using-opencv-c-python/

posted @ 2019-12-06 10:07  Parallax  阅读(1240)  评论(0编辑  收藏  举报