'Adjust image's contrast

I am try to apply contrast to an image but I can not find a good formula to do it. I have tried many different sites formulas, and none have worked. Anyone have any suggestions?

Here is my latest attempt:

int r = Colors.red(pixel);
int g = Colors.green(pixel);
int b = Colors.blue(pixel);

float red = r / 255.0f;
float green = g / 255.0f;
float blue = b / 255.0f;

red = (((red - 0.5f) * amount) + 0.5f) * 255.0f;
green = (((green - 0.5f) * amount) + 0.5f) * 255.0f;
blue = (((blue - 0.5f) * amount) + 0.5f) * 255.0f;

int iR = (int)red;
iR = iR > 255 ? 255 : iR;
iR = iR < 0 ? 0 : iR;
int iG = (int)green;
iG = iG > 255 ? 255 : iG;
iG = iG < 0 ? 0 : iG;
int iB = (int)blue;
iB = iB > 255 ? 255 : iB;
iB = iB < 0 ? 0 : iB;

That didn't work. Anyone have any other suggestions?



Solution 1:[1]

I developed a formula that contrasts an image based on average image intensity. It's made in such a way that if intensity pixel is below the average intensity, it will get even darker; but it it's higher than average intensity, it will get even brighter.

C(x,y)=I(x,y)^{{(1+\overline{I}-I(x,y))}^{\alpha}}

\overline{I} = \frac{1}{NM}\sum_{x=0}^{N-1}\sum_{y=0}^{M-1}{I(x,y)}

I(x,y) must be normalized to be between 0 and 1. Contrast level is defined by alpha factor. Set it to 0 and you get zero contrast.

Here's some OpenCV code:

cv::Mat setImageContrast(cv::Mat image, double alpha)
{
    cv::Mat output = cv::Mat::zeros(image.rows, image.cols, CV_8UC1);
    double I_mean = 0.0;
    int N = image.cols * image.rows;

    for(int x = 0; x < image.cols; x++) {
        for(int y = 0; y < image.rows; y++) {
            I_mean += (double)image.at<unsigned char>(y,x)/255.0;
        }
    }
    I_mean /= (double)N;

    for(int x = 0; x < image.cols; x++) {
        for(int y = 0; y < image.rows; y++) {
            double I = (double)image.at<unsigned char>(y,x)/255.0;
            I = pow(I, pow(1.0 + I_mean - I, alpha)) * 255.0;
            output.at<unsigned char>(y,x) = (int)I;
        }
    }
    return output;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bko