OpenCV——直方图均衡化

1、入门

这里写图片描述

实现代码

#include
using namespace std;
void main()
{
	system("COLOR 2F");
	int src[4][4] = { 255, 128, 200, 50, 50, 200, 255, 50, 255, 200, 128, 128, 200, 200, 255, 50 };
	int bin = 256;
	int b[4][4];
	float sumprobability = 0;
	for (int k = 0; k < bin; k++)
	{
		int s = 0;
		for (int i = 0; i < 4; i++)
		{
			for (int j = 0; j < 4; j++)
			{
				if (k == src[i][j])
				{
					s++;
				}
			}
		}
		if (s != 0)
		{
			cout << "灰度值为" << k << "的像素有" << s << "个" << endl;
			float probability = (float)s / 16;
			cout << "灰度值为" << k << "的像素出现的概率为" << probability << endl;
			sumprobability += probability;
			cout << "灰度值为" << k << "的像素累计概率为" << sumprobability << endl;
			cout << endl;
			for (int i = 0; i < 4; i++)
			{
				for (int j = 0; j < 4; j++)
				{
					if (k == src[i][j])
						b[i][j] = sumprobability * 255 + 0.5;  //四舍五入
				}
			}
		}
	}

	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			cout << b[i][j] << " ";
		}
		cout << endl;
	}
	system("pause");
}

结果
这里写图片描述

2、自写直方图均衡化与opencv函数对比

#include
#include
#include
#include
using namespace std;
using namespace cv;
void main()
{
	system("COLOR 2F");
	Mat srcImage = imread("1.jpg", 0);
	Mat dstImage = Mat::zeros(srcImage.size(), CV_8UC1);
	imshow("src", srcImage);
	int bin = 256;

	float sumprobability = 0;
	for (int k = 0; k < bin; k++)
	{
		int s = 0;
		for (int j = 0; j < srcImage.rows; j++)
		{
			uchar* data = srcImage.ptr<uchar>(j);
			for (int i = 0; i < srcImage.cols; i++)
			{
				if (k == data[i])
				{
					s++;
				}
			}
		}
		if (s != 0)
		{
			float probability = (float)s / (srcImage.rows*srcImage.cols);
			sumprobability += probability;

			for (int j = 0; j < srcImage.rows; j++)
			{
				uchar* data = srcImage.ptr<uchar>(j);
				uchar* dst = dstImage.ptr<uchar>(j);
				for (int i = 0; i < srcImage.cols; i++)
				{
					if (k == data[i])
					{
						dst[i] = sumprobability * 255 + 0.5;  //四舍五入
					}
				}
			}
		}
	}

	imshow("dst", dstImage);

	// 【1】加载源图像
	Mat srcImage1, dstImage1;
	srcImage1 = imread("1.jpg", 1);


	// 【2】转为灰度图并显示出来
	cvtColor(srcImage1, srcImage1, CV_BGR2GRAY);
	imshow("原始图", srcImage1);

	// 【3】进行直方图均衡化
	equalizeHist(srcImage1, dstImage1);

	// 【4】显示结果
	imshow("经过直方图均衡化后的图", dstImage1);

	waitKey(0);
}

这里写图片描述

规定化:http://www.cnblogs.com/wangguchangqing/p/7098213.html

你可能感兴趣的:(OpenCV,opencv-直方图)