时间:2021-06-28 08:24:39 | 栏目:C代码 | 点击:次
本文实例为大家分享了Opencv3实现对象提取与测量的具体代码,供大家参考,具体内容如下
案例背景:下图为一张卫星拍摄的图片,要获取其中岛屿的周长和面积
方案思路:高斯模糊去噪,灰度二值化提取轮廓,闭操作填充缝隙 或小的孔洞,寻找轮廓,通过轮廓特征选择轮廓
#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; }
原图像
高斯模糊
二值化
闭操作
效果图