OpenCV Python – Resize and Rotate an Image
Image resizing and rotation are two of the most important transformations in OpenCV. They are widely used in image preprocessing, computer vision models, and UI adjustments.
In this tutorial, you will learn how to resize and rotate images using OpenCV Python step by step.
1. Why Resize and Rotate Images?
Image transformation is used in:
- Preparing data for AI models
- Adjusting image dimensions
- Correcting image orientation
- Video frame processing
- Image augmentation
2. Import OpenCV
import cv2
3. Read an Image
img = cv2.imread("image.jpg")
cv2.imshow("Original Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
4. Resize an Image
Syntax:
cv2.resize(image, (width, height))
Example:
resized = cv2.resize(img, (300, 300))
cv2.imshow("Resized Image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
Resize Using Scaling Factor
resized = cv2.resize(img, None, fx=0.5, fy=0.5)
cv2.imshow("Scaled Image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
5. Rotate an Image
Step 1: Get Image Dimensions
(h, w) = img.shape[:2]
Step 2: Define Rotation Center
center = (w // 2, h // 2)
Step 3: Create Rotation Matrix
matrix = cv2.getRotationMatrix2D(center, 45, 1.0)
- 45 → rotation angle
- 1.0 → scale factor
Step 4: Apply Rotation
rotated = cv2.warpAffine(img, matrix, (w, h))
cv2.imshow("Rotated Image", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
6. Full Example: Resize and Rotate
import cv2
img = cv2.imread("image.jpg")
# Resize
resized = cv2.resize(img, (400, 400))
# Rotate
(h, w) = resized.shape[:2]
center = (w // 2, h // 2)
matrix = cv2.getRotationMatrix2D(center, 30, 1.0)
rotated = cv2.warpAffine(resized, matrix, (w, h))
cv2.imshow("Final Image", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
7. Types of Rotation
- Clockwise rotation
- Anti-clockwise rotation
- 90°, 180°, 270° rotation
- Custom angle rotation
8. Common Mistakes
❌ Image distortion after resize
✔ Solution:
- Maintain aspect ratio
cv2.resize(img, None, fx=0.5, fy=0.5)
❌ Cropped rotation output
✔ Solution:
-
Adjust output size in
warpAffine
9. Applications
Resize and rotate operations are used in:
- Image preprocessing for AI models
- Data augmentation in deep learning
- Mobile camera apps
- Object detection systems
- Video editing tools
10. Conclusion
Resizing and rotating images are fundamental OpenCV skills. They help prepare and transform images for real-world computer vision applications and AI systems.
Once you master these operations, you can move toward advanced image augmentation and transformations.


0 Comments