How to add a border (frame) to an image using python ?

Active February 07, 2022    /    Viewed 288    /    Comments 0    /    Edit


Examples of how to add a border (frame) to an image (picture) using python:

Import an image

Let's first import an image using python (for example Eiffel Tower):

from matplotlib import image

import matplotlib.pyplot as plt

img = image.imread("eiffel-tower.jpeg")

plt.imshow(img)

plt.show()

print(img.shape)

Add a frame to an image

To add a frame/border to an image, a solution is to use numpy.pad. An example by adding a black border "constant_values=0":

img1 = np.pad(img, ((100, 100), (200, 200), (0,0)), constant_values=0)

print(img1.shape)

plt.imshow(img1)

plt.savefig("pad_image_01.png", bbox_inches='tight', dpi=100)

plt.show()

gives then

Add a frame to an image

Padding only at the top and bottom of the image

img1 = np.pad(img, ((100, 100), (0, 0), (0,0)), constant_values=0)

print(img1.shape)

plt.imshow(img1)

plt.savefig("pad_image_02.png", bbox_inches='tight', dpi=100)

plt.show()

gives

Add a frame to an image

Padding only at the right and left sides of the image

img1 = np.pad(img, ((0, 0), (200, 200), (0,0)), constant_values=0)

print(img1.shape)

plt.imshow(img1)

plt.savefig("pad_image_03.png", bbox_inches='tight', dpi=100)

plt.show()

gives

Add a frame to an image

Example using nearest values 'edge' to padd the image:

img1 = np.pad(img, ((100, 100), (0, 0), (0,0)), 'edge')

print(img1.shape)

plt.imshow(img1)

plt.savefig("pad_image_04.png", bbox_inches='tight', dpi=100)

plt.show()

Add a frame to an image

Remove image axis

Note: to get only the image without the axis with matplotlib a solution is to do

import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

my_dpi=100

Shape = img1.shape

fig = plt.figure()

ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)

im = plt.imshow(img1)

plt.savefig("pad_image_05.png", bbox_inches='tight', dpi=100)

plt.show()

gives here

Add a frame to an image

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount