opencv——对象提取与测量

时间:2023-03-10 02:59:17
opencv——对象提取与测量

opencv——对象提取与测量

 #include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h> using namespace cv;
using namespace std; int main(int argc, char** argv) {
Mat src = imread("test.jpg");
if (src.empty()) {
printf("could not load image...\n");
return -;
}
namedWindow("input image", CV_WINDOW_AUTOSIZE);
imshow("input image", src); //高斯降噪
Mat blurImage;
GaussianBlur(src, blurImage, Size(, ), , );
imshow("blur", blurImage); Mat gray_src, binary;
cvtColor(blurImage, gray_src, COLOR_BGR2GRAY);
threshold(gray_src, binary, , , THRESH_BINARY | THRESH_TRIANGLE);//颜色单一的图像使用THRESH_TRIANGLE
imshow("binary", binary); // 形态学闭操作,去掉空洞
Mat morphImage;
Mat kernel = getStructuringElement(MORPH_RECT, Size(, ), Point(-, -));
morphologyEx(binary, morphImage, MORPH_CLOSE, kernel, Point(-, -), );
imshow("morphology", morphImage); // 获取最大轮廓
vector<vector<Point>> contours;
vector<Vec4i> hireachy;
findContours(morphImage, contours, hireachy, CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
Mat connImage = Mat::zeros(src.size(), CV_8UC3);
for (size_t t = ; t < contours.size(); t++) {
Rect rect = boundingRect(contours[t]);
if (rect.width < src.cols / ) continue;//轮廓筛选
if (rect.width > (src.cols - )) continue;//轮廓筛选
double area = contourArea(contours[t]);
double len = arcLength(contours[t], true);
drawContours(connImage, contours, static_cast<int>(t), Scalar(, , ), , , hireachy);
printf("area of star could : %f\n", area);
printf("length of star could : %f\n", len);
}
imshow("result", connImage); waitKey();
return ;
}