Instagram
youtube
Facebook
Twitter

Add Borders

OpenCV allow us to add a variety of borders in OpenCV. OpenCV borders help us to detect and add the edges and boundaries in images, which can be used for a variety of computer vision applications. In this tutorial, we’ll learn about how to add borders in image using OpenCV.

What is copyMakeBorder() in OpenCV?

the cv2.copyMakeBorder() is a function in OpenCV to add borders in images. This function requires you to pass the image, the border type, the border size, the color of the border, and the interpolation method. 

What are borderType flags in OpenCV?

BorderType flags in OpenCV are used to specify the way to process pixels near the image boundary. The available flags are -

  • BORDER_CONSTANT

  • BORDER_REPLICATE

  • BORDER_REFLECT

  • BORDER_WRAP

  • BORDER_REFLECT_101

  • BORDER_TRANSPARENT.

Let's understand the concept with some practical work.

Input

Example of Constant Border:

Code:

import cv2
img = cv2.imread('sum_a.jpg')  
image = cv2.copyMakeBorder(img, 15, 15, 15, 15, cv2.BORDER_CONSTANT, None, value = 0)
cv2.imshow('Constant Border Image', image)
cv2.waitKey(0)  
cv2.destroyAllWindows()

Here, first we imported cv2. then we used cv2.imread to read image of the given path. Then we used  cv2.copyMakeBorder function to add border in image. We used the constant border flag in this code.

Result:


 

Example of Replicate Border:

Code:

import cv2
img = cv2.imread('sum_a.jpg')  
image = cv2.copyMakeBorder(img, 60, 60, 60, 60, cv2.BORDER_REPLICATE, None, value = 0)
cv2.imshow('Constant Border Image', image)
cv2.waitKey(0)  
cv2.destroyAllWindows()

Here, first we imported cv2. then we used cv2.imread to read image of the given path. Then we used  cv2.copyMakeBorder function to add border in image. We used the Replicate border flag in this code.

Result: