# Producing negative of a grayscale image: C++ and OpenCV

Theory
The concept behind negative of grayscale image is very simple. Just subtract each intensity level of an image from 255. The negative transformation is given by the function
s = L – 1 – r
Where s is the pixel after transformation, r is the pixel before transformation and L is the maximum intensity level (in our case it is 256).

Program
The program is written in C++ using OpenCV library in QT IDE. If you are using QT IDE then add the following line of code in .pro file.

INCLUDEPATH += /usr/include/opencv/
PKGCONFIG += opencv
LIBS += -Icv -Ihighhui

#include <opencv/cv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;

int main()
{
//read the image in matrix image

// initialize the output matrix with zeros
Mat new_image = Mat::zeros( image.size(), image.type() );

// create a matrix with all elements equal to 255 for subtraction
Mat sub_mat = Mat::ones(image.size(), image.type())*255;

//subtract the original matrix by sub_mat to give the negative output new_image
subtract(sub_mat, image, new_image);

// 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;
}

Output

SHARE Producing negative of a grayscale image: C++ and OpenCV

### 5 Responses

1. Anonymous says:

Thanks but why the sub_mat is blue and not white ?

2. Anonymous says:

great question !

3. mc says:

Because Mat::ones function works only for one channel. Your sub_mat matrix is like that {255,0,0;255,0,0;…} The only first channel is ones.