1、函式定義
//直方圖均衡化
struct stPGMImage* EqualHist(struct stPGMImage* image);
2、函式實現
struct stPGMImage* EqualHist(struct stPGMImage* image_src)
{
if (image_src == NULL)
return NULL;
int gray[256] = { 0 };
double gray_prob[256] = { 0 };
double gray_distribution[256] = { 0 };
unsigned char gray_equal[256] = { 0 };
struct stPGMImage* result = (struct stPGMImage*)malloc(sizeof(struct stPGMImage));
result->height = image_src->height;
result->width = image_src->width;
result->maxraw = image_src->maxraw;
result->type = image_src->type;
result->data = (unsigned char*)malloc(sizeof(unsigned char) * result->width * result->height);
memcpy(result->data, image_src->data, image_src->height * image_src->width);
for (int y = 0; y < image_src->height; y++)
{
unsigned char* p = (unsigned char*)(result->data + y * result->width);
for (int x = 0; x < image_src->width; x++)
{
unsigned char vaule = p[x];
gray[vaule]++;
}
}
for (int i = 0; i < 256; i++)
{
gray_prob[i] = ((double)gray[i] / (image_src->width * image_src->height));
}
gray_distribution[0] = gray_prob[0];
for (int i = 1; i < 256; i++)
{
gray_distribution[i] = gray_distribution[i - 1] + gray_prob[i];
}
for (int i = 0; i < 256; i++)
{
gray_equal[i] = (unsigned char)((256 - 1) * gray_distribution[i] + 0.5);
}
for (int y = 0; y < image_src->height; y++)
{
unsigned char* p = (unsigned char*)(result->data + y * result->width);
for (int x = 0; x < image_src->width; x++)
{
p[x] = gray_equal[p[x]];
}
}
return result;
}
3、效果圖