Image Processing Using Python: Understanding Images, Pixels, Arrays & OpenCV
A beginner-friendly guide to how computers represent images and how Python can process them.
Images are an important source of information. From face detection and medical scans to self-driving cars and social media filters, computers use image processing to understand and modify visual information. In this blog, we will learn how digital images are stored, how pixels and colour channels work, how NumPy represents images as arrays, and how to perform basic image-processing tasks using OpenCV.
1. Objectives of This Blog
- Understand how digital images are represented inside a computer.
- Learn about pixels, image dimensions, pixel values and colour channels.
- Understand how NumPy arrays are used to store image data.
- Explore the OpenCV library and its commonly used functions.
- Build a simple image-processing project using Python and OpenCV
2. What Is a Digital Image?
A digital image is a visual representation stored in a computer in a numerical format. Unlike a printed photograph, a digital image is made up of many tiny elements arranged in rows and columns. These elements are called pixels.
Each pixel stores one or more numerical values that describe its brightness or colour. When millions of pixels are displayed together, they form the complete image that we see on a screen.
Common image file formats include JPEG/JPG, PNG, BMP and TIFF. Different formats use different methods to store image information. For example, JPEG usually uses lossy compression, while PNG supports lossless compression.
3. Understanding Pixels
A pixel (picture element) is the smallest individual unit of a digital image. Every pixel contains a value that represents its colour or intensity.
Pixel values
- Grayscale image: A pixel usually has a value from 0 to 255. A value of 0 represents black, 255 represents white, and values in between represent shades of gray.
- Colour image: A pixel commonly contains three values, one for each colour channel. In an 8-bit-per-channel image, each value ranges from 0 to 255.
Image dimensions
Image dimensions describe the number of pixels across the width and height. For example, an image with dimensions 640 × 480 contains 640 columns and 480 rows, or 307,200 pixels. A larger image can contain more visual detail, but it also generally requires more memory to store and process.
4. Images as NumPy Arrays
Python’s NumPy library provides efficient arrays for storing and working with numerical data. Since images are made of pixel values, they can be represented as NumPy arrays.
- A grayscale image is usually a 2D array:
(height, width). - A three-channel colour image is usually a 3D array:
(height, width, 3).
Each position in the array represents a pixel. For a colour image, the final dimension stores the channel values for that pixel.
import numpy as np
# A tiny 2 x 2 grayscale image
image = np.array([
[0, 100],
[150, 255]
])
print(image)
print("Shape:", image.shape)
print("Pixel at row 0, column 1:", image[0, 1])Output:
[[ 0 100]
[150 255]]
Shape: (2, 2)
Pixel at row 0, column 1: 1005. Understanding Colour Channels
A colour channel stores information about one component of a colour image. The most common colour model used for digital displays is RGB, which stands for Red, Green and Blue.
RGB channels
In the RGB model, each pixel has three values: red, green and blue. Different combinations of these values produce different colours. For example, (255, 0, 0) is red, (0, 255, 0) is green, and (0, 0, 255) is blue.
Grayscale images
A grayscale image contains shades from black to white and usually stores one intensity value per pixel instead of three colour values. Grayscale images are useful when colour is not important for a task, such as some edge-detection and shape-analysis operations.
Important: RGB vs BGR in OpenCV
Although RGB is a common colour model, OpenCV reads standard colour images in BGR order by default: Blue, Green and Red. This is important when displaying an OpenCV image using a library that expects RGB, such as Matplotlib. Convert the image from BGR to RGB when needed.
6. Introduction to OpenCV
OpenCV (Open Source Computer Vision Library) is an open-source library used for image processing and computer vision. It provides functions to read, display, edit and analyse images and videos.
Get Samasanjana’s stories in your inbox
Join Medium for free to get updates from this writer.
OpenCV is commonly used in applications such as face detection, object tracking, medical image analysis, quality inspection, document scanning and robotics. Python makes many OpenCV operations accessible through simple function calls.
Installing the required libraries
pip install opencv-python numpy matplotlibimport cv2
import numpy as np
import matplotlib.pyplot as plt7. Basic OpenCV Functions
The following functions are useful starting points when learning image processing with OpenCV.
Example 1: Read and inspect an image
import cv2
img = cv2.imread("photo.jpg")
if img is None:
print("Image not found. Check the file path.")
else:
print("Image dimensions:", img.shape)The imread() function returns an image array. If the file cannot be read, it returns None. Checking for None helps prevent errors in later operations.
Example 2: Convert a colour image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)This converts the three-channel BGR image into a single-channel grayscale image.
Example 3: Resize an image
resized = cv2.resize(img, (300, 200))Example 4: Blur an image
blurred = cv2.GaussianBlur(img, (5, 5), 0)Example 5: Detect edges
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 100, 200)8. Mini Project: Basic Image Processing Using OpenCV
Now let us combine the concepts and functions to create a simple project. The project reads an image, checks that it was loaded, displays its dimensions, converts it to grayscale, resizes it, applies blur, detects edges and saves the processed results.
Project objective
To understand how an input image can be transformed into different useful outputs using basic OpenCV functions.
Step-by-step process
- Choose an image: Keep an image such as
photo.jpgin the same folder as the Python program, or provide its full file path. - Import libraries: Import OpenCV and NumPy.
- Load the image: Use
cv2.imread()and check whether loading succeeded. - Inspect the image: Read its shape to understand its dimensions and channels.
- Process the image: Convert it to grayscale, resize it, blur it and detect its edges.
- Save the outputs: Use
cv2.imwrite()to save the processed images. - View the results: Display the original and processed images.
Complete Python code
import cv2
import numpy as np
# Step 1: Read the input image
img = cv2.imread("photo.jpg")
# Step 2: Check whether the image was loaded
if img is None:
print("Error: Image not found. Check the file path.")
else:
# Step 3: Display image information
print("Original image shape:", img.shape)
# Step 4: Convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Step 5: Resize the original image
resized = cv2.resize(img, (300, 200))
# Step 6: Apply Gaussian blur
blurred = cv2.GaussianBlur(img, (5, 5), 0)
# Step 7: Detect edges from grayscale image
edges = cv2.Canny(gray, 100, 200)
# Step 8: Save processed images
cv2.imwrite("grayscale.jpg", gray)
cv2.imwrite("resized.jpg", resized)
cv2.imwrite("blurred.jpg", blurred)
cv2.imwrite("edges.jpg", edges)
# Step 9: Display the results
cv2.imshow("Original Image", img)
cv2.imshow("Grayscale Image", gray)
cv2.imshow("Resized Image", resized)
cv2.imshow("Blurred Image", blurred)
cv2.imshow("Edge Detection", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
print("Image processing completed successfully.")Displaying images in Jupyter Notebook or Google Colab
import matplotlib.pyplot as plt
import cv2
# OpenCV uses BGR; Matplotlib expects RGB
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.title("Original Image")
plt.axis("off")
plt.show()Expected project outputs
9. Real-World Applications of Image Processing
- Healthcare: Supporting the analysis of X-rays, CT scans and MRI images.
- Security: Face detection and video surveillance systems.
- Transportation: Lane detection, traffic monitoring and driver-assistance systems.
- Agriculture: Analysing plant images to identify disease symptoms.
- Retail and manufacturing: Product inspection, barcode reading and defect detection.
- Mobile applications: Photo filters, document scanning and image enhancement.
10. Conclusion
Image processing helps computers work with visual information. In this blog, we explored how digital images are made of pixels, how pixel values represent brightness and colour, and how images are stored as NumPy arrays. We also learned about RGB, grayscale and OpenCV’s BGR channel order.
Using OpenCV, we practised important functions such as imread(), cvtColor(), resize(), GaussianBlur(), Canny() and imwrite(). Finally, we combined these functions in a basic image-processing project. These fundamentals provide a useful starting point for learning more advanced computer vision techniques.
Learning image processing step by step makes it easier to understand how computers interpret images and how these techniques are used in real-world applications.






