# Changing the contrast and brightness of an image!¶

## Goal¶

In this tutorial you will learn how to:

• Access pixel values
• Initialize a matrix with zeros
• Learn what saturate_cast does and why it is useful
• Get some cool info about pixel transformations

## Theory¶

Note

The explanation below belongs to the book Computer Vision: Algorithms and Applications by Richard Szeliski

### Image Processing¶

• A general image processing operator is a function that takes one or more input images and produces an output image.
• Image transforms can be seen as:
• Point operators (pixel transforms)
• Neighborhood (area-based) operators

#### Pixel Transforms¶

• In this kind of image processing transform, each output pixel’s value depends on only the corresponding input pixel value (plus, potentially, some globally collected information or parameters).
• Examples of such operators include brightness and contrast adjustments as well as color correction and transformations.
• Two commonly used point processes are multiplication and addition with a constant: • The parameters and are often called the gain and bias parameters; sometimes these parameters are said to control contrast and brightness respectively.

• You can think of as the source image pixels and as the output image pixels. Then, more conveniently we can write the expression as: where and indicates that the pixel is located in the i-th row and j-th column.

## Code¶

• The following code performs the operation :
#include <cv.h>
#include <highgui.h>
#include <iostream>

using namespace cv;

double alpha; /**< Simple contrast control */
int beta;  /**< Simple brightness control */

int main( int argc, char** argv )
{
/// Read image given by user
Mat image = imread( argv );
Mat new_image = Mat::zeros( image.size(), image.type() );

/// Initialize values
std::cout<<" Basic Linear Transforms "<<std::endl;
std::cout<<"-------------------------"<<std::endl;
std::cout<<"* Enter the alpha value [1.0-3.0]: ";std::cin>>alpha;
std::cout<<"* Enter the beta value [0-100]: "; std::cin>>beta;

/// Do the operation new_image(i,j) = alpha*image(i,j) + beta
for( int y = 0; y < image.rows; y++ )
{ for( int x = 0; x < image.cols; x++ )
{ for( int c = 0; c < 3; c++ )
{
new_image.at<Vec3b>(y,x)[c] =
saturate_cast<uchar>( alpha*( image.at<Vec3b>(y,x)[c] ) + beta );
}
}
}

/// Create Windows
namedWindow("Original Image", 1);
namedWindow("New Image", 1);

/// Show stuff
imshow("Original Image", image);
imshow("New Image", new_image);

/// Wait until user press some key
waitKey();
return 0;
}


## Explanation¶

1. We begin by creating parameters to save and to be entered by the user:

double alpha;
int beta;

2. We load an image using imread and save it in a Mat object:

Mat image = imread( argv );

3. Now, since we will make some transformations to this image, we need a new Mat object to store it. Also, we want this to have the following features:

• Initial pixel values equal to zero
• Same size and type as the original image
Mat new_image = Mat::zeros( image.size(), image.type() );


We observe that Mat::zeros returns a Matlab-style zero initializer based on image.size() and image.type()

4. Now, to perform the operation we will access to each pixel in image. Since we are operating with RGB images, we will have three values per pixel (R, G and B), so we will also access them separately. Here is the piece of code:

for( int y = 0; y < image.rows; y++ )
{ for( int x = 0; x < image.cols; x++ )
{ for( int c = 0; c < 3; c++ )
{ new_image.at<Vec3b>(y,x)[c] =
saturate_cast<uchar>( alpha*( image.at<Vec3b>(y,x)[c] ) + beta ); }
}
}


Notice the following:

• To access each pixel in the images we are using this syntax: image.at<Vec3b>(y,x)[c] where y is the row, x is the column and c is R, G or B (0, 1 or 2).
• Since the operation can give values out of range or not integers (if is float), we use saturate_cast to make sure the values are valid.
5. Finally, we create windows and show the images, the usual way.

namedWindow("Original Image", 1);
namedWindow("New Image", 1);

imshow("Original Image", image);
imshow("New Image", new_image);

waitKey(0);


Note

Instead of using the for loops to access each pixel, we could have simply used this command:

image.convertTo(new_image, -1, alpha, beta);


where convertTo would effectively perform new_image = a*image + beta. However, we wanted to show you how to access each pixel. In any case, both methods give the same result.

## Result¶

• Running our code and using and \$ ./BasicLinearTransforms lena.jpg
Basic Linear Transforms
-------------------------
* Enter the alpha value [1.0-3.0]: 2.2
* Enter the beta value [0-100]: 50

• We get this:
{"ft_lang_label":"__label__en","ft_lang_prob":0.7129045,"math_prob":0.97066474,"size":3348,"snap":"2022-27-2022-33","text_gpt3_token_len":878,"char_repetition_ratio":0.12679426,"word_repetition_ratio":0.19475655,"special_character_ratio":0.31182796,"punctuation_ratio":0.20977011,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9938314,"pos_list":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],"im_url_duplicate_count":[null,2,null,2,null,8,null,2,null,4,null,2,null,null,null,6,null,4,null,9,null,8,null,4,null,2,null,9,null,2,null,2,null,2,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-08-11T18:05:22Z\",\"WARC-Record-ID\":\"<urn:uuid:40ccf1c7-d89b-4d20-a508-24da9bec805f>\",\"Content-Length\":\"27793\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:dadbc323-7dc2-49c3-b398-dd61e74a8276>\",\"WARC-Concurrent-To\":\"<urn:uuid:9d6e12c9-3005-47c1-9756-70a8b1e558c2>\",\"WARC-IP-Address\":\"104.21.24.86\",\"WARC-Target-URI\":\"https://docs.opencv.org/2.4.0/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html\",\"WARC-Payload-Digest\":\"sha1:K6KR7BRIPOEDZPZEAJKSTE64OOPYZPWP\",\"WARC-Block-Digest\":\"sha1:XYIOK6JMVIYTVEJJ7PKJYNFXOIRY33SA\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-33/CC-MAIN-2022-33_segments_1659882571483.70_warc_CC-MAIN-20220811164257-20220811194257-00763.warc.gz\"}"}