Introduction
Cropping images helps focus on important parts by cutting out unwanted areas. It makes images simpler and clearer for analysis.
Jump into concepts and practice - no test required
cropped_image = image[y_start:y_end, x_start:x_end]
cropped = image[50:150, 100:200]
cropped = image[:100, :100]
cropped = image[100:, 50:]
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)
img to rows 10 to 50 and columns 20 to 70 in Python?import numpy as np img = np.arange(100).reshape(10,10) cropped = img[2:5, 3:7] print(cropped)
cropped = img[50:100, 30:60] but get an IndexError. What is the likely cause?