Making Borders of Image Manually

It is interesting to use ROI to make borders in the image. We set the border pixels to red color using the ROI as shown below. Naturally, we can achieve it by setting the pixel values along the border to a specific color. The following code will manually draw a red line along with the border of the image.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import cv2
import numpy as np
import matplotlib.pyplot as plt
path = r'F:\img\lena.jpg'
img = cv2.imread(path,cv2.IMREAD_COLOR)
img[0:5,:,:] = [0,0,255]
img[:,0:5,:] = [0,0,255]
img[:,img.shape[1]-5:img.shape[1],:] = [0,0,255]
img[img.shape[0]-5:img.shape[0],:,:] = [0,0,255]
rgb = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.imshow(rgb)
plt.axis('off')

Line 6: We set the red color for the top five rows (0:5) and all the columns (:) and for all the channels (:).
Line 7: It does the same thing for all rows(:) and left most five columns (0:5).
Line 8: It is something tricky for the right and bottom borders. Here we need the size of the image. The image size is 225 x 225. We can get the dimensions of the image using the shape() method. To make the right border, we have to set the color for all pixels in columns 220 till 225. So we can get the number of columns by using img.shape[1]. Since shape will return a list containing rows, columns, and channels in this order, we only want the columns, so we provided an index as [1]. Just we want a border of size 5, so we obtained it by taking the difference 225-220.
Line 9: Similarly, we did the same for the bottom border by getting the number of rows using img.shape[0] and then drawing the border of size 5.
Line 10-12: It is just cosmetics. Matplotlib expects an RGB image while OpenCV stores it in BGR format. We converted BGR to RGB and then displayed using the imshow() function of Pyplot of Matplotlib.

A generic square placeholder image with rounded corners in a figure.
Original image.
A generic square placeholder image with rounded corners in a figure.
Bordered image.

Note that we added borders inside the image, not appended borders outside the image. So, the size of the image will not change in this case.


OpenCV Tutorials