Sitemap

Understanding Images and Image Processing Using Python and OpenCV

7 min read20 hours ago

--

Images

What is an image?

Generally, an image is a visual representation of something that we can see, such as a photograph, drawing, picture, or diagram.

In OpenCV, a digital image is represented as a collection of pixels arranged in rows and columns.

Types of Images

There are different types of digital images:

  1. Grayscale Images: Images containing different shades of black, white, and gray.
  2. Color Images: Images containing multiple colors, generally represented using RGB channels.
  3. Binary Images: Images containing only two pixel values, usually black and white.
  4. Vector Images: Images created using mathematical shapes, lines, and paths rather than individual pixels. Unlike raster images, they can be resized without losing quality.

Importance of Images

Images play an important role in different fields:

  • Education: Help students understand concepts visually.
  • Healthcare: Used in medical imaging, such as X-rays and MRI scans.
  • Business: Used in advertisements and product presentations.
  • Technology: Used in facial recognition and object detection.
  • Social Media: Help people share experiences and communicate.

What is Pixel?

A pixel (Picture Element) is the smallest individual unit of a digital image.

An image is made up of thousands or millions of tiny squares called pixels. Each pixel contains numerical information that represents its color and brightness.

Pixel Values

For a standard 8-bit image:

  • 0 represents black.
  • 255 represents white.
  • Values between 0 and 255 represent different shades of gray.

For a color image, each pixel generally contains three values representing its color channels.

For example, in RGB:

  • (255, 0, 0) represents red.
  • (0, 255, 0) represents green.
  • (0, 0, 255) represents blue.
  • (0, 0, 0) represents black.
  • (255, 255, 255) represents white.

Image Dimensions

Image dimensions describe the height and width of an image.

For example, an image with dimensions 800 × 600 has:

  • Width = 800 pixels
  • Height = 600 pixels

The total number of pixels is:

Total Pixels = Width × Height

Therefore, 800 × 600 = 480,000 pixels.

Images as Arrays and the Role of NumPy

In Python, images are commonly represented as arrays using the NumPy library.

NumPy stands for Numerical Python. It is a Python library used to perform mathematical and numerical operations on arrays.

When an image is loaded using OpenCV, it is generally stored as a NumPy array.

How Images Are Represented as Arrays

Grayscale Image:

A grayscale image is represented as a two-dimensional array.

Each element represents the intensity value of a pixel.

Example:

import numpy as np

gray_image = np.array([
[0, 100, 150],
[50, 200, 255],
[30, 120, 180]
])

print(gray_image)

Color Image:

A color image is represented as a three-dimensional array containing:

  • Height
  • Width
  • Color channels

For example, (400, 600, 3) represents an image with 400 rows, 600 columns, and 3 color channels.

Reading an Image as a NumPy Array

import cv2
import numpy as np

img = cv2.imread("image.jpg")

print(type(img))
print(img.shape)
print(img.size)
print(img.dtype)

Explanation:

  • type(img) – Displays the data type of the image.
  • img.shape – Returns the image dimensions and channels.
  • img.size – Returns the total number of array elements.
  • img.dtype – Returns the data type of pixel values, commonly uint8.

Note: OpenCV reads color images in BGR format by default instead of RGB.

Accessing Pixel Values

pixel = img[100, 150]
print(pixel)

This accesses the pixel at row 100 and column 150.

Channels

A channel represents one component of an image’s color information.

RGB (Red, Green, Blue)

RGB is a color model that combines three primary colors:

  • Red
  • Green
  • Blue

Different combinations of these colors produce different colors in an image.

BGR (Blue, Green, Red)

OpenCV uses BGR as its default channel order when reading color images.

The channel order is:

  • Blue
  • Green
  • Red

Grayscale

A grayscale image contains only one channel. It represents brightness or intensity instead of separate color information.

Its pixel values generally range from 0 to 255.

Converting BGR to RGB

rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

Converting BGR to Grayscale

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Splitting Image Channels

OpenCV provides cv2.split() to separate the individual channels of a color image.

b, g, r = cv2.split(img)
cv2.imshow("Blue Channel", b)
cv2.imshow("Green Channel", g)
cv2.imshow("Red Channel", r)
cv2.waitKey(0)

How Do Computers Process Images?

Computers use a technique called Image Processing to analyze and modify images.

Python is one of the popular programming languages used for this purpose. It provides a powerful library called OpenCV (cv2).

OpenCV allows us to perform various operations, such as:

  • Reading and displaying images.
  • Resizing and cropping photographs.
  • Converting color images into grayscale.
  • Detecting edges and objects.
  • Applying filters and removing noise.
  • Drawing shapes and adding text to images.

For example, converting a color image into grayscale using OpenCV is simple:

import cv2
# imread --> Read the image
# OpenCV reads every pixel from the image and converts it into numpy array
img = cv2.imread("image.jpg")

# OpenCV by default reads the image in BGR Format
# cvtColor Convert one color space into another
color_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)


cv2.imshow("Color Image", color_img)
# image will be displayed till we close the window by pressing any key on keyboard
cv2.waitKey(0)
# closes all opened windows
cv2.destroyAllWindows()

Introduction to OpenCV Library

OpenCV stands for Open Source Computer Vision Library.

It is an open-source library used for image processing and computer vision applications.

Get Deepti Gupta’s stories in your inbox

Join Medium for free to get updates from this writer.

In Python, OpenCV is imported using the cv2 module.

Installing OpenCV

pip install opencv-python

Importing OpenCV

import cv2

Importance of OpenCV

OpenCV provides functions to:

  • Read and display images.
  • Resize and crop images.
  • Convert images into different color spaces.
  • Perform basic image processing.
  • Detect edges and object boundaries.
  • Save processed images.

