直方图均衡

直方图均衡

直方图均衡可均衡大部分像素集中在某一区间的图像,经过处理后可使图像利用大部分灰度值。

openCV直方图均衡化代码:

void histogramBalanced(){
    IplImage* im = cvLoadImage("/Users/qixiangzhang/Desktop/openCV/gyy.jpg",CV_LOAD_IMAGE_UNCHANGED);
    IplImage* imOut = cvCreateImage(cvGetSize(im), IPL_DEPTH_8U, 1);

    cvShowImage("Original", im);

    cvEqualizeHist(im, imOut);

    cvShowImage("histogram", imOut);

    cvSaveImage("/Users/qixiangzhang/Desktop/histogram.jpg",imOut);
}

使用matlab查看直方图统计结果:

>> gyy = imread('gyy.jpg');
>> gyyH = imread('gyyH.jpg');
>> hist_gyy = imhist(gyy);
>> bar(hist_gyy);
>> hist_gyyH = imhist(gyyH);
>> figure();bar(hist_gyyH)

直方图均衡_第1张图片
不使用opencv的API计算直方图均衡代码:

//以下代码为求思路清晰,在性能上不做优化
void myEqualizeHist(){
    auto im = imread("/Users/qixiangzhang/Desktop/openCV/gyy.jpg");

    long int sta[256] = {0};
    int nl = im.rows;
    int nc = im.cols*im.channels();
    uchar* data;
   //统计 
    for(int j = 0; j<nl; j++){
        data = im.ptr<uchar>(j);
        for(int i = 0; i<nc; i++){
            sta[data[i]%256]++;
        }
    }
    //概率
    double pro[256] = {0};
    for(int j = 0; j<256; j++){
        pro[j] = sta[j]/double(nl*nc);
    }
    //计算结果
    pro[0]*=255;
    for(int j = 1; j<256; j++){
        pro[j] = pro[j]*255+pro[j-1];
    }
    int res[256] = {0};
    for(int j = 0; j<256; j++){
        res[j] = pro[j];
        if(pro[j]-int(pro[j])>=0.5) res[j]++;
    }
    //替换
    for(int j = 0; j<nl; j++){
        data = im.ptr<uchar>(j);
        for(int i = 0; i<nc; i++){
            data[i] = res[data[i]%256];
        }
    }

    imshow("a", im);
    IplImage i = IplImage(im);
    cvSaveImage("/Users/qixiangzhang/Desktop/histogram2.jpg", &i);
}

结果与使用API的结果一致:

你可能感兴趣的:(直方图均衡)