发新帖

[C/VC/C++] [Cv] 基于opencv计算目标图像的面积

零下一度 2023-1-5 842


需求:计算目标图像(白色区域)的面积

解决思路:二值分割+形态学处理+轮廓提取

#include <opencv2\opencv.hpp>
#include <math.h>
using namespace std;
using namespace cv;
bool verify(vector<Point> input, long min);
const int threshold_value = 80;
const int max_binary_value = 255;
int main()
{
	Mat src = imread("xxx.jpg");
	if (!src.data)
	{
		cout << "src image load failed!" << endl;
		return -1;
	}
	Mat blur, gray, Threshold;
	GaussianBlur(src, blur, Size(5, 5), 0, 0);
	cvtColor(blur, gray, COLOR_BGR2GRAY);
	
	/*图像二值化*/
	threshold(gray, Threshold, threshold_value, max_binary_value, THRESH_BINARY);
	/*形态学闭操作*/
	Mat morph;
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
	morphologyEx(Threshold, morph, MORPH_CLOSE, kernel, Point(-1, -1), 2);
	/*查找轮廓*/
	vector< vector<Point> > contours;
	vector<Vec4i> hierarchy;
	findContours(morph, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
	Mat Draw_img;
	Draw_img.create(src.size(), src.type());
	Draw_img = Scalar(255, 255, 255);
	double sum_Area = 0.0;
	int idx = 0;
	for (; idx >= 0; idx = hierarchy[idx][0])
	{
		if (verify(contours[idx], 10)) //过滤干扰的小轮廓
		{
			Scalar color(rand() & 255, rand() & 255, rand() & 255);
			drawContours(Draw_img, contours, idx, color, FILLED, 8, hierarchy);
			sum_Area += fabs(contourArea(contours[idx]));
		}
	}
	long nRow = gray.rows;
	long nCol = gray.cols;
	cout << "Sum Area:" << sum_Area << endl;
	cout << "Image Area:" << nRow*nCol << endl;
	//cout << "比率:" << (sum_Area) / (nRow*nCol) << endl;
	imshow("Draw", Draw_img);
	waitKey();
	return 0;
}
bool verify(vector<Point> input, long min)
{
	float area = fabs(contourArea(input));
	if (area > min)
		return true;
	else
		return false;
}


结果如图:






参考文献:

[1]https://blog.csdn.net/weicao1990/article/details/73135436

[2]https://docs.opencv.org/4.x/d7/d1b/group__imgproc__misc.html#gaa9e58d2860d4afa658ef70a9b1115576

[3]https://blog.csdn.net/weixin_39539602/article/details/116001568




@CSDN




最新回复 (0)
返回
零下一度
主题数
931
帖子数
0
注册排名
1