OpenCV C++ Tutorial: Load and Process Images with IplImage

Classified in Computers

Written on in English with a size of 2.91 KB

OpenCV C Source Code for Image Processing

Below is a complete C program utilizing the OpenCV library to load, display, and process two images using IplImage.

Required Libraries

#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>

Main Function and Validation

int main(int argc, char **argv) 
{
    if (argc != 3) // e.g., fruits, birds
    {
        printf("Error: Usage %s image_file_name\n", argv[0]);
        return EXIT_FAILURE;
    }
    // CV_LOAD_IMAGE_COLOR = 1 forces the resultant IplImage to be colour.
    // CV_LOAD_IMAGE_GRAYSCALE = 0 forces a greyscale IplImage.
    // CV_LOAD_IMAGE_UNCHANGED = -1

    // IMG1
    IplImage* Img = cvLoadImage(argv[1], CV_LOAD_IMAGE_UNCHANGED);
    
    // IMG2
    IplImage* Img2 = cvLoadImage(argv[2], CV_LOAD_IMAGE_UNCHANGED);
    
    // Always check if the program can find the image file
    if (!Img) 
    {
        printf("Error: file %s not found\n", argv[1]);
        return EXIT_FAILURE;
    }

Image Visualization

    // IMG1
    // A visualization window is created with title: image file name
    cvNamedWindow(argv[1], CV_WINDOW_AUTOSIZE);
    // Img is shown in 'image' window
    cvShowImage(argv[1], Img);
    cvWaitKey(0);  

    // IMG2
    // A visualization window is created with title: image file name
    cvNamedWindow(argv[2], CV_WINDOW_AUTOSIZE);
    // Img is shown in 'image' window
    cvShowImage(argv[2], Img2);
    cvWaitKey(0);
    
    // IplImage* ImgBarrido = cvCreateImage(cvSize(Img->width, Img->height), IPL_DEPTH_8U, 3);
    int fila, columna;

Pixel Processing Loop

    for (fila = 0; fila < Img->height; fila++) 
    {
        unsigned char *pImg = (unsigned char *) Img->imageData + fila * Img->widthStep;
        unsigned char *pImgFinal = (unsigned char *) Img2->imageData + fila * Img2->widthStep;

        for (columna = 0; columna < Img->width; columna++) 
        {
            // ColumnaIzquierda
            *pImg = *pImgFinal;
            pImg++;
            pImgFinal++;
            
            // ColumnaCentral
            *pImg = *pImgFinal;
            pImg++;
            pImgFinal++;
            
            // ColumnaDerecha
            *pImg = *pImgFinal;
            pImg++;
            pImgFinal++;
        }
        cvShowImage("Final", Img);
        
        // Transición
        // cvWaitKey(10);    
    } 
    
    // EsperaFin
    cvWaitKey(0);

Memory Cleanup and Exit

    /*
    // Memory release for images before exiting the application
    cvReleaseImage(&Img);
    cvReleaseImage(&Img2);
    cvReleaseImage(&ImgBarrido);

    // Self-explanatory
    cvDestroyWindow(argv[1]);
    cvDestroyWindow(argv[2]);
    cvDestroyWindow("Barrido");

    return EXIT_SUCCESS;
    */
}

Related entries: