Examples of how to add a border (frame) to an image (picture) using python:
Table of contents
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
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
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
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()
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