Use the OpenCV function :copy_make_border:`copyMakeBorder <>` to set the borders (extra padding to your image). The explanation below belongs to the bookLearning OpenCV by Bradski and Kaehler.
This will be seen more clearly in the Code section.
What does this program do?
''' file name : border.py
Description : This sample shows how to add border to an image'''
import cv2
import numpy as np
print " Press r to replicate the border with a random color "
print " Press c to replicate the border "
print " Press Esc to exit "
img = cv2.imread('../boldt.jpg')
rows,cols = img.shape[:2]
dst = img.copy()
top = int (0.05*rows)
bottom = int (0.05*rows)
left = int (0.05*cols)
right = int (0.05*cols)
while(True):
cv2.imshow('border',dst)
k = cv2.waitKey(500)
if k==27:
break
elif k == ord('c'):
value = np.random.randint(0,255,(3,)).tolist()
dst = cv2.copyMakeBorder(img,top,bottom,left,right,
cv2.BORDER_CONSTANT,value = value)
elif k == ord('r'):
dst = cv2.copyMakeBorder(img,top,bottom,left,right,cv2.BORDER_REPLICATE)
cv2.destroyAllWindows()
1. Now we initialize the argument that defines the size of the borders (top,bottom,left andright). We give them a value of 5% the size of src.
top = int (0.05*rows)
bottom = int (0.05*rows)
left = int (0.05*cols)
right = int (0.05*cols)
2. The program begins a while loop. If the user presses 'c' or 'r', the borderType variable takes the value ofBORDER_CONSTANT orBORDER_REPLICATE respectively:
while(True):
cv2.imshow('border',dst)
k = cv2.waitKey(500)
if k==27:
break
elif k == ord('c'):
value = np.random.randint(0,255,(3,)).tolist()
dst = cv2.copyMakeBorder(img,top,bottom,left,right,cv2.BORDER_CONSTANT,value = value)
elif k == ord('r'):
dst = cv2.copyMakeBorder(img,top,bottom,left,right,cv2.BORDER_REPLICATE)
3. Finally, we call the function :copy_make_border:`copyMakeBorder <>` to apply the respective padding:
copyMakeBorder( src, dst, top, bottom, left, right, borderType, value );
The arguments are:
After compiling the code above, you can execute it giving as argument the path of an image. The result should be:
Below some screenshot showing how the border changes color and how theBORDER_REPLICATE option looks: