This chapter teaches you how toad borders to an image.
The copyMakeBorder() Method
You can add various borders to an image in using the method copyMakeBorder() of the class named Core, which belongs to the package org.opencv.core. following is the syntax of this method.
copyMakeBorder(src, dst, top, bottom, left, right, borderType)
This method accepts the following parameters −
-
src − An object of the class Mat representing the source (input) image.
-
dst − An object of the class Mat representing the destination (output) image.
-
top − A variable of integer the type integer representing the length of the border at the top of the image.
-
bottom − A variable of integer the type integer representing the length of the border at the bottom of the image.
-
left − A variable of integer the type integer representing the length of the border at the left of the image.
-
right − A variable of integer the type integer representing the length of the border at the right of the image.
-
borderType − A variable of the type integer representing the type of the border that is to be used.
Example
Following program is an example demonstrating, how to add border to a given image.
import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; public class AddingBorder { public static void main( String[] args ) { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file ="E:/OpenCV/chap15/input.jpg"; Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat dst = new Mat(); Core.copyMakeBorder(src, dst, 20, 20, 20, 20, Core.BORDER_CONSTANT); Imgcodecs.imwrite("E:/OpenCV/chap15/border_constant.jpg", dst); System.out.println("Image Processed"); } }
Assume that following is the input image thresh_input.jpg specified in the above program.
Output
On executing the program, you will get the following output −
Image Processed
If you open the specified path, you can observe the output image as follows −
Other Types of Borders
In addition to the border type, BORDER_CONSTANT demonstrated in the previous example, OpenCV caters various other types of borders. All these types are represented by predefined static fields (fixed values) of Core class.
You can choose the type of the threshold operation you need, by passing its respective predefined value to the parameter named borderType of the copyMakeBorder() method.
Core.copyMakeBorder(src, dst, 20, 20, 20, 20, Core.BORDER_CONSTANT);
Following are the values representing various types of borders operations and their respective outputs.
Operation and Description | Output |
---|---|
BORDER_CONSTANT | |
BORDER_ISOLATED | |
BORDER_DEFAULT | |
BORDER_REFLECT | |
BORDER_REFLECT_101 | |
BORDER_REFLECT101 | |
BORDER_REPLICATE | |
BORDER_WRAP |
Learning working make money