#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;
}
|