18-Crop an Image

What is meant by cropping an image

Let's use this method of selecting a range of rows and columns to extract a larger portion from an image. By the way, this is also known as cropping an image.

Cropping an image is the process of removing unwanted parts of an image to improve its composition, focus on the subject, or change its size or aspect ratio. It is a common practice in photography and photo editing, and can be done with a variety of software tools.

Matlab Code

Let's use a different picture this time. Let's see what it looks like. All right, a classic two-wheeler there. Let's check the size of the image first. All right, 320 by 500. When cropping this image, we'd want our limits to be within this range. Let's say we want to select rows 110 through 310, and columns 10 through 160. I wonder what we'll find there. That's the front wheel. No points for that. So what is the size of the cropped image? 

Python Code

There are two popular Python libraries for cropping images: Pillow and OpenCV.

Pillow

To crop an image using Pillow, you can use the Image.crop() method. This method takes a 4-tuple as input, representing the left, upper, right, and lower coordinates of the cropping rectangle.

For example, the following code crops an image to a square of 500x500 pixels at the center of the image:

from PIL import Image
img = Image.
open('my_image.jpg')
# Crop the image to a square of 500x500 pixels at the center of the image.
box = (
250, 250, 750, 750)
cropped_img = img.crop(box)
# Save the cropped image. cropped_img.save('cropped_image.jpg')

OpenCV

To crop an image using OpenCV, you can use the cv2.imcrop() function. This function takes the image and a 4-tuple representing the cropping rectangle as input, and returns a cropped image.

For example, the following code crops an image to a square of 500x500 pixels at the center of the image:

import cv2 
img = cv2.imread('my_image.jpg')
# Crop the image to a square of 500x500 pixels at the center of the image. box = (250, 250, 750, 750)
cropped_img = cv2.imcrop(img, box)
# Save the cropped
image.
cv2.imwrite('cropped_image.jpg', cropped_img)

References

Last modified: Saturday, 21 October 2023, 9:36 AM