如何在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.
下面的代码向原始图像的所有四个侧面添加大小为10像素的恒定边框.
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.
如果将底部和右侧的bordersize值保留为0,甚至会得到对称的边框.
If you leave bordersize values for bottom and right at 0, you even get a symmetric border.
BORDER_TYPE的其他值也是可能的,例如BORDER_DEFAULT,BORDER_REPLICATE,BORDER_WRAP.
Other values for BORDER_TYPE are possible, such as BORDER_DEFAULT, BORDER_REPLICATE, BORDER_WRAP.
有关更多详细信息,请参见: http://docs .opencv.org/trunk/d3/df2/tutorial_py_basic_ops.html#gsc.tab = 0
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()