opencv的形状匹配及算法C++
时间: 2023-11-17 09:04:54 浏览: 149
opencv形状匹配
OpenCV中的形状匹配算法可以通过计算轮廓的Hu矩来实现,具体步骤如下:
1. 读取并二值化图像,提取目标轮廓:
```c++
Mat src = imread("image.jpg");
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE);
```
2. 计算目标轮廓的Hu矩:
```c++
Moments mu = moments(contours[0], false);
double hu[7];
HuMoments(mu, hu);
```
3. 读取并二值化模板图像,提取模板轮廓:
```c++
Mat tpl = imread("template.jpg");
Mat gray_tpl, binary_tpl;
cvtColor(tpl, gray_tpl, COLOR_BGR2GRAY);
threshold(gray_tpl, binary_tpl, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
vector<vector<Point>> contours_tpl;
vector<Vec4i> hierarchy_tpl;
findContours(binary_tpl, contours_tpl, hierarchy_tpl, RETR_LIST, CHAIN_APPROX_SIMPLE);
```
4. 计算模板轮廓的Hu矩:
```c++
Moments mu_tpl = moments(contours_tpl[0], false);
double hu_tpl[7];
HuMoments(mu_tpl, hu_tpl);
```
5. 计算目标轮廓和模板轮廓的Hu矩的差异(即Hu矩距离):
```c++
double dist = matchShapes(contours[0], contours_tpl[0], CONTOURS_MATCH_I1, 0);
```
6. 根据Hu矩距离判断目标轮廓和模板轮廓的相似度:
```c++
if (dist < 0.1) {
cout << "匹配成功!" << endl;
} else {
cout << "匹配失败!" << endl;
}
```
完整的代码如下:
```c++
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main() {
Mat src = imread("image.jpg");
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE);
Moments mu = moments(contours[0], false);
double hu[7];
HuMoments(mu, hu);
Mat tpl = imread("template.jpg");
Mat gray_tpl, binary_tpl;
cvtColor(tpl, gray_tpl, COLOR_BGR2GRAY);
threshold(gray_tpl, binary_tpl, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
vector<vector<Point>> contours_tpl;
vector<Vec4i> hierarchy_tpl;
findContours(binary_tpl, contours_tpl, hierarchy_tpl, RETR_LIST, CHAIN_APPROX_SIMPLE);
Moments mu_tpl = moments(contours_tpl[0], false);
double hu_tpl[7];
HuMoments(mu_tpl, hu_tpl);
double dist = matchShapes(contours[0], contours_tpl[0], CONTOURS_MATCH_I1, 0);
if (dist < 0.1) {
cout << "匹配成功!" << endl;
} else {
cout << "匹配失败!" << endl;
}
return 0;
}
```
阅读全文