自适应直方图均衡化c++
时间: 2023-11-18 17:50:16 浏览: 96
以下是自适应直方图均衡化的C代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_PIXELS 1000000
void adaptive_histogram_equalization(unsigned char *image, int rows, int cols, int window_size) {
int i, j, k, n, m, index, sum, threshold;
int offset = window_size / 2;
int *histogram = (int*)calloc(256, sizeof(int));
int *histogram_sum = (int*)calloc(256, sizeof(int));
unsigned char *result = (unsigned char*)calloc(rows * cols, sizeof(unsigned char));
if (histogram == NULL || histogram_sum == NULL || result == NULL) {
printf("Memory allocation failed.\n");
return;
}
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
for (k = 0; k < 256; k++) {
histogram[k] = 0;
}
for (n = -offset; n <= offset; n++) {
for (m = -offset; m <= offset; m++) {
if (i + n < 0 || i + n >= rows || j + m < 0 || j + m >= cols) {
continue;
}
index = (i + n) * cols + (j + m);
histogram[image[index]]++;
}
}
histogram_sum[0] = histogram[0];
for (k = 1; k < 256; k++) {
histogram_sum[k] = histogram_sum[k - 1] + histogram[k];
}
sum = histogram_sum[255];
threshold = (int)floor(sum / 2.0);
for (k = 0; k < 256; k++) {
if (histogram_sum[k] >= threshold) {
break;
}
}
for (k = 0; k < 256; k++) {
histogram[k] = (int)floor((double)histogram[k] * k / sum);
}
result[i * cols + j] = histogram[image[i * cols + j]];
}
}
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
image[i * cols + j] = result[i * cols + j];
}
}
free(histogram);
free(histogram_sum);
free(result);
}
int main(int argc, char *argv[]) {
FILE *fp;
unsigned char *image;
int rows, cols, i, j;
if (argc != 4) {
printf("Usage: %s input_image output_image window_size\n", argv[0]);
return 1;
}
fp = fopen(argv[1], "rb");
if (fp == NULL) {
printf("Failed to open input image.\n");
return 1;
}
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (size > MAX_PIXELS) {
printf("Image size exceeds maximum limit.\n");
fclose(fp);
return 1;
}
image = (unsigned char*)calloc(size, sizeof(unsigned char));
if (image == NULL) {
printf("Memory allocation failed.\n");
fclose(fp);
return 1;
}
if (fread(image, sizeof(unsigned char), size, fp) != size) {
printf("Failed to read input image.\n");
fclose(fp);
free(image);
return 1;
}
fclose(fp);
rows = sqrt(size);
cols = rows;
adaptive_histogram_equalization(image, rows, cols, atoi(argv[3]));
fp = fopen(argv[2], "wb");
if (fp == NULL) {
printf("Failed to open output image.\n");
free(image);
return 1;
}
fwrite(image, sizeof(unsigned char), size, fp);
fclose(fp);
free(image);
return 0;
}
```
阅读全文