#include <opencv2/opencv.hpp>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
int main()
{
Mat srcImage = imread("/home/pi/works/nongyuchang/mianji/global.jpg", 0);
imshow("原始图", srcImage);
Mat dstImage = Mat::zeros(srcImage.rows, srcImage.cols, CV_8UC3);
threshold(srcImage, srcImage, 200, 255, 3);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(srcImage, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
int index = 0;
for (; index >= 0; index = hierarchy[index][0])
{
Scalar color(rand() & 255, rand() & 255, rand() & 255);
drawContours(dstImage, contours, index, color, FILLED, 8, hierarchy);
}
Mat drawing = Mat::zeros(srcImage.size(), CV_8UC3);
for (unsigned int i = 0; i < contours.size(); i++)
{
Scalar color1 = Scalar(0, 0, 255);
drawContours(drawing, contours, i, color1, 1, 8, vector<Vec4i>(), 0, Point());
}
for (unsigned i = 0; i < contours.size(); i++)
{
if (contourArea(contours[i]) > 1000)
{
cout << "苹果的面积为:" << contourArea(contours[i]) << endl;
double R =sqrt(contourArea(contours[i])/3.141592654);
cout << "R1为:" << R << endl;
double S=4*3.141592654*R*R;
cout << "表面积1为:" << S << endl;
}
if (arcLength(contours[i], true)>1000)
{
cout << "苹果的周长为:" << arcLength(contours[i], true) << endl;
double r=arcLength(contours[i], true)/(2*3.141592654);
cout << "R2为:" << r << endl;
double s=4*3.1415926*r*r;
cout << "表面积2为:" << s << endl;
double L = 4 * 3.141592654*contourArea(contours[i]) / (arcLength(contours[i], true)*arcLength(contours[i], true));
cout << "圆度率为:" << L << endl;
}
double A =sqrt(contourArea(contours[i])/3.141592654);
double a=4*3.141592654*A*A;
double B=arcLength(contours[i], true)/(2*3.141592654);
double b=4*3.1415926*B*B;
double C=(a+b)/2;
cout << "最终表面积为:" << C << endl;
}
imshow("提取的轮廓图", drawing);
waitKey(0);
}
评论0