Loading web-font TeX/Main/Regular
OpenCV  
Open Source Computer Vision
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
Image Pyramids

Prev Tutorial: Extract horizontal and vertical lines by using morphological operations

Next Tutorial: Basic Thresholding Operations

Original author Ana Huamán
Compatibility OpenCV >= 3.0

Goal

In this tutorial you will learn how to:

Theory

Note
The explanation below belongs to the book Learning OpenCV by Bradski and Kaehler.

Image Pyramid

Gaussian Pyramid

Note
When we reduce the size of an image, we are actually losing information of the image.

Code

This tutorial code's is shown lines below.

You can also download it from here

#include "iostream"
using namespace std;
using namespace cv;
const char* window_name = "Pyramids Demo";
int main( int argc, char** argv )
{
cout << "\n Zoom In-Out demo \n "
"------------------ \n"
" * [i] -> Zoom in \n"
" * [o] -> Zoom out \n"
" * [ESC] -> Close program \n" << endl;
const char* filename = argc >=2 ? argv[1] : "chicky_512.png";
// Loads an image
Mat src = imread( samples::findFile( filename ) );
// Check if image is loaded fine
if(src.empty()){
printf(" Error opening image\n");
printf(" Program Arguments: [image_name -- default chicky_512.png] \n");
return EXIT_FAILURE;
}
for(;;)
{
imshow( window_name, src );
char c = (char)waitKey(0);
if( c == 27 )
{ break; }
else if( c == 'i' )
{ pyrUp( src, src, Size( src.cols*2, src.rows*2 ) );
printf( "** Zoom In: Image x 2 \n" );
}
else if( c == 'o' )
{ pyrDown( src, src, Size( src.cols/2, src.rows/2 ) );
printf( "** Zoom Out: Image / 2 \n" );
}
}
return EXIT_SUCCESS;
}

Explanation

Let's check the general structure of the program:

Load an image

const char* filename = argc >=2 ? argv[1] : "chicky_512.png";
// Loads an image
Mat src = imread( samples::findFile( filename ) );
// Check if image is loaded fine
if(src.empty()){
printf(" Error opening image\n");
printf(" Program Arguments: [image_name -- default chicky_512.png] \n");
return EXIT_FAILURE;
}

Create window

imshow( window_name, src );

Loop

for(;;)
{
imshow( window_name, src );
char c = (char)waitKey(0);
if( c == 27 )
{ break; }
else if( c == 'i' )
{ pyrUp( src, src, Size( src.cols*2, src.rows*2 ) );
printf( "** Zoom In: Image x 2 \n" );
}
else if( c == 'o' )
{ pyrDown( src, src, Size( src.cols/2, src.rows/2 ) );
printf( "** Zoom Out: Image / 2 \n" );
}
}

Perform an infinite loop waiting for user input. Our program exits if the user presses ESC. Besides, it has two options:

else if( c == 'i' )
{ pyrUp( src, src, Size( src.cols*2, src.rows*2 ) );
printf( "** Zoom In: Image x 2 \n" );
}
else if( c == 'o' )
{ pyrDown( src, src, Size( src.cols/2, src.rows/2 ) );
printf( "** Zoom Out: Image / 2 \n" );
}

Notice that it is important that the input image can be divided by a factor of two (in both dimensions). Otherwise, an error will be shown.

Results