After learning how to read and display images, the next step is performing basic image operations. OpenCV provides simple functions for resizing, cropping, rotating, and flipping images. These operations are commonly used in preprocessing before applying computer vision algorithms.
Use cv2.resize() to change the width and height of an image.
import cv2
img = cv2.imread("sample.jpg")
resized = cv2.resize(img, (400, 300)) # width=400, height=300
cv2.imshow("Resized Image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
Cropping is done by selecting a region of interest (ROI) using pixel slicing.
cropped = img[50:200, 100:300] # [y1:y2, x1:x2]
cv2.imshow("Cropped Image", cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()
Use cv2.getRotationMatrix2D() with cv2.warpAffine() to rotate an image.
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
matrix = cv2.getRotationMatrix2D(center, 45, 1.0) # Rotate 45 degrees
rotated = cv2.warpAffine(img, matrix, (w, h))
cv2.imshow("Rotated Image", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
Use cv2.flip() to flip an image horizontally, vertically, or both.
flip_horizontal = cv2.flip(img, 1) # Horizontal flip flip_vertical = cv2.flip(img, 0) # Vertical flip flip_both = cv2.flip(img, -1) # Both directions
✅ In this lesson, you learned how to perform resize, crop, rotate, and flip operations in OpenCV.
These preprocessing techniques are essential in image analysis, preparing data for computer vision models.
👉 With this, we complete Module 1: Introduction to OpenCV. Next, we’ll test your knowledge with a quiz. 🎯
