Opencv 三种方法提取图片亮度

方法一

计算图片在灰度图上的均值和方差

当存在亮度异常时,均值会偏离均值点(可以假设为128),方差也会偏小;通过计算灰度图的均值和方差,评估图像是否存在过曝光或曝光不足

int light(string imgName)
{
	//Mat 转 IplImage
	Mat M= imread(imgName);
	IplImage *image = &IplImage(M);
	IplImage * gray = cvCreateImage(cvGetSize(image), image->depth, 1);
	//转为灰度图片
	cvCvtColor(image, gray, CV_BGR2GRAY);
	double sum = 0;
	double avg = 0;
	CvScalar scalar;
	int ls[256];
	for (int i = 0; i<256; i++)
		ls[i] = 0;
	for (int i = 0; i<gray->height; i++)
	{
		for (int j = 0; j<gray->width; j++)
		{
			scalar = cvGet2D(gray, i, j);
			sum += (scalar.val[0] - 128);
			int x = (int)scalar.val[0];
			ls[x]++;
		}
	}
	avg = sum / (gray->height * gray->width);
	double total = 0;
	double mean = 0;
	for (int i = 0; i<256; i++)
	{
		total += abs(i - 128 - avg)* ls[i];
	}
	mean = total / (gray->height * gray->width);
	double cast = abs(avg / mean);
	cout << imgName << "亮度异常值:" << cast << endl;
	if (cast>1) 
	{
		if (avg > 0)
		{
			cout << "亮度异常 过亮" << avg << endl;
			return 1;
		}
		else {
			cout << "亮度异常 过暗" << avg << endl;
			return -1;
		}
	}
	else
	{
		cout << "normal" << endl;
		return 0;
	}
}

方法二

Opencv 三种方法提取图片亮度_第1张图片

根据hsl中l=(max(R,G,B)+min(R,G,B))/2

用cvAvg分别计算R,G,B三通道平均值,最大与最小的平均值作为亮度

int light2(string imgName)
{
	Mat img,gray;
	img = imread(imgName);
	IplImage *img1 = &IplImage(img);
	CvScalar cs;
	const char * c = imgName.c_str();
	IplImage *src1;
	src1 = cvLoadImage(c);

	cs = cvAvg(src1);
	double max1=max(cs.val[0],cs.val[1]), min1=min(cs.val[0],cs.val[1]);
	cout <<"R"<<cs.val[0] << endl;
	cout <<"G"<< cs.val[1] << endl;
	cout <<"B"<< cs.val[2] << endl;
	cout << "亮度为" << (max(max1,cs.val[2]) + min(min1,cs.val[2]))/2 << endl;
	return 0;
}

方法三

转为灰度图片,用cvAvg计算像素平均值作为亮度

int light(string imgName)
{
	Mat img;
	img = imread(imgName,0);
	Scalar scalar = mean(img);
	return scalar.val[0];
}

测试

int main()
{
string img1Name,img2Name;
	img1Name = "brightKurt.jpg";
	img2Name = "darkKurt.jpg";
	cout << "图片1 brightKurt" << endl;
	cout << "方法1" << endl;
	light(img1Name);
	cout << "方法2" << endl;
	light2(img1Name);
	cout << "方法3" << endl;
	light3(img1Name);
	cout << endl << endl<< "图片2 darkKurt" << endl;
	cout << "方法1" << endl;
	light(img2Name);
	cout << "方法2" << endl;
	light2(img2Name);
	cout << "方法3" << endl;
	light3(img2Name);
	Mat img1, img2;
	img1 = imread(img1Name);
	img2 = imread(img2Name);
	imshow("img1 bright Kurt", img1);
	imshow("img2 dark Kurt", img2);
	
	waitKey(0);
	return 0;
}

Opencv 三种方法提取图片亮度_第2张图片

你可能感兴趣的:(openCV,图片亮度)