Article:
Histogram Equalization
2343
dangtrieu.myopenid.com 5Over 4 years ago |
Dùng thử thư viện xử lý ảnh OpenCV bằng cách viết chương trình về Histogram Equalization
Phương pháp này tính histogram của cả bức ảnh rồi mới cân bằng nên những nơi tối quá, hoặc sáng quá (cục bộ) sẽ không có tác dụng.
Phương pháp
Local Histogram Equalization, xử lý từng block của bức ảnh sẽ cho ảnh
rõ nét cả những nơi tranh tối, tranh sáng. Chỉ cần có 1 chút sáng thì
khuếch đại lên sẽ thấy hết
. Cái này để hôm khác.

Hình trước khi xử lý

Sau khi xử lý

#include "stdafx.h"
#include
#include
#include
#include
#include
#define FILE_NAME "../sampleImage/m.jpg"
#define OUT_FILE_NAME1 "mGray.jpg"
#define OUT_FILE_NAME2 "mEqual.jpg"
#define GRAY_LEVEL 255
int main(int argc, char* argv[])
{
int i, j;
int hist[GRAY_LEVEL], sumOfHist[GRAY_LEVEL];
// Load color image
IplImage* cimg;
cimg = cvLoadImage(FILE_NAME);
if (!cimg) {
printf("Cannot open %s
", FILE_NAME);
return -1;
}
// Create gray image
CvSize size;
size.height = cimg->height;
size.width = cimg->width;
IplImage* gimg = cvCreateImage(size, IPL_DEPTH_8U, 1);
cvCvtColor(cimg, gimg, CV_BGR2GRAY); //cimg -> gimg
int width = gimg->width;
int height = gimg->height;
int step = gimg->widthStep/sizeof(uchar);
uchar* gdata = (uchar *)gimg->imageData;
// Create result image
IplImage* gimgRes = cvCreateImage(size, IPL_DEPTH_8U, 1);
uchar* gdataRes = (uchar *)gimgRes->imageData;
// Initial array
for(i = 0; i< GRAY_LEVEL; i++){
hist[i] = 0;
sumOfHist[i] = 0;
}
// Calculate histogram
int k = 0;
for (i = 0; i < width; j++) {
k = gdata[i*step + j];
hist[k] = hist[k] + 1;
}
}
// Calculate the sum of histogram
int sum=0;
for(i = 0; i<= GRAY_LEVEL; i++){
sum = sum + hist[i];
sumOfHist[i] = sum;
}
// Transform input image to output image
int area = width*height;
for (i = 0; i < width; j++) {
k = gdata[i*step + j];
gdataRes[i*step + j] = (GRAY_LEVEL*1.0/area) * sumOfHist[k];
}
}
//Writing to file
if(!cvSaveImage(OUT_FILE_NAME1, gimg))
printf("Could not save: %s
", OUT_FILE_NAME1);
if(!cvSaveImage(OUT_FILE_NAME2, gimgRes))
printf("Could not save: %s
", OUT_FILE_NAME2);
// Render
cvNamedWindow("Image:", 1);
cvShowImage("Image:", cimg);
cvNamedWindow("Gray Image:", 1);
cvShowImage("Gray Image:", gimg);
cvNamedWindow("Equalization image:", 1);
cvShowImage("Equalization image:", gimgRes);
// Loop and wait
cvWaitKey();
// Release
cvDestroyWindow("Image:");
cvReleaseImage(&cimg);
cvDestroyWindow("Gray Image:");
cvReleaseImage(&gimg);
cvDestroyWindow("Equalization image:");
cvReleaseImage(&gimgRes);
return 0;
}
Giải thuật căn bản về xử lí ảnh
5