Crop images in Python with array indexes
The advantage of this simple procedure for image cropping is that there’s no need to install special image manipulation packages.
To demonstrate this cropping process, I am going to use this image of the Salamanca Market in Hobart, Tasmania, Australia. My aim will be to crop the image so that I can focus in on the “Tasmanian Printed T-Shirts” sign.
I only need to import two packages: OpenCV and PyPlot from the MatPlotLib package:
import cv2
import matplotlib.pyplot as plt
Next, I will import my image:
img = cv2.imread("/home/username/path/to/hobart.jpg")
I can use PyPlot to check that the image has loaded correctly:
plt.imshow(img)
Next, I need to identify the cropping region. The formula for this is img[min_y:max_y, min_x:max_x]
. So the code for cropping this particular image will be:
img_crop = img[50:1000, 2050:3000]
Now for a check to see that it’s worked:
plt.imshow(img_crop)
Success!
Comments
No comments have yet been submitted. Be the first!