OpenCV轮廓匹配原理介绍与使用
1. 轮廓匹配的基本概念
轮廓匹配(Contour Matching)是计算机视觉中的一种重要方法,主要用于比较两个轮廓的相似性。它广泛应用于目标识别、形状分析、手势识别等领域。
在 OpenCV 中,轮廓匹配主要基于形状匹配算法,其中 matchShapes
是核心函数。该函数用于计算两个轮廓之间的相似度,返回一个数值,该数值越小表示两个轮廓越相似。
2. 轮廓匹配的算法原理
Hu矩(Hu Moments)是由Ming-Kuei Hu在1962年提出。OpenCV 采用 Hu 矩(Hu Moments)进行轮廓匹配。Hu 矩是一组不变矩,可以用于描述图像的形状特征,并且具有旋转、缩放和平移不变性。Hu矩是通过对图像的归一化中心矩进行特定的线性组合得到的。具体而言,它们是基于二阶和三阶的归一化中心矩计算的。
Hu 矩由 7 个不变矩组成:
I 1 = η 20 + η 02 I 2 = ( η 20 − η 02 ) 2 + 4 η 11 2 I 3 = ( η 30 − 3 η 12 ) 2 + ( 3 η 21 − η 03 ) 2 I 4 = ( η 30 + η 12 ) 2 + ( η 21 + η 03 ) 2 I 5 = ( η 30 − 3 η 12 ) ( η 30 + η 12 ) [ ( η 30 + η 12 ) 2 − 3 ( η 21 + η 03 ) 2 ] + ( 3 η 21 − η 03 ) ( η 21 + η 03 ) [ 3 ( η 30 + η 12 ) 2 − ( η 21 + η 03 ) 2 ] I 6 = ( η 20 − η 02 ) [ ( η 30 + η 12 ) 2 − ( η 21 + η 03 ) 2 ] + 4 η 11 ( η 30 + η 12 ) ( η 21 + η 03 ) I 7 = ( 3 η 21 − η 03 ) ( η 30 + η 12 ) [ ( η 30 + η 12 ) 2 − 3 ( η 21 + η 03 ) 2 ] − ( η 30 − 3 η 12 ) ( η 21 + η 03 ) [ 3 ( η 30 + η 12 ) 2 − ( η 21 + η 03 ) 2 ] \begin{align*}I_1 &= \eta_{20} + \eta_{02} \\I_2 &= (\eta_{20} - \eta_{02})^2 + 4\eta_{11}^2 \\I_3 &= (\eta_{30} - 3\eta_{12})^2 + (3\eta_{21} - \eta_{03})^2 \\I_4 &= (\eta_{30} + \eta_{12})^2 + (\eta_{21} + \eta_{03})^2 \\I_5 &= (\eta_{30} - 3\eta_{12})(\eta_{30} + \eta_{12})\left[(\eta_{30} + \eta_{12})^2 - 3(\eta_{21} + \eta_{03})^2\right] \\&\quad + (3\eta_{21} - \eta_{03})(\eta_{21} + \eta_{03})\left[3(\eta_{30} + \eta_{12})^2 - (\eta_{21} + \eta_{03})^2\right] \\I_6 &= (\eta_{20} - \eta_{02})\left[(\eta_{30} + \eta_{12})^2 - (\eta_{21} + \eta_{03})^2\right] \\&\quad + 4\eta_{11}(\eta_{30} + \eta_{12})(\eta_{21} + \eta_{03}) \\I_7 &= (3\eta_{21} - \eta_{03})(\eta_{30} + \eta_{12})\left[(\eta_{30} + \eta_{12})^2 - 3(\eta_{21} + \eta_{03})^2\right] \\&\quad - (\eta_{30} - 3\eta_{12})(\eta_{21} + \eta_{03})\left[3(\eta_{30} + \eta_{12})^2 - (\eta_{21} + \eta_{03})^2\right]\end{align*} I1I2I3I4I5I6I7=η20+η02=(η20−η02)2+4η112=(η30−3η12)2+(3η21−η03)2=(η30+η12)2+(η21+η03)2=(η30−3η12)(η30+η12)[(η30+η12)2−3(η21+η03)2]+(3η21−η03)(η21+η03)[3(η30+η12)2−(η21+η03)2]=(η20−η02)[(η30+η12)2−(η21+η03)2]+4η11(η30+η12)(η21+η03)=(3η21−η03)(η30+η12)[(η30+η12)2−3(η21+η03)2]−(η30−3η12)(η21+η03)[3(η30+η12)2−(η21+η03)2]
通过计算 Hu 矩的值,OpenCV 使用 matchShapes
进行轮廓匹配.
需要注意的是,虽然Hu矩对常见的几何变换具有不变性,但在实际应用中,噪声、遮挡和分割质量等因素可能影响其稳定性。因此,在处理实际问题时,需综合考虑这些因素对Hu矩计算的影响。
3. matchShapes
函数介绍
3.1 函数原型
double matchShapes(InputArray contour1, InputArray contour2, int method, double parameter);
3.2 参数说明
contour1
:第一个轮廓(vector<Point>
格式)。contour2
:第二个轮廓(vector<Point>
格式)。method
:匹配方法,可选值:CONTOURS_MATCH_I1
: d ( I ) = ∑ ∣ 1 I i ( 1 ) − 1 I i ( 2 ) ∣ d(I)=\sum\begin{vmatrix} \frac{1}{I_i^{(1)}}-\frac{1}{I_i^{(2)}} \end{vmatrix} d(I)=∑ Ii(1)1−Ii(2)1 CONTOURS_MATCH_I2
: d ( I ) = ∣ I i ( 1 ) − I i ( 2 ) ∣ d(I)=\begin{vmatrix}I_i^{(1)}-I_i^{(2)}\end{vmatrix} d(I)= Ii(1)−Ii(2) CONTOURS_MATCH_I3
: d ( I ) = ∑ ∣ 1 i 1 ( 1 ) − 1 i i ( 2 ) ∣ d(I)=\sum\begin{vmatrix} \frac{1}{i_1^{(1)}}-\frac{1}{i_i^{(2)}} \end{vmatrix} d(I)=∑ i1(1)1−ii(2)1
parameter
:该参数在当前版本未使用,通常填0
。
3.3 返回值
返回两个轮廓之间的相似性分数,数值越小,轮廓越相似
。
4. 轮廓匹配
4.1示例代码1:直接匹配
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
int main()
{
// 1. 读取输入图像和模板图像,并转换为灰度图
Mat inputImg = imread("E:/image/pic1.png");
Mat templateImg = imread("E:/image/templ.png");
if (inputImg.empty() || templateImg.empty()) {
cerr << "图像加载失败!" << endl;
return -1;
}
Mat grayInput, grayTemplate;
cvtColor(inputImg, grayInput, COLOR_BGR2GRAY);
cvtColor(templateImg, grayTemplate, COLOR_BGR2GRAY);
// 2. 对图像应用阈值处理得到二值图像
Mat binaryInput, binaryTemplate;
threshold(grayInput, binaryInput, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
threshold(grayTemplate, binaryTemplate, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
// 3. 检测轮廓
vector<vector<Point>> contoursInput, contoursTemplate;
vector<Vec4i> hierarchy;
findContours(binaryInput, contoursInput, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
findContours(binaryTemplate, contoursTemplate, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 4. 假设模板图像只包含一个主要轮廓,取第一个轮廓作为模板
if (contoursTemplate.empty()) {
cerr << "模板轮廓检测失败!" << endl;
return -1;
}
cout << contoursTemplate.size();
vector<Point> templateContour = contoursTemplate[0];
// 5. 遍历输入图像中的所有轮廓,计算与模板轮廓的匹配度
for (size_t i = 0; i < contoursInput.size(); i++) {
double matchScore = matchShapes(templateContour, contoursInput[i], CONTOURS_MATCH_I1, 0);
cout << "轮廓 " << i << " 匹配分数: " << matchScore << endl;
// 在输入图像上绘制轮廓并标注匹配分数
if (matchScore<0.05)
{
drawContours(inputImg, contoursInput, static_cast<int>(i), Scalar(0, 255, 0), 2);
}
Moments m = moments(contoursInput[i]);
int cx = static_cast<int>(m.m10 / m.m00);
int cy = static_cast<int>(m.m01 / m.m00);
putText(inputImg, format("%.2f", matchScore), Point(cx, cy), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255), 1);
}
//6. 显示结果\n
imshow("输入图像轮廓匹配", inputImg);
imshow("模板图像", templateImg);
waitKey(0);
return 0;
}
绿色为找到的轮廓
4. 2示例代码2:hu距匹配
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
int main()
{
// 1. 读取输入图像和模板图像,并转换为灰度图
Mat inputImg = imread("E:/image/pic1.png");
Mat templateImg = imread("E:/image/templ.png");
if (inputImg.empty() || templateImg.empty()) {
cerr << "图像加载失败!" << endl;
return -1;
}
Mat grayInput, grayTemplate;
cvtColor(inputImg, grayInput, COLOR_BGR2GRAY);
cvtColor(templateImg, grayTemplate, COLOR_BGR2GRAY);
// 2. 对图像应用阈值处理得到二值图像
Mat binaryInput, binaryTemplate;
threshold(grayInput, binaryInput, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
threshold(grayTemplate, binaryTemplate, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
// 3. 检测轮廓
vector<vector<Point>> contoursInput, contoursTemplate;
vector<Vec4i> hierarchy;
findContours(binaryInput, contoursInput, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
findContours(binaryTemplate, contoursTemplate, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 4. 假设模板图像只包含一个主要轮廓,取第一个轮廓作为模板
if (contoursTemplate.empty()) {
cerr << "模板轮廓检测失败!" << endl;
return -1;
}
cout << contoursTemplate.size();
vector<Point> templateContour = contoursTemplate[0];
Moments mTemplate = moments(contoursTemplate[0]);
Mat huTemplate;
HuMoments(mTemplate, huTemplate);
// 5. 遍历输入图像中的所有轮廓,计算与模板轮廓的匹配度
for (size_t i = 0; i < contoursInput.size(); i++) {
// 在输入图像上绘制轮廓并标注匹配分数
Moments m = moments(contoursInput[i]);
Mat hu;
HuMoments(m, hu);
double matchScore = matchShapes(hu, huTemplate, CONTOURS_MATCH_I1, 0);
cout << "轮廓 " << i << " 匹配分数: " << matchScore << endl;
if (matchScore < 0.005)
{
drawContours(inputImg, contoursInput, static_cast<int>(i), Scalar(0, 255, 0), 2);
}
int cx = static_cast<int>(m.m10 / m.m00);
int cy = static_cast<int>(m.m01 / m.m00);
putText(inputImg, format("%.2f", matchScore), Point(cx, cy), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255), 1);
}
//6. 显示结果\n
imshow("输入图像轮廓匹配", inputImg);
imshow("模板图像", templateImg);
waitKey(0);
return 0;
}
5. 轮廓匹配的应用场景
OpenCV 的 matchShapes
通过 Hu 矩计算轮廓的相似性,是一种高效的轮廓匹配方法。适用于各种形状分析任务,在实际应用中,可以结合其他特征进一步优化匹配结果。
常用场景
- 目标识别:如手写字符识别、手势识别,车牌识别等。
- 工业检测:用于检测物品形状偏差。
- 医学影像分析:对比医学影像中的病变轮廓。
- 形状检索:在数据库中寻找相似形状的对象。