OpenCV
Open Source Computer Vision
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
Adding borders to your images

Prev Tutorial: Making your own linear filters!
Next Tutorial: Sobel Derivatives

Original author Ana Huamán
Compatibility OpenCV >= 3.0

Goal

In this tutorial you will learn how to:

  • Use the OpenCV function copyMakeBorder() to set the borders (extra padding to your image).

Theory

Note
The explanation below belongs to the book Learning OpenCV by Bradski and Kaehler.
  1. In our previous tutorial we learned to use convolution to operate on images. One problem that naturally arises is how to handle the boundaries. How can we convolve them if the evaluated points are at the edge of the image?
  2. What most of OpenCV functions do is to copy a given image onto another slightly larger image and then automatically pads the boundary (by any of the methods explained in the sample code just below). This way, the convolution can be performed over the needed pixels without problems (the extra padding is cut after the operation is done).
  3. In this tutorial, we will briefly explore two ways of defining the extra padding (border) for an image:

    1. BORDER_CONSTANT: Pad the image with a constant value (i.e. black or 0
    2. BORDER_REPLICATE: The row or column at the very edge of the original is replicated to the extra border.

    This will be seen more clearly in the Code section.

  • What does this program do?
    • Load an image
    • Let the user choose what kind of padding use in the input image. There are two options:

      1. Constant value border: Applies a padding of a constant value for the whole border. This value will be updated randomly each 0.5 seconds.
      2. Replicated border: The border will be replicated from the pixel values at the edges of the original image.

      The user chooses either option by pressing 'c' (constant) or 'r' (replicate)

    • The program finishes when the user presses 'ESC'

Code

The tutorial code's is shown lines below.

You can also download it from here

using namespace cv;
// Declare the variables
Mat src, dst;
int top, bottom, left, right;
int borderType = BORDER_CONSTANT;
const char* window_name = "copyMakeBorder Demo";
RNG rng(12345);
int main( int argc, char** argv )
{
const char* imageName = argc >=2 ? argv[1] : "lena.jpg";
// Loads an image
src = imread( samples::findFile( imageName ), IMREAD_COLOR ); // Load an image
// Check if image is loaded fine
if( src.empty()) {
printf(" Error opening image\n");
printf(" Program Arguments: [image_name -- default lena.jpg] \n");
return -1;
}
// Brief how-to for this program
printf( "\n \t copyMakeBorder Demo: \n" );
printf( "\t -------------------- \n" );
printf( " ** Press 'c' to set the border to a random constant value \n");
printf( " ** Press 'r' to set the border to be replicated \n");
printf( " ** Press 'ESC' to exit the program \n");
namedWindow( window_name, WINDOW_AUTOSIZE );
// Initialize arguments for the filter
top = (int) (0.05*src.rows); bottom = top;
left = (int) (0.05*src.cols); right = left;
for(;;)
{
Scalar value( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255) );
copyMakeBorder( src, dst, top, bottom, left, right, borderType, value );
imshow( window_name, dst );
char c = (char)waitKey(500);
if( c == 27 )
{ break; }
else if( c == 'c' )
{ borderType = BORDER_CONSTANT; }
else if( c == 'r' )
{ borderType = BORDER_REPLICATE; }
}
return 0;
}
n-dimensional dense array class
Definition mat.hpp:829
int cols
Definition mat.hpp:2155
bool empty() const
Returns true if the array has no elements.
int rows
the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
Definition mat.hpp:2155
Random Number Generator.
Definition core.hpp:2874
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3
Definition core.hpp:107

Explanation

Declare the variables

First we declare the variables we are going to use:

// Declare the variables
Mat src, dst;
int top, bottom, left, right;
int borderType = BORDER_CONSTANT;
const char* window_name = "copyMakeBorder Demo";
RNG rng(12345);

Especial attention deserves the variable rng which is a random number generator. We use it to generate the random border color, as we will see soon.

Load an image

As usual we load our source image src:

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

Create a window

After giving a short intro of how to use the program, we create a window:

namedWindow( window_name, WINDOW_AUTOSIZE );

Initialize arguments

Now we initialize the argument that defines the size of the borders (top, bottom, left and right). We give them a value of 5% the size of src.

// Initialize arguments for the filter
top = (int) (0.05*src.rows); bottom = top;
left = (int) (0.05*src.cols); right = left;

Loop

The program runs in an infinite loop while the key ESC isn't pressed. If the user presses 'c' or 'r', the borderType variable takes the value of BORDER_CONSTANT or BORDER_REPLICATE respectively:

char c = (char)waitKey(500);
if( c == 27 )
{ break; }
else if( c == 'c' )
{ borderType = BORDER_CONSTANT; }
else if( c == 'r' )
{ borderType = BORDER_REPLICATE; }

Random color

In each iteration (after 0.5 seconds), the random border color (value) is updated...

Scalar value( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255) );

This value is a set of three numbers picked randomly in the range [0,255].

Form a border around the image

Finally, we call the function copyMakeBorder() to apply the respective padding:

copyMakeBorder( src, dst, top, bottom, left, right, borderType, value );
  • The arguments are:
    1. src: Source image
    2. dst: Destination image
    3. top, bottom, left, right: Length in pixels of the borders at each side of the image. We define them as being 5% of the original size of the image.
    4. borderType: Define what type of border is applied. It can be constant or replicate for this example.
    5. value: If borderType is BORDER_CONSTANT, this is the value used to fill the border pixels.

Display the results

We display our output image in the image created previously

imshow( window_name, dst );

Results

  1. After compiling the code above, you can execute it giving as argument the path of an image. The result should be:

    • By default, it begins with the border set to BORDER_CONSTANT. Hence, a succession of random colored borders will be shown.
    • If you press 'r', the border will become a replica of the edge pixels.
    • If you press 'c', the random colored borders will appear again
    • If you press 'ESC' the program will exit.

    Below some screenshot showing how the border changes color and how the BORDER_REPLICATE option looks: