Add borders to the image using OpenCV-Python

In this blog, we will learn how to add different borders to the image using OpenCV-Python. Adding border doesn’t only make the image looks stylish but this is also useful in many image processing tasks such as image interpolation, morphological operations, edge detection, etc. OpenCV provides different border styles and in this blog, we will explore these. Below is the inbuilt function provided by OpenCV for this.

Here, src is the input image and top, left, right, and bottom specifies how many pixels to add in each direction. “borderType” specifies what type of border to add. Below are the types available in OpenCV.

  • cv2.BORDER_REFLECT: this reflects the border elements such as fedcba|abcdefgh|hgfedcb
  • cv2.BORDER_REFLECT_101: this reflects leaving the border pixel such as gfedcb|abcdefgh|gfedcba
  • cv2.BORDER_REPLICATE: Border pixel will be replicated such as aaaaaa|abcdefgh|hhhhhhh
  • cv2.BORDER_WRAP: this reflects the pixel from the opposite boundary as cdefgh|abcdefgh|abcdefg
  • cv2.BORDER_CONSTANT: this adds a constant border whose value is given by the “value” argument.

Now, let’s take an example to illustrate this. Here, I have created a trackbar that lets us understand this clearly.

Play around with these trackbars to get a feeling of different border types. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Leave a Reply