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.
1 |
cv2.copyMakeBorder(src, top, bottom, left, right, borderType[, value]) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import cv2 # Load the image img = cv2.imread('D:/downloads/open1.PNG') # create window title_window = "Border type demo" cv2.namedWindow(title_window) border_dic = {0: 'Constant', 1: 'Replicate', 2: 'Reflect', 3: 'Wrap', 4: 'Reflect_101'} # define callback function def bordertype(val): # get current trackbar position border = cv2.getTrackbarPos('Bordertype', title_window) left = cv2.getTrackbarPos('left', title_window) right = cv2.getTrackbarPos('right', title_window) top = cv2.getTrackbarPos('top', title_window) bottom = cv2.getTrackbarPos('bottom', title_window) val = cv2.getTrackbarPos('value', title_window) # Add border out = cv2.copyMakeBorder(img,top,bottom,left,right,border,value=[val,val,val]) # display text font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(out,'Border:{}'.format(border_dic[border]),(10,40), font, 0.5,(0,255,255),1,cv2.LINE_AA) cv2.imshow(title_window, out) # create trackbars cv2.createTrackbar('Bordertype', title_window , 0, 4, bordertype) cv2.createTrackbar('left', title_window , 0, 25, bordertype) cv2.createTrackbar('right', title_window , 0, 25, bordertype) cv2.createTrackbar('top', title_window , 0, 25, bordertype) cv2.createTrackbar('bottom', title_window , 0, 25, bordertype) cv2.createTrackbar('value', title_window , 0, 255, bordertype) # Instantiate the function bordertype(0) cv2.waitKey() |
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.