OpenCV
Resize and Crop
Resize with interpolation and crop regions of interest.
By EZ4Code Team
resizecrop
Code
import cv2
img = cv2.imread("input.jpg")
h, w = img.shape[:2]
# Resize to fixed size
fixed = cv2.resize(img, (300, 200))
# Resize by scale factor, preserving aspect
scaled = cv2.resize(img, None, fx=0.5, fy=0.5,
interpolation=cv2.INTER_AREA)
# Crop a region of interest (y, x ordering)
roi = img[100:400, 200:600]
# Resize to a target width keeping aspect ratio
target_w = 400
ratio = target_w / w
new_size = (target_w, int(h * ratio))
resized = cv2.resize(img, new_size, interpolation=cv2.INTER_LINEAR)
cv2.imwrite("roi.jpg", roi)Explanation
resize() accepts either an explicit (width, height) or scale factors fx and fy, with INTER_AREA best for shrinking and INTER_CUBIC for enlarging. Cropping uses NumPy slicing with row-first indexing [y1:y2, x1:x2]. Aspect ratio can be preserved by computing the new height from a target width.
More OpenCV Snippets
Read and Write Images
Load, display, and save images in various formats.
Color Conversion
Convert between BGR, RGB, HSV, and grayscale.
Blur and Filter
Smooth and sharpen images with kernels.
Edge Detection
Detect edges with Canny, Sobel, and Laplacian.
Contours
Find, draw, and measure contours.
Face Detection
Detect faces with a Haar cascade classifier.