Skip to main content

Lesson 2 of 12

Convolution Explained

Convolution is the mathematical operation at the heart of CNNs. Understanding it conceptually — even without the full maths — is essential for using CNNs effectively.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

What is Convolution?

Convolution is the operation of sliding a small filter (kernel) across an image and computing a weighted sum at each position.

For each position:
1. The filter is placed on a region of the image
2. Each filter value is multiplied by the corresponding pixel value
3. All products are summed to produce one output value
4. The filter slides to the next position

The result is a feature map — an image that highlights where in the original image the filter's pattern was found.

Different filters detect different features:
- A vertical edge filter detects vertical edges
- A horizontal edge filter detects horizontal edges
- A circular pattern filter detects circles

In CNNs, the filter values are not hand-crafted — they are learned during training to detect the features most useful for the task.

Diagram
Loading diagram…

Machine Learning follows a structured pipeline from data to deployment

Manual Convolution in Python

Manual Convolution in Python
import cv2
import numpy as np

image = cv2.imread("photo.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY).astype(np.float32)

# HAND-CRAFTED FILTERS (the kind CNNs learn automatically)

# Vertical edge detector
vertical_filter = np.array([
    [-1, 0, 1],
    [-2, 0, 2],
    [-1, 0, 1]
], dtype=np.float32)

# Horizontal edge detector
horizontal_filter = np.array([
    [-1, -2, -1],
    [ 0,  0,  0],
    [ 1,  2,  1]
], dtype=np.float32)

# Sharpening filter
sharpen_filter = np.array([
    [ 0, -1,  0],
    [-1,  5, -1],
    [ 0, -1,  0]
], dtype=np.float32)

# Apply filters using cv2.filter2D (same math as convolution)
vertical_edges   = cv2.filter2D(gray, -1, vertical_filter)
horizontal_edges = cv2.filter2D(gray, -1, horizontal_filter)
sharpened        = cv2.filter2D(gray, -1, sharpen_filter)

# Combine vertical and horizontal edges (like Sobel)
edge_magnitude = np.sqrt(vertical_edges**2 + horizontal_edges**2)
edge_magnitude = np.clip(edge_magnitude, 0, 255).astype(np.uint8)

cv2.imwrite("vertical_edges.jpg", np.abs(vertical_edges).astype(np.uint8))
cv2.imwrite("combined_edges.jpg", edge_magnitude)
print("Convolution examples saved")
print("These are the kind of filters CNNs learn automatically during training")

Topics in This Module

0/12 done