Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add border around an image in opencv python

If I have an image like below, how can I add border all around the image such that the overall height and width of the final image increases but the height and width of the original image stays as-is in the middle.

enter image description here

like image 526
Anthony Avatar asked Mar 28 '16 03:03

Anthony


People also ask

What is cv2 copyMakeBorder?

cv2. copyMakeBorder() method is used to create a border around the image like a photo frame. Syntax: cv2.copyMakeBorder(src, top, bottom, left, right, borderType, value) Parameters: src: It is the source image.

What is Border_constant?

BORDER_CONSTANT: Pad the image with a constant value (i.e. black or 0. BORDER_REPLICATE: The row or column at the very edge of the original is replicated to the extra border.

How do I crop a frame in OpenCV?

There is no specific function for cropping using OpenCV, NumPy array slicing is what does the job. Every image that is read in, gets stored in a 2D array (for each color channel). Simply specify the height and width (in pixels) of the area to be cropped. And it's done!


2 Answers

The following code adds a constant border of size 10 pixels to all four sides of your original image.

For the colour, I have assumed that you want to use the average gray value of the background, which I have calculated from the mean value of bottom two lines of your image. Sorry, somewhat hard coded, but shows the general how-to and can be adapted to your needs.

If you leave bordersize values for bottom and right at 0, you even get a symmetric border.

Other values for BORDER_TYPE are possible, such as BORDER_DEFAULT, BORDER_REPLICATE, BORDER_WRAP.

For more details cf: http://docs.opencv.org/trunk/d3/df2/tutorial_py_basic_ops.html#gsc.tab=0

import numpy as np import cv2  im = cv2.imread('image.jpg') row, col = im.shape[:2] bottom = im[row-2:row, 0:col] mean = cv2.mean(bottom)[0]  bordersize = 10 border = cv2.copyMakeBorder(     im,     top=bordersize,     bottom=bordersize,     left=bordersize,     right=bordersize,     borderType=cv2.BORDER_CONSTANT,     value=[mean, mean, mean] )  cv2.imshow('image', im) cv2.imshow('bottom', bottom) cv2.imshow('border', border) cv2.waitKey(0) cv2.destroyAllWindows() 
like image 193
tfv Avatar answered Oct 04 '22 05:10

tfv


Try This:

import cv2 import numpy as np       img=cv2.imread("img_src.jpg") h,w=img.shape[0:2]  base_size=h+20,w+20,3 # make a 3 channel image for base which is slightly larger than target img base=np.zeros(base_size,dtype=np.uint8) cv2.rectangle(base,(0,0),(w+20,h+20),(255,255,255),30) # really thick white rectangle base[10:h+10,10:w+10]=img # this works 
like image 25
Saransh Kejriwal Avatar answered Oct 04 '22 05:10

Saransh Kejriwal