Applications of OpenCV

  1. Face detection and recognition.
  2. Object detection.
  3. Medical image processing.
  4. Security and surveillance.
  5. Image enhancement.
  6. Self-driving cars.

Various operations using OpenCV

1. Reading and Displaying Images

imread( )

imread() is a function in the OpenCV library used to read or load an image from a specified file location.

It reads the image and converts it into a NumPy array so that Python can process it.

import cv2

img = cv2.imread("image.jpg")

cv2.imshow() – Displaying an image

The imshow() function is used to display an image in a separate window.

cv2.imshow("Nature", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2.waitKey() – Wait for keyboard input

Waits for a keyboard event for a specified number of milliseconds.

cv2.waitKey(0)
  • 0 means wait indefinitely until a key is pressed.
  • 1000 means wait for 1 second.

cv2.destroyAllWindows() – Close windows

Closes all windows created by OpenCV.

cv2.destroyAllWindows()

cv2.imwrite() – Save an image

Saves an image to a specified file path.

cv2.imwrite("output.jpg", img)

2. Resizing and cropping photographs.

cv2.resize() – Resize an image

Changes the height and width of an image.

resized = cv2.resize(img, (300, 300))

cv2.rotate() – Rotate an image

Rotates an image by 90, 180, or 270 degrees.

rotated = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)

cv2.flip() – Flip an image

Creates a mirror image by flipping the image horizontally or vertically.

horizontal = cv2.flip(img, 1)
vertical = cv2.flip(img, 0)
  • 1 = Horizontal flip
  • 0 = Vertical flip
  • -1 = Both horizontal and vertical flip

Cropping an image

Cropping is used to extract a particular portion of an image.

OpenCV uses NumPy slicing for cropping.

cropped = img[50:300, 100:400]

cv2.imshow("Cropped", cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here:

  • 50:300 = Rows (height)
  • 100:400 = Columns (width)

3. Color conversion functions

cv2.cvtColor() – Convert image color

Converts an image from one color space to another.

Example: BGR to grayscale

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

4. Detecting edges and objects

cv2.Canny() – Canny edge detection

Detects edges by identifying sudden changes in pixel intensity.

edge = cv2.Canny(resized_image, 200,200)

5. Applying filters and removing noise

Filters help improve image quality by smoothing images and reducing unwanted noise.

cv2.blur() – Average blur

Reduces noise by calculating the average value of neighboring pixels.

blurred = cv2.blur(resized_image, ksize = (20,20))

6. Image Thresholding

Threshold → Converts an image into black and white

image = cv2.imread("image.jpg", 0)

resized = cv2.resize(image, (300, 300))

_,thresh = cv2.threshold(
resized, 127, 255, cv2.THRESH_BINARY
)

cv2.imshow("Threshold Image", thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

7. Drawing functions

OpenCV also allows us to draw shapes and text on images.

First, create a blank black image:

import numpy as np

black = np.zeros((400, 400, 3), dtype=np.uint8)

cv2.line() – Draw a line

# Syntax
# cv2.line(image, satrt_point, end_point, color, thickness)
cv2.line(black, (50,50),(300,300),(0,55,0),5)

cv2.rectangle() – Draw a rectangle

cv2.rectangle(black, (100,100),(300,250),(255,0,0),3)

cv2.circle() – Draw a circle

# cv2.circle(image, centre, radius, color, thickness)
cv2.circle(img, (150, 150), 50, (0, 0, 255), 3)

cv2.putText() – Add text to an image

cv2.putText(img, "OpenCV", (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1,
(255, 255, 255), 2)

Project Building Process — Basic Image Processing Using OpenCV

Project Title: Basic Image Processing Using OpenCV

Objective:

To load an image and perform basic image processing operations such as resizing and grayscale conversion using Python and OpenCV.

Step 1: Import Required Libraries

import cv2
import numpy as np

OpenCV is used for image processing, while NumPy supports array operations.

Step 2: Read the Image

img = cv2.imread("image.jpg")
if img is None:
print("Image not found")
else:
print("Image loaded successfully")

This loads the image from the specified location.

Step 3: Understand Image Properties

print("Image Shape:", img.shape)
print("Image Size:", img.size)
print("Image Data Type:", img.dtype)

This helps us understand the dimensions, number of channels, and pixel data type.

Step 4: Resize the Image

resized = cv2.resize(img, (300, 300))

This changes the image dimensions to 300 × 300 pixels.

Step 5: Convert the Image into Grayscale

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

This converts the original color image into a single-channel grayscale image.

Step 6: Display the Images

cv2.imshow("Original Image", img)
cv2.imshow("Resized Image", resized)
cv2.imshow("Grayscale Image", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

This displays the original image and the processed results.

Step 7: Save the Processed Image

cv2.imwrite("processed_image.jpg", gray)

This saves the grayscale image to the current working directory.

Expected Project Output

After completing the project, we obtain:

  1. Original Image — The image loaded from the computer.
  2. Resized Image — The image with changed dimensions.
  3. Grayscale Image — The image converted into one intensity channel.

Project Workflow

Image Input → Image Loading → Understanding Properties → Resizing → Grayscale Conversion → Display → Save Results

Conclusion

Images are more than just pictures. They are collections of pixels containing valuable visual information.

With Python and OpenCV, we can read, modify, process, and analyze images using different techniques.

Learning these basic OpenCV functions provides a foundation for exploring advanced topics such as Computer Vision, Object Detection, Image Recognition, and Artificial Intelligence.

Remember: Every image has a story, and image processing helps computers understand the information hidden inside it!

--

--