Adding Border Tutorial


In this chapter we are going to add different types of border to an image.

We are going to use OpenCV function copyMakeBorder. It can be found under Imgproc package. Its syntax is given below:


The parameters along with their description are listed below:

Sr.NoParameters & description
The Source image.
The destination image.
Length in pixels of the border at the top of the image.
Length in pixels of the border at the bottom of the image.
Length in pixels of the border at the left of the image.
Length in pixels of the border at the right of the image.
Define what type of border is applied. The possible borders are BORDER_REPLICATE, BORDER_REFLECT, BORDER_WRAP, BORDER_CONSTANT e.t.c.

Apart from the copyMakeBorder method, there are other methods provide by the Imgproc class. They are listed below:

Sr.NoMethod & Description
1cvtColor(Mat src, Mat dst, int code, int dstCn)
Converts an image from one colour space to another.
2dilate(Mat src, Mat dst, Mat kernel)
Dilates an image by using a specific structuring element.
3equalizeHist(Mat src, Mat dst)
Equalizes the histogram of a grayscale image.
4filter2D(Mat src, Mat dst, int ddepth, Mat kernel, Point anchor, double delta)
Convolves an image with the kernel.
5GaussianBlur(Mat src, Mat dst, Size ksize, double sigmaX)
Blurs an image using a Gaussian filter.
6integral(Mat src, Mat sum)
Calculates the integral of an image.


The following example demonstrates the use of Imgproc class to add border to an image.

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

public class main {
   public static void main( String[] args )
         System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
         Mat source = Highgui.imread("digital_image_processing.jpg",
         Mat destination = new Mat(source.rows(),source.cols(),source.type());
         int top, bottom, left, right;
         int borderType;

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

         destination = source;
         Imgproc.copyMakeBorder(source, destination, top, bottom, 
         left, right, Imgproc.BORDER_WRAP);
         Highgui.imwrite("borderWrap.jpg", destination);
         }catch (Exception e) {
            System.out.println("error: " + e.getMessage());


Original Image

Adding Border Tutorial

Isolated Border Image

Adding Border Tutorial

Wrapped Border Image

Adding Border Tutorial

Reflect Border Image

Adding Border Tutorial