0
0
Computer Visionml~5 mins

Cropping images in Computer Vision

Choose your learning style9 modes available
Introduction
Cropping images helps focus on important parts by cutting out unwanted areas. It makes images simpler and clearer for analysis.
You want to zoom in on a face in a photo to recognize emotions.
You need to remove background clutter before training a model.
You want to prepare images to a fixed size for a neural network.
You want to highlight a product in a picture for better detection.
You want to reduce image size to save memory and speed up processing.
Syntax
Computer Vision
cropped_image = image[y_start:y_end, x_start:x_end]
Coordinates start at the top-left corner of the image.
y corresponds to rows (height), x corresponds to columns (width).
Examples
Crops the image from row 50 to 149 and column 100 to 199.
Computer Vision
cropped = image[50:150, 100:200]
Crops the top-left 100x100 pixels of the image.
Computer Vision
cropped = image[:100, :100]
Crops from row 100 to bottom and column 50 to right edge.
Computer Vision
cropped = image[100:, 50:]
Sample Model
This code creates a black image with a white square. Then it crops the white square area and prints the cropped image size and center pixel color.
Computer Vision
import cv2
import numpy as np

# Create a simple 200x200 image with a white square on black background
image = np.zeros((200, 200, 3), dtype=np.uint8)
cv2.rectangle(image, (50, 50), (150, 150), (255, 255, 255), -1)

# Crop the white square area
cropped_image = image[50:151, 50:151]

# Check the shape of cropped image
print('Cropped image shape:', cropped_image.shape)

# Check pixel value at center (should be white)
center_pixel = cropped_image[50, 50]
print('Center pixel value:', center_pixel)
OutputSuccess
Important Notes
Cropping does not change the original image; it creates a new view or copy.
Be careful with coordinates to avoid errors or empty crops.
Cropping is useful before feeding images into models to focus on relevant parts.
Summary
Cropping cuts out a part of an image using row and column ranges.
It helps focus on important areas and reduces image size.
Use slicing syntax image[y_start:y_end, x_start:x_end] to crop.