我正在进行自己的直方图均衡实现,但它会生成一些令人毛骨悚然的图像。 我得到了每个像素的颜色强度,然后通过将颜色强度除以图片中的像素数得到概率。然后,我做了一个累积概率数组,我后来乘以255并将其平铺。该值最终成为新颜色。我错过了什么?
我的代码:
void pixelFrequency(Mat img, int intensity[])
{
for (int j = 0; j < img.rows; j++)
for (int i = 0; i < img.cols; i++)
intensity[int(img.at<uchar>(j, i))]++;
}
void pixelProbability(Mat img, double probability[], int intensity[])
{
for (int i = 0; i < 256; i++)
probability[i] = intensity[i] / double(img.rows * img.cols);
}
void cumuProbability(double probability[], double cumulativeProbability[])
{
cumulativeProbability[0] = probability[0];
for (int i = 1; i < 256; i++)
cumulativeProbability[i] = probability[i] + cumulativeProbability[i - 1];
}
void histogramEqualization(Mat& img, int intensity[], double probability[], double cumulativeProbability[])
{
pixelFrequency(img, intensity);
pixelProbability(img, probability, intensity);
cumuProbability(probability, cumulativeProbability);
for (int i = 0; i < 256; i++)
cumulativeProbability[i] = floor(cumulativeProbability[i] * 255);
for (int j = 0; j < img.rows; j++)
{
for (int i = 0; i < img.cols; i++)
{
//int color = cumulativeProbability[int(img.at<uchar>(i, j))];
img.at<uchar>(j, i) = cumulativeProbability[int(img.at<uchar>(i, j))];
}
}
}
int main()
{
int intensity[256] = { 0 };
double probability[256] = { 0 };
double cumulativeProbability[256] = { 0 };
Mat img = imread("ex.jpg", CV_LOAD_IMAGE_GRAYSCALE);
histogramEqualization(img, intensity, probability, cumulativeProbability);
namedWindow("image", WINDOW_AUTOSIZE);
imshow("image", img);
waitKey(0);
return 0;
}