OpenCV Python – How to add borders to an image?


OpenCV provides the function cv2.copyMakeBorder() to add borders in images. To add border in an image, you could follow the steps given below −

  • The first step is to import required libraries. In all below Python examples the required Python library is OpenCV. Make sure you have already installed it.

  • The next step is to read an input image using the cv2.imread() function. Specify the full image path with image types (.jpg or .png).

  • Specify different parameters to the function cv2.copyMakeBorder(). The different parameters to be specified are src, dst, top, bottom, left, right, borderType, and value.

  • Call cv2.copyMakeBorder() function passing the above specified parameters to add the borders to the input image.

img1 = cv2.copyMakeBorder(src, top, bottom, left, right, borderType,dst,value)
  • Display the output image with borders.

Let's understand the adding borders to images using OpenCV Python with the help of some Python examples.

We will use this image as the Input File in the following examples −


Example

In this Python program, we add borders with different border sizes for different sides- top, bottom, left, right. We applied the border type cv2.BORDER_CONSTANT.

# import required library import cv2 # read input image img = cv2.imread('building.jpg') # set different parameters src = img dst = None top, bottom, left, right = 50, 100, 130, 200 borderType = cv2.BORDER_CONSTANT value=[255, 255, 0] # Add borders with above parameters img1 = cv2.copyMakeBorder(src, top, bottom, left, right, borderType,dst,value) # display the image with borders cv2.imshow("Image with Borders", img1) cv2.waitKey(0) cv2.destroyAllWindows()

Output

When you run the above program, it will produce the following output window −


We added the borders to the input image with border size (pixels) top=50, bottom=100, left= 130, and right=200.

Example

In this program, we add borders with different border sizes for different sides- top, bottom, left, right. We applied the border type cv2.BORDER_REPLICATE.

# import required library import cv2 # read input image img = cv2.imread('building.jpg') src = img dst = None top, bottom, left, right = 50, 50, 100, 100 borderType = cv2.BORDER_REPLICATE # add borders img1 = cv2.copyMakeBorder(src, top, bottom, left, right, borderType,dst) cv2.imshow("Image with Borders", img1) cv2.waitKey(0) cv2.destroyAllWindows()

Output

When you run the above program, it will produce the following output window −


We added the borders to the input image with border size (pixels) top=50, bottom=100, left= 130, and right=200.

Notice the difference between the border types used in the above two examples.

Updated on: 02-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements