紧密度=轮廓面积/最小外接矩形面积
#include "iostream";
#include "opencv.hpp"
using namespace std;
using namespace cv;
//紧密度
int main()
{
Mat grayImage, dstImage, resultImage;
Mat Image = imread("1.png");
resultImage = Image.clone();
imshow("原图", Image);
cvtColor(Image, grayImage, COLOR_RGB2GRAY);
threshold(grayImage, dstImage, 100, 255, THRESH_BINARY);
//imshow("二值化", dstImage);
vector<vector<Point>> contours;
vector<Vec4i> hierarcy;
findContours(dstImage, contours, hierarcy, RETR_EXTERNAL, CHAIN_APPROX_NONE);
vector<RotatedRect> box(contours.size()); //最小外接矩形
Point2f rect[4];
float width = 0; //外接矩形的宽和高
float height = 0;
float ratio = 0; //存储长宽比=width/heigth
float area = 0; //最小外接矩形面积
float cps = 0; //紧密度 轮廓面积/最小外接矩形面积
Mat ImageContours = Mat::zeros(dstImage.size(), CV_8UC1); //轮廓图
for (int i = 0; i < contours.size(); i++)
{
box[i] = minAreaRect(contours[i]);
box[i].points(rect); //最小外接矩形的4个端点
width = box[i].size.width;
height = box[i].size.height;
area = width * height;
if (height >= width)
{
float x = 0;
x = height;
height = width;
width = x;
}
ratio = width / height;
cps = contourArea(contours[i], false) / area;
cout << "最小外接矩形面积" << area<< endl;
cout << "轮廓面积"<<contourArea(contours[i], false)<<endl;
cout << "紧密度" << cps << endl;
cout << "宽" << width << " " << "高" << height << "长宽比"<<ratio<<endl;
drawContours(ImageContours,contours,i,Scalar(255),-1,8);
for (int j = 0; j < 4; j++)
{
line(resultImage, rect[j], rect[(j + 1) % 4], Scalar(0, 0, 255), 1, 8);//绘制最小外接矩形的每条边
}
}
namedWindow("结果图", 1);
imshow("结果图", resultImage);
namedWindow("轮廓图", 1);
imshow("轮廓图", ImageContours);
waitKey(0);
return 0;
}
运行结果: