写一个C语言的局部直方图均衡化代码
时间: 2023-05-24 13:02:19 浏览: 106
以下是C语言的局部直方图均衡化代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define BYTE unsigned char // 定义 BYTE 为 unsigned char 类型
void local_histogram_eq(BYTE* src, BYTE* dst, int width, int height, int win_size) {
int i, j, k, t, sum, w, h, shift;
int mid = win_size / 2;
int gs[256];
int* histo = malloc(sizeof(int) * 256);
double* pmap = malloc(sizeof(double) * 256);
double cdf_min = 0;
memset(histo, 0, sizeof(int) * 256);
memset(pmap, 0, sizeof(double) * 256);
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
sum = 0;
for (w = 0; w < win_size; w++) {
for (h = 0; h < win_size; h++) {
if (i + h - mid >= 0 && i + h - mid < height && j + w - mid >= 0 && j + w - mid < width) {
sum += *(src + (i + h - mid) * width + j + w - mid);
}
}
}
*(dst + i * width + j) = (BYTE)(sum / (win_size * win_size));
histo[*(dst + i * width + j)] += 1;
}
}
for (i = 0; i < 256; i++) {
pmap[i] = (double)histo[i] / (width * height);
if (pmap[i] != 0) cdf_min = pmap[i];
}
for (i = 1; i < 256; i++) pmap[i] += pmap[i - 1];
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
t = *(dst + i * width + j);
if (t > 0) {
gs[t] = (int)(255 * (pmap[t] - cdf_min) / (1 - cdf_min) + 0.5);
*(dst + i * width + j) = (BYTE)gs[t];
}
}
}
free(histo);
free(pmap);
}
int main() {
BYTE img[256][256];
BYTE dst[256][256];
int i, j;
int width = 256, height = 256, win_size = 11;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
img[i][j] = (BYTE)(i * j / 256);
}
}
local_histogram_eq((BYTE*)img, (BYTE*)dst, width, height, win_size);
return 0;
}
阅读全文