区域紧密度检测 opencv

71 篇文章 7 订阅
32 篇文章 10 订阅

紧密度=轮廓面积/最小外接矩形面积

 

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

运行结果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酷小川

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值