Contrast Stretching using C++ and OpenCV: Image Processing

Theory

Contrast Stretching is one of the piecewise linear function. Contrast Stretching increases the dynamic range of the grey level in the image being processed.

Points (r1, s1) and (r2, s2) control the shape of the transformation. The selection of control points depends upon the types of image and varies from one image to another image. If r1 = s1 and r2 = s2 then the transformation is linear and this doesn’t affect the image. In other case we can calculate the intensity of output pixel, provided intensity of input pixel is x, as follows

for 0   output = s1 / r1 * x
for r1   output = ((s2 – s1)/(r2 – r1))*(x – r1) + s1
for r2   output = ((L-1 – s2)/(L-1 – r2))*(x – r2) + s2

Source Code

#include 
#include 
#include 

using namespace cv;
using namespace std;

int computeOutput(int, int, int, int, int);

int main()
{
    Mat image = imread("pic.jpg");
    Mat new_image = image.clone();

    int r1, s1, r2, s2;
    cout>r1;
    cout>s1;
    cout>r2;
    cout>s2;

    for(int y = 0; y (y,x)[c], r1, s1, r2, s2);
                new_image.at(y,x)[c] = saturate_cast(output);
            }
        }
    }

    namedWindow("Original Image", 1);
    imshow("Original Image", image);

    namedWindow("New Image", 1);
    imshow("New Image", new_image);

    waitKey();

    return 0;
}

int computeOutput(int x, int r1, int s1, int r2, int s2)
{
    float result;
    if(0 
 

Output
r1 = 70 s1 = 0 r2 = 140 s2 = 255