本文实例为大家分享了Opencv3实现对象提取与测量的具体代码,供大家参考,具体内容如下
案例背景:下图为一张卫星拍摄的图片,要获取其中岛屿的周长和面积
方案思路:高斯模糊去噪,灰度二值化提取轮廓,闭操作填充缝隙 或小的孔洞,寻找轮廓,通过轮廓特征选择轮廓
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
#include<opencv2\opencv.hpp>
using namespace cv;
using namespace std;
int main( int arc, char ** argv) {
Mat src = imread( "1.jpg" );
namedWindow( "input" , CV_WINDOW_AUTOSIZE);
imshow( "input" , src);
//该高斯模糊去噪
GaussianBlur(src, src, Size(15, 15), 0, 0);
imshow( "output1" , src);
//灰度二值化
Mat gray,binary;
cvtColor(src, gray, CV_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);
imshow( "output2" , binary);
//闭操作
Mat kernel = getStructuringElement(MORPH_RECT, Size(4, 4));
morphologyEx(binary, binary, MORPH_CLOSE, kernel);
imshow( "output3" , binary);
//寻找轮廓
vector<vector<Point>>contours;
Mat draw = Mat::zeros(src.size(), CV_8UC3);
findContours(binary, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for ( int i = 0; i < contours.size(); i++) {
Rect rect = boundingRect(contours[i]);
if (rect.width < src.cols / 2 || rect.height>src.rows-20) continue ; //筛选轮廓
drawContours(draw, contours, i, Scalar(0, 0, 255), 1);
printf ( "area:%f\n" , contourArea(contours[i]));
printf ( "length:%f\n" ,arcLength(contours[i], true ));
}
imshow( "output4" , draw);
waitKey(0);
return 0;
}
|
原图像
高斯模糊
二值化
闭操作
效果图
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_24946843/article/details/82776553