Image Processing Using Python: From Pixels to Computer Vision with OpenCV
Introduction
Have you ever wondered how a computer understands an image?
When we look at a photograph, we see people, objects, colors, and shapes. But a computer doesn’t see an image the way we do. For a computer, an image is simply a collection of numbers.
These numbers represent pixels, colors, and brightness levels. By processing these numbers, computers can detect objects, recognize faces, identify edges, and much more.
This is where Image Processing comes in.
In this article, we’ll explore image processing using Python and OpenCV. We’ll start with the basics of images and pixels, understand how images are represented as NumPy arrays, and gradually learn essential OpenCV functions.
By the end, we’ll build a small project that reads an image, analyzes it, detects edges, and saves the processed results.
Let’s get started!
1. What Is an Image?
An image is a visual representation of something captured using a camera, created digitally, or generated by a computer.
For example, when we look at a photograph of a cat, we can easily recognize the cat, its colors, and its surroundings.
But computers don’t understand images in the same way humans do.
To a computer, an image is a collection of numerical values arranged in rows and columns. These values represent the information stored in the image.
Let’s understand this with a simple comparison.
What we see: We recognize objects, colors, and patterns in an image.
What the computer sees: It processes numerical values that represent the image.
This is the basic idea behind digital image processing. Instead of understanding an image visually, computers work with its numerical representation.
Important: Every digital image is made up of tiny elements called pixels. Let’s understand what they are.
2. What Is a Pixel?
A pixel (Picture Element) is the smallest individual unit of a digital image.
Think of an image as a large grid made up of tiny squares. Each square represents one pixel.
When thousands or millions of these pixels come together, they form the complete image we see.
For example:
• A 100 × 100 image contains 10,000 pixels.
• A 500 × 500 image contains 250,000 pixels.
• A 1920 × 1080 image contains 2,073,600 pixels.
Each pixel stores information about the image, such as its brightness or color.
In a grayscale image, a pixel typically contains a value between 0 and 255.
• 0 represents black.
• 255 represents white.
• Values between 0 and 255 represent different shades of gray.
Let’s visualize how an image looks when we zoom into its pixels.
As you can see, when we zoom into a small region of an image, individual pixels become visible.
Why are pixels important?
Almost every image processing operation works with pixels. Changing brightness, resizing an image, converting colors, and detecting edges all involve manipulating pixel values.
3. Color Channels: Grayscale, RGB and BGR
Now that we understand pixels, let’s look at how computers represent colors.
A grayscale image stores only brightness information, while a color image generally uses three channels to represent colors.
Let’s understand the difference.
3.1 Grayscale Images
A grayscale image contains different shades of gray, ranging from black to white.
Each pixel stores a single intensity value between 0 and 255.
• 0 = Black
• 255 = White
• 127 = Medium gray
Because grayscale images contain only one channel, they are simpler to process and are often used for edge detection and other computer vision operations.
3.2 RGB Color Model
A color image commonly uses three channels:
• Red (R)
• Green (G)
• Blue (B)
Each channel stores an intensity value between 0 and 255.
By combining different intensities of these three colors, we can represent millions of colors.
For example:
• Red: (255, 0, 0)
• Green: (0, 255, 0)
• Blue: (0, 0, 255)
• White: (255, 255, 255)
• Black: (0, 0, 0)
3.3 RGB vs BGR in OpenCV
Here is something important to remember when working with OpenCV.
Although RGB is a commonly used color representation, OpenCV uses BGR (Blue, Green, Red) by default when reading color images.
This means the channel order is different.
ColorRGBBGRRed(255, 0, 0)(0, 0, 255)Green(0, 255, 0)(0, 255, 0)Blue(0, 0, 255)(255, 0, 0)
For example, if we want to represent pure red:
• RGB: (255, 0, 0)
• BGR: (0, 0, 255)
This difference becomes important when displaying images using libraries such as Matplotlib or working with color values in OpenCV.
Important: Always remember that OpenCV uses BGR order, not RGB, by default. We will see how to convert between these formats in the upcoming sections.
4. Images as NumPy Arrays
Now we know that images are made up of pixels and color channels. But how does Python actually store and manipulate this information?
Python uses NumPy arrays to represent image data.
When we read an image using OpenCV, it is returned as a NumPy array. This allows us to access individual pixels, change colors, crop regions, and perform mathematical operations on images.
Let’s understand this step by step.
4.1 Understanding Image Shape
An image array generally has three dimensions:
• Height — Number of rows (pixels).
• Width — Number of columns (pixels).
• Channels — Number of color channels.
For example, an image with a height of 400 pixels, a width of 600 pixels, and 3 color channels has the following shape:
(400, 600, 3)Here, 3 represents the Blue, Green, and Red channels used by OpenCV.
4.2 Understanding Data Type (dtype)
The dtype property tells us what type of numerical values are stored in the image array.
Most standard OpenCV color images use uint8 (unsigned 8-bit integers).
This means each channel can store values between 0 and 255.
print(img.dtype)# Output:
# uint84.3 Accessing Pixel Values
We can access an individual pixel using its row and column position.
pixel = img[100, 200]print(pixel)This accesses the pixel at row 100 and column 200.
For a color image, the output contains three values in BGR order.
4.4 Slicing and Cropping Images
NumPy slicing allows us to select a specific region of an image.
The general syntax is:
cropped = img[start_y:end_y, start_x:end_x]For example:
cropped = img[50:200, 100:300]This extracts a region:
• Rows 50 to 199.
• Columns 100 to 299.
The selected region becomes a new image.
4.5 Changing Image Brightness Using NumPy
We can also increase or decrease image brightness by performing mathematical operations on pixel values.
For example:
import numpy as npbrighter = np.clip(img + 50, 0, 255)Here:
• img + 50 increases the pixel values.
• np.clip() keeps all values within the range 0 to 255.
Adding values makes the image brighter, while subtracting values makes it darker.
Important: NumPy makes image manipulation simple because images are stored as arrays of numerical values.
5. What Is OpenCV?
OpenCV (Open Source Computer Vision Library) is an open-source library used for image processing and computer vision.
It provides ready-to-use functions that help developers work with images and videos without implementing every operation from scratch.
Using OpenCV, we can perform tasks such as:
• Reading and saving images.
• Resizing and cropping images.
• Converting images between color spaces.
• Blurring and sharpening images.
• Detecting edges and contours.
• Face and object detection.
Why is OpenCV popular?
• It provides a large collection of image processing functions.
• It works efficiently with NumPy arrays.
• It supports Python, C++, and other programming languages.
• It is widely used in computer vision applications.
Installing OpenCV
Before using OpenCV, we need to install it.
Open your terminal or command prompt and run:
pip install opencv-pythonWe can also install NumPy and Matplotlib:
pip install numpy matplotlibImporting OpenCV
After installation, we can import OpenCV into our Python program using cv2.
import cv2print(cv2.__version__)The cv2 module provides access to OpenCV functions.
If the installation is successful, the code displays the installed OpenCV version.
6. Setting Up: Required Libraries
Before exploring OpenCV functions, let’s understand the three libraries we will use throughout this article.
1. OpenCV (cv2)
Used for reading, displaying, modifying, and saving images.
import cv22. NumPy (numpy)
Used for working with image arrays, accessing pixels, slicing images, and performing mathematical operations.
import numpy as np3. Matplotlib (matplotlib.pyplot)
Used for displaying images, comparing results, and creating visualizations.
import matplotlib.pyplot as pltComplete Imports
We can import all three libraries together:
import cv2
import numpy as np
import matplotlib.pyplot as pltDisplaying Images: Scripts vs Notebooks
There are different ways to display images in Python, depending on where we run our code.
Using OpenCV:
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()This opens a separate window to display the image. It is commonly used when running Python scripts on a desktop.
Using Matplotlib:
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.show()This displays the image directly inside a Jupyter Notebook or similar interactive environment.
Notice that we convert BGR to RGB before displaying the image with Matplotlib. This is because OpenCV uses BGR order by default, whereas Matplotlib expects RGB.
Important: Throughout this article, we will use Matplotlib for visualizing images and comparing processing results, especially in Jupyter Notebook.
7. Essential OpenCV Functions
Now that we understand images, pixels, NumPy arrays, and OpenCV, let’s explore some commonly used OpenCV functions.
These functions will help us read, display, modify, and analyze images.
For the examples below, we’ll assume that an image named photo.jpg is available in the current working directory.
7.1 Reading an Image
The first step in image processing is loading an image into Python.
OpenCV provides the cv2.imread() function to read images from a file.
Syntax:
cv2.imread(filename, flags)• filename – Path of the image to read.
• flags – Specifies how the image should be loaded.
Common flags:
• cv2.IMREAD_COLOR – Loads the image in color (default).
• cv2.IMREAD_GRAYSCALE – Loads the image in grayscale.
• cv2.IMREAD_UNCHANGED – Loads the image without changing its original channels, including alpha if present.
Example:
import cv2img = cv2.imread("photo.jpg")if img is None:
print("Image not found!")
else:
print("Image loaded successfully!")
Output:
Image loaded successfully!If the image path is incorrect or the file cannot be read, cv2.imread() returns None.
Always check whether the image was loaded successfully before performing further operations.
7.2 Displaying an Image
After reading an image, we may want to display it.
OpenCV provides cv2.imshow() to display an image in a separate window.
Syntax:
cv2.imshow(window_name, image)• window_name – Title of the display window.
• image – Image that needs to be displayed.
Example:
img = cv2.imread("photo.jpg")if img is not None:
cv2.imshow("My Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()Here are two additional functions used with cv2.imshow().
1. cv2.waitKey()
Syntax:
cv2.waitKey(delay)• delay – Time in milliseconds to wait for a keyboard event. A value of 0 waits indefinitely until a key is pressed.
2. cv2.destroyAllWindows()
Syntax:
cv2.destroyAllWindows()Closes all windows created by OpenCV.
Displaying Images Using Matplotlib
We can also display images using Matplotlib, especially inside Jupyter Notebook.
However, OpenCV reads color images in BGR format, while Matplotlib expects RGB.
So, we need to convert the image before displaying it.
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)plt.imshow(img_rgb)
plt.axis("off")
plt.show()This displays the image with the correct colors.
7.3 Saving an Image
After processing an image, we may want to save the result.
OpenCV provides cv2.imwrite() to save an image to a file.
Syntax:
cv2.imwrite(filename, image)• filename – Name or path of the output image.
• image – Image that needs to be saved.
Example:
img = cv2.imread("photo.jpg")if img is not None:
cv2.imwrite("output.jpg", img)This saves the image as output.jpg in the current working directory.
The function returns True if the image is saved successfully and False otherwise.
7.4 Understanding Image Properties
Before processing an image, it is useful to understand its properties.
NumPy provides several attributes that help us inspect image data.
Let’s look at three commonly used properties.
1. Shape
Syntax:
img.shapeReturns the dimensions of the image.
For a color image, the output contains:
(height, width, channels)Example:
print(img.shape)# Output:
# (400, 600, 3)This means the image has:
• Height: 400 pixels.
• Width: 600 pixels.
• Channels: 3 (BGR).
2. Size
Syntax:
img.sizeReturns the total number of elements in the image array.
print(img.size)# Output:
# 720000For a 400 × 600 color image:
400 × 600 × 3 = 720,000 elements.
3. Data Type (dtype)
Syntax:
img.dtypeReturns the data type of the image array.
print(img.dtype)# Output:
# uint8Most standard OpenCV images use uint8, which stores values between 0 and 255.
7.5 Converting Color Spaces
Sometimes, we need to change an image from one color format to another.
For example, converting a color image into grayscale is useful for edge detection and other image processing operations.
OpenCV provides the cv2.cvtColor() function for converting between color spaces.
Syntax:
cv2.cvtColor(image, conversion_code)• image – Input image.
• conversion_code – Specifies the required color conversion.
1. BGR to Grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)This converts a three-channel BGR image into a single-channel grayscale image.
2. BGR to RGB
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)This changes the channel order from BGR to RGB.
It is especially useful when displaying OpenCV images using Matplotlib.
Important: OpenCV uses BGR by default. Always check the expected color format when working with different libraries.
7.6 Resizing an Image
Sometimes, an image is too large for processing or displaying.
We can change its dimensions using cv2.resize().
Syntax:
cv2.resize(image, dsize, interpolation)• image – Input image.
• dsize – Desired output size in (width, height) format.
• interpolation – Method used to calculate pixel values during resizing.
Common interpolation methods:
• cv2.INTER_LINEAR – Commonly used for enlarging images.
• cv2.INTER_AREA – Recommended for reducing image size.
• cv2.INTER_CUBIC – Provides smoother results when enlarging images.
Example:
resized = cv2.resize(img, (300, 200))This resizes the image to:
• Width: 300 pixels.
• Height: 200 pixels.
Keeping the Aspect Ratio
If we resize an image without considering its aspect ratio, it may look stretched or distorted.
To avoid this, calculate the height based on the original dimensions.
height, width = img.shape[:2]new_width = 300
new_height = int(height * new_width / width)resized = cv2.resize(img, (new_width, new_height))
This changes the width while maintaining the original aspect ratio.
7.7 Cropping an Image
Cropping means selecting a specific region from an image and removing the unwanted parts.
Get Hemanthkumarchintakuntla’s stories in your inbox
Join Medium for free to get updates from this writer.
We can perform cropping directly using NumPy slicing. We don’t need a separate OpenCV cropping function.
Syntax:
cropped = img[start_y:end_y, start_x:end_x]• start_y – Starting row.
• end_y – Ending row (excluded).
• start_x – Starting column.
• end_x – Ending column (excluded).
Example:
cropped = img[50:200, 100:300]plt.imshow(cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.show()This extracts a region from the original image.
The cropped image is also a NumPy array.
7.8 Rotating and Flipping Images
OpenCV provides functions to rotate and flip images easily.
1. Rotating an Image
We can use cv2.rotate() to rotate an image in different directions.
Syntax:
cv2.rotate(image, rotateCode)• image – Input image.
• rotateCode – Specifies the rotation direction.
Common rotation codes:
• cv2.ROTATE_90_CLOCKWISE – Rotates 90 degrees clockwise.
• cv2.ROTATE_180 – Rotates 180 degrees.
• cv2.ROTATE_90_COUNTERCLOCKWISE – Rotates 90 degrees counterclockwise.
Example:
rotated = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)2. Flipping an Image
We can use cv2.flip() to flip an image horizontally or vertically.
Syntax:
cv2.flip(image, flipCode)• image – Input image.
• flipCode – Specifies the flipping direction.
Common values:
• 1 – Horizontal flip.
• 0 – Vertical flip.
• -1 – Both horizontal and vertical flip.
Example:
flipped = cv2.flip(img, 1)This creates a horizontally flipped image.
7.9 Blurring an Image
Sometimes, images contain unwanted details or noise that make processing difficult.
Blurring helps reduce noise and smooth the image.
One commonly used technique is Gaussian Blur.
OpenCV provides the cv2.GaussianBlur() function.
Syntax:
cv2.GaussianBlur(image, ksize, sigmaX)• image – Input image.
• ksize – Kernel size, specified as (width, height). Both values must be positive odd numbers.
• sigmaX – Standard deviation in the X direction. A value of 0 allows OpenCV to calculate it automatically from the kernel size.
Example:
blurred = cv2.GaussianBlur(img, (5, 5), 0)Here, (5, 5) represents a 5 × 5 kernel.
A kernel is a small matrix that moves across the image and helps calculate new pixel values using neighboring pixels.
A larger kernel generally produces a stronger blur.
Gaussian Blur is commonly applied before edge detection to reduce unwanted noise.
7.10 Edge Detection
Edges are boundaries where the intensity or color of an image changes significantly.
For example, the boundary between an object and its background is an edge.
Edge detection helps identify these boundaries and is widely used in computer vision.
OpenCV provides the cv2.Canny() function for detecting edges.
Syntax:
cv2.Canny(image, threshold1, threshold2)• image – Input image, usually converted to grayscale.
• threshold1 – Lower threshold.
• threshold2 – Upper threshold.
Example:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)edges = cv2.Canny(gray, 100, 200)Here, we use 100 as the lower threshold and 200 as the upper threshold.
How do the thresholds work?
Canny edge detection uses two thresholds to classify possible edges.
• Weak edges below the lower threshold are discarded.
• Strong edges above the upper threshold are kept.
• Edges between the two thresholds are considered weak candidates and are kept only when connected to strong edges.
The output is generally a binary image where detected edges appear white and the background appears black.
7.11 Drawing Functions
OpenCV also allows us to draw shapes and add text directly to images.
These functions are useful for highlighting objects, marking regions, and adding annotations.
1. Drawing a Line
We can use cv2.line() to draw a line between two points.
Syntax:
cv2.line(image, pt1, pt2, color, thickness)• image – Input image.
• pt1 – Starting point (x, y).
• pt2 – Ending point (x, y).
• color – Line color in BGR format.
• thickness – Line thickness in pixels.
Example:
cv2.line(img, (50, 50), (300, 50), (0, 255, 0), 3)This draws a green line with a thickness of 3 pixels.
2. Drawing a Rectangle
We can use cv2.rectangle() to highlight a particular region.
Syntax:
cv2.rectangle(image, pt1, pt2, color, thickness)• image – Input image.
• pt1 – Top-left corner.
• pt2 – Bottom-right corner.
• color – Rectangle color in BGR format.
• thickness – Border thickness in pixels.
Example:
cv2.rectangle(img, (50, 50), (300, 200), (0, 255, 0), 3)This draws a green rectangle around the selected region.
3. Drawing a Circle
We can use cv2.circle() to draw a circle.
Syntax:
cv2.circle(image, center, radius, color, thickness)• image – Input image.
• center – Center coordinates (x, y).
• radius – Radius of the circle in pixels.
• color – Circle color in BGR format.
• thickness – Border thickness. Use -1 to fill the circle.
Example:
cv2.circle(img, (200, 150), 50, (255, 0, 0), -1)This draws a filled blue circle.
4. Adding Text
We can use cv2.putText() to add text to an image.
Syntax:
cv2.putText(image, text, org, fontFace, fontScale, color, thickness)• image – Input image.
• text – Text to display.
• org – Bottom-left starting position (x, y).
• fontFace – Font type.
• fontScale – Font size.
• color – Text color in BGR format.
• thickness – Text thickness.
Example:
cv2.putText(
img,
"Hello OpenCV",
(50, 50),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(0, 255, 0),
2
)This adds green text to the image.
Important: OpenCV drawing functions use BGR color order, not RGB.
7.12 Thresholding
Thresholding is a technique used to convert a grayscale image into a binary image.
A binary image contains only two pixel values:
• 0 — Black.
• 255 — White.
The idea is simple: compare each pixel with a threshold value and decide whether it should become black or white.
Let’s first understand thresholding using NumPy.
Using NumPy:
import numpy as npm = np.array([50, 100, 150, 200, 250])binary = np.where(m > 127, 255, 0)print(binary)# Output:
# [ 0 0 255 255 255]
Here:
• Values greater than 127 become 255 (white).
• Values less than or equal to 127 become 0 (black).
Using OpenCV:
OpenCV provides the cv2.threshold() function to perform thresholding on images.
Syntax:
cv2.threshold(src, thresh, maxval, type)• src – Input grayscale image.
• thresh – Threshold value.
• maxval – Maximum value assigned to pixels that satisfy the threshold condition.
• type – Thresholding method.
Example:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)_, binary = cv2.threshold(
gray,
127,
255,
cv2.THRESH_BINARY
)Here:
• 127 is the threshold value.
• 255 is the maximum output value.
• cv2.THRESH_BINARY converts pixels greater than 127 to white and the remaining pixels to black.
The resulting image contains only black and white pixels.
Thresholding is commonly used for document processing, object separation, and image segmentation.
What We Learned
In this section, we explored some of the most commonly used OpenCV functions:
• Reading, displaying, and saving images.
• Understanding image properties.
• Converting color spaces.
• Resizing, cropping, rotating, and flipping images.
• Applying Gaussian Blur and Canny edge detection.
• Drawing shapes and adding text.
• Converting grayscale images into binary images using thresholding.
Now that we understand these functions, let’s combine them to build a small image processing project.
8. Building a Basic Image Processing Project: Image Analyzer and Edge Detector
Now that we have learned the essential OpenCV functions, let’s combine them to build a small practical project.
In this project, we’ll create an Image Analyzer and Edge Detector using Python, OpenCV, NumPy, and Matplotlib.
Our program will take an input image, analyze its properties, resize it, convert it into grayscale, reduce noise, detect edges, and save the processed images.
Project Workflow
We’ll follow these eight steps:
- Load the image.
- Inspect image properties.
- Resize the image while maintaining its aspect ratio.
- Convert the image to grayscale.
- Apply Gaussian Blur to reduce noise.
- Detect edges using Canny Edge Detection.
- Annotate the original image with a rectangle and text.
- Display and save the processed images.
Let’s implement each step separately before combining everything into one Python script.
Step 1: Load the Image
First, we’ll load an image named photo.jpg using cv2.imread().
We’ll also check whether the image exists and raise a FileNotFoundError if it cannot be loaded.
import cv2img = cv2.imread("photo.jpg")if img is None:
raise FileNotFoundError("Could not find photo.jpg")print("Image loaded successfully!")
Step 2: Inspect Image Properties
Next, we’ll check the image dimensions, total number of elements, and data type.
print("Image Shape:", img.shape)
print("Image Size:", img.size)
print("Image Data Type:", img.dtype)This helps us understand the image before processing it.
Step 3: Resize the Image
We’ll resize the image to a width of 600 pixels while maintaining its original aspect ratio.
height, width = img.shape[:2]new_width = 600
new_height = int(height * new_width / width)resized = cv2.resize(img, (new_width, new_height))
This prevents the image from becoming stretched or distorted.
Step 4: Convert to Grayscale
Now, we’ll convert the resized color image into grayscale.
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)The resulting image contains only one intensity channel instead of three color channels.
Step 5: Apply Gaussian Blur
Before detecting edges, we’ll apply Gaussian Blur to reduce unwanted noise.
blurred = cv2.GaussianBlur(gray, (5, 5), 0)The (5, 5) kernel helps smooth the image by considering neighboring pixels.
Step 6: Detect Edges
Now, we’ll use Canny Edge Detection to identify the boundaries in the image.
edges = cv2.Canny(blurred, 100, 200)Here:
• 100 is the lower threshold.
• 200 is the upper threshold.
The output highlights the detected edges in white against a black background.
Step 7: Annotate the Original Image
Next, we’ll draw a green rectangle and add the text “Image Analyzer” to the original resized image.
We’ll create a copy so that the original resized image remains unchanged.
annotated = resized.copy()cv2.rectangle(
annotated,
(20, 20),
(new_width - 20, new_height - 20),
(0, 255, 0),
3
)cv2.putText(
annotated,
"Image Analyzer",
(30, 55),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(0, 255, 0),
2
)
Remember that OpenCV uses BGR color order. The color (0, 255, 0) represents green.
Step 8: Display and Save the Results
Finally, we’ll save the grayscale image, detected edges, and annotated image.
cv2.imwrite("gray.png", gray)
cv2.imwrite("edges.png", edges)
cv2.imwrite("annotated.png", annotated)We’ll use Matplotlib to display the original, grayscale, and edge-detected images side by side.
import matplotlib.pyplot as pltplt.figure(figsize=(15, 5))plt.subplot(1, 3, 1)
plt.imshow(cv2.cvtColor(resized, cv2.COLOR_BGR2RGB))
plt.title("Original")
plt.axis("off")plt.subplot(1, 3, 2)
plt.imshow(gray, cmap="gray")
plt.title("Grayscale")
plt.axis("off")plt.subplot(1, 3, 3)
plt.imshow(edges, cmap="gray")
plt.title("Edges")
plt.axis("off")plt.tight_layout()
plt.show()
Notice that we convert the original image from BGR to RGB before displaying it with Matplotlib.
Complete Python Script
Now let’s combine all the steps into one complete Python program.
Required libraries:
pip install opencv-python numpy matplotlibComplete Code:
import cv2
import numpy as np
import matplotlib.pyplot as plt# Step 1: Load Image
img = cv2.imread("photo.jpg")if img is None:
raise FileNotFoundError("Could not find photo.jpg")print("Image loaded successfully!")# Step 2: Inspect Properties
print("Image Shape:", img.shape)
print("Image Size:", img.size)
print("Image Data Type:", img.dtype)# Step 3: Resize Image
height, width = img.shape[:2]new_width = 600
new_height = int(height * new_width / width)resized = cv2.resize(img, (new_width, new_height))# Step 4: Convert to Grayscale
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)# Step 5: Apply Gaussian Blur
blurred = cv2.GaussianBlur(gray, (5, 5), 0)# Step 6: Detect Edges
edges = cv2.Canny(blurred, 100, 200)# Step 7: Annotate Original Image
annotated = resized.copy()cv2.rectangle(
annotated,
(20, 20),
(new_width - 20, new_height - 20),
(0, 255, 0),
3
)cv2.putText(
annotated,
"Image Analyzer",
(30, 55),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(0, 255, 0),
2
)# Step 8: Save Processed Images
cv2.imwrite("gray.png", gray)
cv2.imwrite("edges.png", edges)
cv2.imwrite("annotated.png", annotated)print("Processed images saved successfully!")# Display Results
plt.figure(figsize=(15, 5))plt.subplot(1, 3, 1)
plt.imshow(cv2.cvtColor(resized, cv2.COLOR_BGR2RGB))
plt.title("Original")
plt.axis("off")plt.subplot(1, 3, 2)
plt.imshow(gray, cmap="gray")
plt.title("Grayscale")
plt.axis("off")plt.subplot(1, 3, 3)
plt.imshow(edges, cmap="gray")
plt.title("Edges")
plt.axis("off")plt.tight_layout()
plt.show()
Expected Output
After running the program, you’ll see three images displayed side by side:
• Original: The resized input image.
• Grayscale: The image converted into shades of gray.
• Edges: The boundaries and important details detected using Canny Edge Detection.
The program also generates three output files:
File NameDescriptiongray.pngGrayscale version of the imageedges.pngEdge-detected imageannotated.pngOriginal resized image with rectangle and text
What did we achieve?
We successfully built a basic image processing pipeline using Python and OpenCV.
We started with a single image and performed multiple operations, combining the functions we learned throughout this article.
This is a simple example of how individual image processing techniques can work together in a practical computer vision application.
9. Conclusion
We’ve reached the end of our introduction to image processing using Python and OpenCV!
Throughout this article, we explored how computers represent images using pixels and numerical values. We also learned how images are stored as NumPy arrays and how OpenCV helps us manipulate and analyze them.
We covered several essential operations, including reading, displaying, resizing, cropping, rotating, blurring, edge detection, drawing, and thresholding.
Finally, we combined these concepts to build a basic Image Analyzer and Edge Detector project.
But this is just the beginning of computer vision!
What to Learn Next
If you want to explore image processing further, here are some topics worth learning:
• Adaptive Thresholding and Otsu’s Method: Techniques for converting images into binary images using automatically calculated thresholds.
• Contour Detection: Finding and identifying the boundaries of objects in an image.
• Morphological Operations: Techniques such as erosion, dilation, opening, and closing for processing image shapes.
• Face Detection with Haar Cascades: Detecting human faces using pre-trained classifiers.
• Image Classification with Deep Learning: Training neural networks to recognize and classify objects in images.
Each of these topics will help you move one step closer to understanding real-world computer vision applications.
Final Thoughts
The best way to learn image processing is by experimenting with different images and trying out the techniques yourself.
Start with simple operations, understand how pixel values change, and gradually move towards more advanced computer vision projects.
I hope this article helped you understand the fundamentals of image processing using Python and OpenCV.
If you found this article useful, share your thoughts in the comments, give it a clap, and follow for more Python, Machine Learning, and AI-related content.
Happy Learning! 🚀
Connect with Me
I’m learning and building projects in Machine Learning, Python, Data Science, and AI. Follow my journey and explore my work!
- LinkedIn: linkedin.com/Hemanth-kumar-ch
- GitHub: github.com/Hemanth-kumar-ch
- Medium: hemanthkumarchintakuntla
- Feel free to connect, explore my projects, and share your feedback!






