samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp#

An example using copyMakeBorder function. Check the corresponding tutorial for more details

 1/**
 2 * @file copyMakeBorder_demo.cpp
 3 * @brief Sample code that shows the functionality of copyMakeBorder
 4 * @author OpenCV team
 5 */
 6
 7#include "opencv2/imgproc.hpp"
 8#include "opencv2/imgcodecs.hpp"
 9#include "opencv2/highgui.hpp"
10
11using namespace cv;
12
13//![variables]
14// Declare the variables
15Mat src, dst;
16int top, bottom, left, right;
17int borderType = BORDER_CONSTANT;
18const char* window_name = "copyMakeBorder Demo";
19RNG rng(12345);
20//![variables]
21
22/**
23 * @function main
24 */
25int main( int argc, char** argv )
26{
27    //![load]
28    const char* imageName = argc >=2 ? argv[1] : "lena.jpg";
29
30    // Loads an image
31    src = imread( samples::findFile( imageName ), IMREAD_COLOR ); // Load an image
32
33    // Check if image is loaded fine
34    if( src.empty()) {
35        printf(" Error opening image\n");
36        printf(" Program Arguments: [image_name -- default lena.jpg] \n");
37        return -1;
38    }
39    //![load]
40
41    // Brief how-to for this program
42    printf( "\n \t copyMakeBorder Demo: \n" );
43    printf( "\t -------------------- \n" );
44    printf( " ** Press 'c' to set the border to a random constant value \n");
45    printf( " ** Press 'r' to set the border to be replicated \n");
46    printf( " ** Press 'ESC' to exit the program \n");
47
48//![create_window]
49    namedWindow( window_name, WINDOW_AUTOSIZE );
50//![create_window]
51
52    //![init_arguments]
53    // Initialize arguments for the filter
54    top = (int) (0.05*src.rows); bottom = top;
55    left = (int) (0.05*src.cols); right = left;
56    //![init_arguments]
57
58    for(;;)
59    {
60        //![update_value]
61        Scalar value( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255) );
62        //![update_value]
63
64        //![copymakeborder]
65        copyMakeBorder( src, dst, top, bottom, left, right, borderType, value );
66        //![copymakeborder]
67
68        //![display]
69        imshow( window_name, dst );
70        //![display]
71
72        //![check_keypress]
73        char c = (char)waitKey(500);
74        if( c == 27 )
75        { break; }
76        else if( c == 'c' )
77        { borderType = BORDER_CONSTANT; }
78        else if( c == 'r' )
79        { borderType = BORDER_REPLICATE; }
80        //![check_keypress]
81    }
82
83    return 0;
84}