图像灰度值调整(C/C++源代码)

类别:编程语言 点击:0 评论:0 推荐:

图像的象素值变换,包括亮度、对比度和GAMMA校正算法,环境是OPENCV4.0,VC6.0。算法参考了MATLAB函数 imadjust 。

//
// perform histgram equalization for single channel image
//

#include "cv.h"
#include "highgui.h"

/*
Reference for correspondent MATLAB function: imadjust
IMADJUST Adjust image intensity values or colormap.
    J = IMADJUST(I,[LOW_IN HIGH_IN],[LOW_OUT HIGH_OUT],GAMMA) maps the
    values in intensity image I to new values in J such that values between
    LOW_IN and HIGH_IN map to values between LOW_OUT and HIGH_OUT. Values
    below LOW_IN and above HIGH_IN are clipped; that is, values below LOW_IN
    map to LOW_OUT, and those above HIGH_IN map to HIGH_OUT. You can use an
    empty matrix ([]) for [LOW_IN HIGH_IN] or for [LOW_OUT HIGH_OUT] to
    specify the default of [0 1]. GAMMA specifies the shape of the curve
    describing the relationship between the values in I and J. If GAMMA is
    less than 1, the mapping is weighted toward higher (brighter) output
    values. If GAMMA is greater than 1, the mapping is weighted toward lower
    (darker) output values. If you omit the argument, GAMMA defaults to 1
    (linear mapping).

    Note that if HIGH_OUT < LOW_OUT, the output image is reversed, as in a
    photographic negative.
====
  src and dst are grayscale, 8-bit images;
  Default input value:
           [low, high] = [0,1];
           [bottom, top] = [0,1];
           gamma = 1;
  if adjust successfully, return 0, otherwise, return non-zero.
  Author: R.Z.Liu, 18/09/04
====
*/
int ImageAdjust(IplImage* src, IplImage* dst,
                double low, double high,   // low and high are the intensities of src
                double bottom, double top, // mapped to bottom and top of dst
                double gamma )
{
    double low2 = low*255;
    double high2 = high*255;
    double bottom2 = bottom*255;
    double top2 = top*255;
    double err_in = high2 - low2;
    double err_out = top2 - bottom2;

    int x,y;
    double val;

    if( low<0 && low>1 && high <0 && high>1 && bottom<0 && bottom>1 && top<0 && top>1)
        return 1;
   
    // intensity transform
    for( y = 0; y < src->height; y++)
    {
        for (x = 0; x < src->width; x++)
        {
            val = ((uchar*)(src->imageData + src->widthStep*y))[x];
            val = pow((val - low2)/err_in, gamma) * err_out + bottom2;
            if(val>255) val=255; if(val<0) val=0; // Make sure src is in the range [low,high]
            ((uchar*)(dst->imageData + dst->widthStep*y))[x] = (uchar) val;
        }
    }
    return 0;
}

本文地址:http://com.8s8s.com/it/it27163.htm