OpenCV Tutorial
Image Processing
Feature Detection and Description
Drawing Functions
Video Processing
Applications and Projects
Adding a border around an image can be useful in many scenarios, such as padding, visualization, or separating images. OpenCV provides a simple way to achieve this using the copyMakeBorder()
function. This function allows you to create different types of borders, including constant-colored borders and replicated borders.
Ensure you have OpenCV installed:
pip install opencv-python
Import necessary libraries:
import cv2 import numpy as np
Load the image on which you want to add a border:
image = cv2.imread('path_to_image.jpg')
Use the cv2.copyMakeBorder()
function:
bordered_image = cv2.copyMakeBorder(image, top, bottom, left, right, borderType, value=color)
Where:
image
: The source image.top
, bottom
, left
, right
: Width of borders in the respective directions.borderType
: The type of border to be added (e.g., cv2.BORDER_CONSTANT
for a colored border, cv2.BORDER_REPLICATE
to replicate the edge-most content).color
: Color of the border (used only if borderType
is cv2.BORDER_CONSTANT
).Example of adding a constant blue border of 10 pixels in all directions:
border_size = 10 color = [255, 0, 0] # Blue color in BGR format bordered_image = cv2.copyMakeBorder(image, border_size, border_size, border_size, border_size, cv2.BORDER_CONSTANT, value=color)
Example of adding a replicated border:
border_size = 10 bordered_image = cv2.copyMakeBorder(image, border_size, border_size, border_size, border_size, cv2.BORDER_REPLICATE)
cv2.imshow('Bordered Image', bordered_image) cv2.waitKey(0) cv2.destroyAllWindows()
Upon running the code, you'll see your image displayed with the desired border. Depending on the parameters you choose, this can be a constant color or a replicated edge of the image.
This wraps up the tutorial on adding borders to images using OpenCV. The copyMakeBorder()
function is versatile and can create various border styles by adjusting its parameters.
Adding Borders to Images in OpenCV:
import cv2 import numpy as np # Read an image img = cv2.imread('image.jpg') # Add a border to the image border_color = (0, 255, 0) # Green color border_thickness = 10 img_with_border = cv2.copyMakeBorder(img, border_thickness, border_thickness, border_thickness, border_thickness, cv2.BORDER_CONSTANT, value=border_color) # Display the original and bordered images cv2.imshow('Original Image', img) cv2.imshow('Image with Border', img_with_border) cv2.waitKey(0) cv2.destroyAllWindows()