Skip to content

Basic OpenCV Programming – Negative of an Image

September 5, 2010

For starting with image processing using OpenCV, I would suggest to start working on problems and try to write the code for its solution. This can give you real experience in coding and learning syntax can be done as and when its required.

Lets see the code to obtain the negative of an image.


int main(int argc, char **argv)
//reading the input image
const char* imagename = argc &gt; 1 ? argv[1] : "lena.jpg";
IplImage* img = 0;
int h, w, step, channels, i, j, k;
uchar *data;
img = cvLoadImage(imagename, CV_LOAD_IMAGE_UNCHANGED);
printf("Could not load image file: %s\n", imagename);
//obtaining the image parameters
h = img-&gt;height;
w = img-&gt;width;
step = img-&gt;widthStep;
channels = img-&gt;nChannels;
data = (uchar *)img-&gt;imageData;
//transforming to negative
for(i=0; i&lt;h; i++)
for(j=0; j&lt;w; j++)
for(k=0; k&lt;channels; k++)
data[i*step+j*channels+k] = 255 - data[i*step+j*channels+k];
//displaying the negative
cvNamedWindow("OpenCV", CV_WINDOW_AUTOSIZE);
cvShowImage("OpenCV", img);
return 0;

In this code we have read an image and converted it to its negative. The details of the functions used are given below:

cvLoadImage() Loads the required image.

cvNamedWindow() Creates a window with the name and window size as specified.

cvShowImage() Outputs the image to the window created earlier.

cvWaitKey() Waits till the user interrupts.

For more detailed understanding of these functions, I would recommend to read the OpenCV documentation.


From → OpenCV

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: