Skip to content

Tag: cvadd

OpenCV: adding two images

This is a very simple example of how to open two images and display them added.

I got two pictures at project Commons from Wikimedia that were highlighted on Featured Pictures. I did a crop on both to have the same size, as I’m trying to make this example as simple as possible.

The first one is a photo of our Milky Way, taken at Paranal Observatory by Stéphane Guisard.

milkyway

The second one is a California surfer inside wave, taken by Mila Zinkova.

surfer

In this simple OpenCV code below, we open the images, create a new one to display the result and use cvAdd to add them. We do not save the result or handle more than the ordinary case of two images with the same size.

#include 
#include 
#include 

int main( int argc, char **argv ){
    IplImage *surfer, *milkyway, *result;
    int key = 0;
    CvSize size;

    /* load images, check, get size (both should have the same) */
    surfer = cvLoadImage("surfer.jpg", CV_LOAD_IMAGE_COLOR);
    milkyway = cvLoadImage("milkyway.jpg", CV_LOAD_IMAGE_COLOR);
    if((!surfer)||(!milkyway)){
        printf("Could not open one or more images.");
        exit -1;
    }
    size = cvGetSize(surfer);

    /* create a empty image, same size, depth and channels of others */
    result = cvCreateImage(size, surfer->depth, surfer->nChannels);
    cvZero(result);

    /* result = surfer + milkyway (NULL mask)*/
    cvAdd(surfer, milkyway, result, NULL);
 
    /* create a window, display the result, wait for a key */
    cvNamedWindow("example", CV_WINDOW_AUTOSIZE);
    cvShowImage("example", result);
    cvWaitKey(0);

    /* free memory and get out */
    cvDestroyWindow("example");
    cvReleaseImage(&surfer);
    cvReleaseImage(&milkyway);
    cvReleaseImage(&result);
    return 0;
}

/* gcc add.c -o add `pkg-config opencv --libs --cflags` */

Compile it (on a well configured OpenCV development environment) and run it:

gcc add.c -o add `pkg-config opencv –libs –cflags`
./add

The result got pretty cool, a milky way surfer.

surfer in the milk way