I want to fill the image to become a square one. The interface copyMakeBorder can help us to expand the original image to a bigger size.

/*
@param top
@param bottom
@param left
@param right Parameter specifying how many pixels in each direction from the source image rectangle
to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs
to be built.
*/
CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst,
                                 int top, int bottom, int left, int right,
                                 int borderType, const Scalar& value = Scalar() );

Here is a rectangle image.

The following program expand it to a square image.

#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"

using namespace cv;

int main( int argc, char** argv )
{
    Mat src, dst;
    const char* imageName = "/Users/weiyang/Desktop/person.png";
    const char* window_name = "copyMakeBorder";
    src = imread( imageName, IMREAD_COLOR );

    if( src.empty() )
    {
        fprintf( stderr, "Error opening image\n" );
        return -1;
    }
    namedWindow( window_name, WINDOW_AUTOSIZE );
    int side = max( src.rows, src.cols );
    int top = static_cast<int>( (side - src.rows ) / 2.0 + 0.5 );
    int bottom = side - src.rows - top;
    int left = (side - src.cols ) / 2;
    int right = side - src.cols - left;
    copyMakeBorder( src, dst, top, bottom, left, right, BORDER_REPLICATE, Scalar(0, 0, 0) );
    imshow( window_name, dst );
    waitKey( 0 );
    imwrite( "/Users/weiyang/Desktop/newImage.png", dst );
    return 0;
}

Result:

Categories: OpenCV

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x