Open In App

Adding borders to the images using Python – OpenCV

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Image processing is an interesting field in today’s era of Artificial Intelligence and Machine Learning. We can see the applications of image processing in our day-to-day life, like whenever we apply filter over any image (selfie) or when we want to apply some effect like blurring the image, etc. 

In this article, we will discuss how to add borders to an image using Python. Python provides a module called OpenCV that can be used for the same. So before adding borders let’s see a small introduction about OpenCV.

OpenCV (Open Source Computer Vision Library)

  • It is an open-source library.
  • Designed to solve Computer Vision problems.
  • It makes use of a highly optimized library for numerical operations which is Numpy along with MATLAB style syntax.

To add borders to the images OpenCV has a package copyMakeBorder which helps to make a border around the image.

Syntax: cv2.copyMakeBorder()

Parameters of copyMakeBorder:

  • inputImage
  • topBorderWidth
  • bottomBorderWidth
  • leftBorderWidth
  • rightBorderWidth
  • cv2.BORDER_CONSTANT
  • value=color of border

Input Image:

Example:

Python3




# importing required packages
  
import cv2
  
# reading the image
virat_img = cv2.imread('geek.jpg')
  
# making border around image using copyMakeBorder
borderoutput = cv2.copyMakeBorder(
    virat_img, 20, 20, 20, 20, cv2.BORDER_CONSTANT, value=[255, 255, 0])
  
# showing the image with border
cv2.imwrite('output.png', borderoutput)


Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads