Image preprocessing is one of the most important stages in computer vision and image processing. Before applying machine learning models, object detection, face recognition, or image classification, images often need to be resized, cropped, rotated, or flipped. These operations improve consistency, reduce computational cost, and prepare images for further analysis.
In this lesson, you will begin by learning how to resize images using OpenCV. Resizing changes the dimensions of an image while preserving as much visual information as possible. It is widely used in data preprocessing, web applications, deep learning, and computer vision projects.
Image resizing is the process of changing the width and height of an image. An image can be enlarged or reduced depending on the requirements of the application.
For example, a high-resolution image captured by a digital camera may have dimensions of 4000 × 3000 pixels. Such large images consume more memory and require longer processing time. Resizing the image to 800 × 600 pixels makes it faster to process while maintaining sufficient visual information for many tasks.
Resizing is one of the most common preprocessing operations in computer vision. It offers several advantages:
OpenCV provides the cv2.resize() function to resize images. This function allows you to specify either the exact output dimensions or scaling factors.
Syntax:
cv2.resize(src, dsize, fx=None, fy=None, interpolation=cv2.INTER_LINEAR)
The simplest way to resize an image is by specifying its new width and height.
import cv2
image = cv2.imread("sample.jpg")
resized = cv2.resize(image, (400,300))
cv2.imshow("Resized Image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
The resized image now has a width of 400 pixels and a height of 300 pixels.
Instead of specifying dimensions, you can resize images using scaling factors.
import cv2
image = cv2.imread("sample.jpg")
resized = cv2.resize(
image,
None,
fx=0.5,
fy=0.5
)
The image width and height become 50% of the original dimensions.
Similarly, using fx=2 and fy=2 doubles the image size.
The aspect ratio is the relationship between an image’s width and height. Maintaining the correct aspect ratio prevents the image from appearing stretched or compressed.
For example:
If you resize an image without maintaining its aspect ratio, circles may appear as ovals and faces may become distorted.
A common approach is to calculate the new dimensions while preserving the original ratio.
import cv2
image = cv2.imread("sample.jpg")
height, width = image.shape[:2]
new_width = 600
new_height = int(height * (new_width / width))
resized = cv2.resize(image, (new_width, new_height))
This approach keeps the image proportions unchanged.
Interpolation determines how OpenCV estimates pixel values when resizing an image.
| Interpolation Method | Recommended Use |
|---|---|
| INTER_NEAREST | Fastest but lower quality. |
| INTER_LINEAR | Default method for enlarging images. |
| INTER_AREA | Best for reducing image size. |
| INTER_CUBIC | High-quality enlargement. |
| INTER_LANCZOS4 | Highest quality but slower. |
Example:
resized = cv2.resize(
image,
(400,300),
interpolation=cv2.INTER_AREA
)
INTER_AREA when reducing image size.INTER_CUBIC or INTER_LINEAR when enlarging images.
In this lesson, you learned how to resize images using OpenCV with the cv2.resize() function. You explored fixed-size resizing, scaling factors, aspect ratio preservation, interpolation methods, and real-world applications. Image resizing is one of the most important preprocessing techniques in computer vision and serves as the foundation for many machine learning and image analysis tasks.
After learning how to resize images, the next essential image processing operations are cropping, rotating, and flipping. These techniques are widely used in computer vision applications such as face recognition, object detection, medical imaging, image augmentation, document scanning, and deep learning.
These operations help focus on important regions of an image, correct image orientation, create training datasets, and improve the performance of machine learning models.
Image cropping is the process of selecting a specific portion of an image while removing unwanted areas. Instead of modifying the original image, cropping extracts a region called the Region of Interest (ROI).
Cropping is commonly used when only a specific object or area needs to be analyzed.
Examples include:
Unlike many image editing software applications, OpenCV does not provide a separate cropping function. Since images are stored as NumPy arrays, cropping is performed using array slicing.
Syntax:
cropped = image[y1:y2, x1:x2]
Notice that rows (y-values) come before columns (x-values).
import cv2
image = cv2.imread("sample.jpg")
cropped = image[100:350, 150:450]
cv2.imshow("Cropped Image", cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()
The program extracts the selected rectangular region while leaving the original image unchanged.
A Region of Interest (ROI) is the specific portion of an image that contains useful information for analysis.
Instead of processing an entire image, many computer vision systems analyze only the ROI, improving speed and reducing computational cost.
Examples of ROI include:
Image rotation changes the orientation of an image by rotating it around a fixed point. Rotation is useful when images are tilted, scanned incorrectly, or need data augmentation for machine learning.
OpenCV performs arbitrary rotations using two functions:
cv2.getRotationMatrix2D()cv2.warpAffine()The first step is to create a rotation matrix by specifying:
matrix = cv2.getRotationMatrix2D(center, angle, scale)
import cv2
image = cv2.imread("sample.jpg")
height, width = image.shape[:2]
center = (width // 2, height // 2)
matrix = cv2.getRotationMatrix2D(center, 45, 1)
rotated = cv2.warpAffine(image, matrix, (width, height))
cv2.imshow("Rotated", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
The image is rotated by 45 degrees while maintaining the original canvas size.
OpenCV also provides predefined rotation constants for common rotations.
rotated = cv2.rotate(
image,
cv2.ROTATE_90_CLOCKWISE
)
Other options include:
Flipping creates a mirror image by reversing the image along one or both axes. Image flipping is widely used for image augmentation because it increases dataset diversity without collecting additional data.
Syntax:
cv2.flip(image, flipCode)
The flip code determines the direction of the flip.
| Flip Code | Operation |
|---|---|
| 0 | Vertical Flip |
| 1 | Horizontal Flip |
| -1 | Horizontal and Vertical Flip |
import cv2
image = cv2.imread("sample.jpg")
flipped = cv2.flip(image, 1)
cv2.imshow("Horizontal Flip", flipped)
cv2.waitKey(0)
cv2.destroyAllWindows()
In this lesson, you learned how to crop images using NumPy slicing, rotate images using rotation matrices and predefined rotation functions, and flip images horizontally or vertically using cv2.flip(). These operations are fundamental preprocessing techniques used in almost every computer vision and deep learning project.
In real-world computer vision applications, a single image processing operation is rarely sufficient. Instead, developers combine multiple operations such as resizing, cropping, rotating, and flipping to prepare images before applying machine learning models or computer vision algorithms.
For example, before training a face recognition model, images are often resized to a standard resolution, cropped to focus on the face, rotated to correct orientation, and flipped to increase the diversity of the training dataset.
An image preprocessing pipeline is a sequence of operations applied to an image before analysis. The exact steps depend on the application, but a common workflow looks like this:
cv2.imread().The following program demonstrates how several image transformations can be applied in sequence.
import cv2
# Read the image
image = cv2.imread("sample.jpg")
# Resize
image = cv2.resize(image, (600, 400))
# Crop
image = image[50:350, 100:500]
# Rotate
height, width = image.shape[:2]
center = (width // 2, height // 2)
matrix = cv2.getRotationMatrix2D(center, 30, 1.0)
image = cv2.warpAffine(image, matrix, (width, height))
# Flip horizontally
image = cv2.flip(image, 1)
# Display result
cv2.imshow("Processed Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
This example illustrates a simple preprocessing pipeline that can be adapted for many computer vision tasks.
Image augmentation is the process of creating additional training images by applying transformations to existing images. Instead of collecting thousands of new images, developers generate new variations using operations such as resizing, rotation, flipping, cropping, brightness adjustment, and scaling.
Image augmentation helps machine learning models become more accurate and robust by exposing them to different versions of the same object.
Common augmentation techniques include:
Basic image operations are used across a wide range of industries and technologies.
| Industry | Application |
|---|---|
| Healthcare | Preparing X-ray and MRI images for diagnosis. |
| Security | Face recognition and surveillance systems. |
| Retail | Product image preprocessing for visual search. |
| Manufacturing | Quality inspection and defect detection. |
| Agriculture | Crop and plant disease monitoring. |
| Autonomous Vehicles | Preprocessing camera images before object detection. |
| Robotics | Vision-based navigation and object tracking. |
INTER_AREA for shrinking and INTER_CUBIC for enlarging images.Machine learning and deep learning models typically require input images of a fixed size. Resizing ensures consistency across the dataset and reduces computational requirements.
Cropping removes unwanted portions of an image while preserving the original pixel values in the selected area. Resizing changes the dimensions of the entire image, which may alter pixel values through interpolation.
Image flipping is commonly used during data augmentation to increase the variety of training images without collecting additional data.
Repeated rotations can introduce interpolation artifacts and slightly reduce image quality. Whenever possible, apply only the necessary transformations.
cv2.resize() changes image dimensions.cv2.getRotationMatrix2D() and cv2.warpAffine() rotate images.cv2.flip() performs horizontal, vertical, or both-direction flips.Congratulations! You have completed Module 1: Introduction to OpenCV. In this module, you learned the fundamentals of computer vision and image processing using OpenCV. You explored the history and applications of OpenCV, installed the library in Python, configured Jupyter Notebook, understood how images are represented as pixels, learned about BGR, RGB, Grayscale, and HSV color spaces, and practiced reading, displaying, saving, resizing, cropping, rotating, and flipping images.
These foundational concepts are essential for all future OpenCV topics. In the next module, you will move beyond basic image operations and begin exploring advanced image processing techniques such as filtering, blurring, edge detection, thresholding, contour detection, and feature extraction. These skills will enable you to build practical computer vision applications and prepare you for more advanced topics such as object detection, face recognition, and deep learning.