这篇博客是关于试用CImg库来实现灰度图和彩色图的直方图均衡化操作。感觉效果还不错,除了彩色图在均衡化时会有一定的色彩失真。
C++代码实现:
//
// hEqualization.hpp
// 直方图均衡化
//
// Created by Alala on 2017/3/20.
// Copyright © 2017年 Alala. All rights reserved.
// #ifndef hEqualization_h
#define hEqualization_h
#include<CImg.h> using namespace cimg_library; class hEqualization {
private:
CImg<unsigned char> image;
int x;
int y;
float totalPixel; public:
hEqualization();
hEqualization(CImg<unsigned char> img);
void setImage(CImg<unsigned char> img);
CImg<unsigned char> toGray();
void grayProcess();
void RGBProcess();
}; hEqualization::hEqualization() {
x = ;
y = ;
totalPixel = ;
}
hEqualization::hEqualization(CImg<unsigned char> img) {
image = img;
x = image.width();
y = image.height();
totalPixel = x * y;
}
void hEqualization::setImage(CImg<unsigned char> img) {
image = img;
x = image.width();
y = image.height();
totalPixel = x * y;
} CImg<unsigned char> hEqualization::toGray() {
CImg<unsigned char> gray = image;
cimg_forXY(image, x, y) {
int r = image(x, y, );
int g = image(x, y, );
int b = image(x, y, );
double temp = (r * 0.2126 + g * 0.7152 + b * 0.0722);
gray(x, y, ) = temp;
gray(x, y, ) = temp;
gray(x, y, ) = temp;
}
return gray;
}
void hEqualization::grayProcess() {
CImg<unsigned char> gray = toGray();
gray.display("gray");
float pixels[];
float probability[];
float newP[];
memset(&pixels, , *sizeof(float));
cimg_forXY(image, x, y) {
pixels[int(image(x, y, ))]++;
}
for(int i = ; i < ; i++) {
probability[i] = pixels[i] / totalPixel;
if(i == ) {
newP[i] = probability[i];
} else {
newP[i] = probability[i] + newP[i-];
}
}
cimg_forXY(image, x, y) {
int temp = gray(x, y, );
temp = int(newP[temp] * + 0.5);
gray(x, y, ) = temp;
gray(x, y, ) = temp;
gray(x, y, ) = temp;
}
gray.display("test");
}
void hEqualization::RGBProcess() {
float pixelsR[];
float pixelsG[];
float pixelsB[];
memset(&pixelsR, , *sizeof(float));
memset(&pixelsG, , *sizeof(float));
memset(&pixelsB, , *sizeof(float)); float probabilityR[];
float probabilityG[];
float probabilityB[]; float newPR[];
float newPG[];
float newPB[];
cimg_forXY(image, x, y) {
pixelsR[int(image(x, y, ))]++;
pixelsG[int(image(x, y, ))]++;
pixelsB[int(image(x, y, ))]++;
}
for(int i = ; i < ; i++) {
probabilityR[i] = pixelsR[i] / totalPixel;
probabilityG[i] = pixelsG[i] / totalPixel;
probabilityB[i] = pixelsB[i] / totalPixel;
if(i == ) {
newPR[i] = probabilityR[i];
newPG[i] = probabilityG[i];
newPB[i] = probabilityB[i];
} else {
newPR[i] = probabilityR[i] + newPR[i-];
newPG[i] = probabilityG[i] + newPG[i-];
newPB[i] = probabilityB[i] + newPB[i-];
}
}
CImg<unsigned char> color = image;
cimg_forXY(image, x, y) {
int tempR = image(x, y, );
int tempG = image(x, y, );
int tempB = image(x, y, );
tempR = int(newPR[tempR] * + 0.5);
tempG = int(newPG[tempG] * + 0.5);
tempB = int(newPB[tempB] * + 0.5);
color(x, y, ) = tempR;
color(x, y, ) = tempG;
color(x, y, ) = tempB;
}
color.display("color");
} #endif /* hEqualization_h */