Skip to main content

Trim Image to Equal Height and Width using Python

Trimming image using python:
                           The following code contains to trim image in equal height and width size. To do this image pixel stored as array of pixel.

from PIL import Image
import cv2
import numpy as np
from matplotlib import pyplot as plt
imagename = "pixg.png"
img = cv2.imread(imagename, 0) # 0 params, for gray image
height, width = img.shape[:2]  # image height and width
img1 = Image.fromarray(img)
print("height")
print(height)
print("width")
print(width)
array=np.array(img)
d=np.delete(array,231,0)
d=np.delete(d,231,0)
d=np.delete(d,231,0)
d=np.delete(d,230,0)
img2=Image.fromarray(d)
plt.imshow(img2,cmap = 'gray')
plt.show()
print("After Trim")
height, width = img2.size
#img2.save('trim.png')
print("height")
print(height)
print("width")
print(width)

Output:
 height:234, width:230
After Trim:
height:230, width:230

By using cv2 the img read the image from local file. The numpy np convert image into array of pixel. 
np.delete(d,1,0)  will delete row, np.delete(d,1,1) will delete  column.
In the above example width=230 and height=234. We delete extra 4 rows from the image matrix, by d=np.delete(array,231,0)
d=np.delete(d,231,0)
d=np.delete(d,231,0)
d=np.delete(d,230,0).




Comments