I'm sota, a local go apprentice. Since I am a beginner, I think there are many mistakes, but I would appreciate it if you could let me know in the comments.
I often implement padding in research and bytes, but every time I researched what to do with pillow and opencv, I used it for implementation for almost an hour, but as the title says, it can be implemented in one line with opencv. I understand it, so I will leave it as a memorandum.
cv2.copyMakeBorder()
Specifically, use cv2.copyMakeBorder ()
.
How to use
output = cv2.copyMakeBorder(src, top, bottom, left, right, borderType, value)
is.
--src
is the input image
--top, bottom, left, right
are how many pixels are added to the top, bottom, left, and right of the image.
-- borderType
is a flag to specify the type of boundary to add. If you want so-called padding, select cv2.BORDER_CONSTANT
.
--There are also cv2.BORDER_REFLECT, cv2.BORDER_DEFAULT, cv2.BORDER_REPLICATE, cv2.BORDER_WRAP
, etc., but they are a little different from padding, so please refer to the official document.
http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_core/py_basic_ops/py_basic_ops.html
--value
specifies the color of the padded part. (0,0,0)
is black, (255,255,255)
is white, and so on.
import cv2
img = cv2.imread('./fig.png')
img_pad = cv2.copyMakeBorder(img, 50, 50, 50, 50, cv2.BORDER_CONSTANT, (0,0,0))
cv2.imwrite('./fig_pad.png', img_pad)
I'm padding safely. It was surprisingly easy considering the time and effort of creating a black image and pasting it while thinking about the location with slices each time. I will pad in this way in opencv from now on.
Recommended Posts