LearnItWeb

Convolutional Neural Networks (CNNs): Understanding Convolution Operations from Scratch

1. Introduction

Convolutional Neural Networks (CNNs) are a special type of neural network designed primarily for processing visual data, such as images and videos.

They are widely used in computer vision applications, including:

  • Image classification
  • Face recognition
  • Object detection
  • Medical image analysis
  • Handwriting recognition
  • Autonomous driving

What makes CNNs particularly effective at understanding images is their ability to automatically identify visual patterns. Instead of treating an image as an ordinary collection of numbers, CNNs learn to recognize meaningful visual features such as edges, corners, textures, shapes, and eventually complex objects.

To understand how CNNs achieve this, we need to understand one fundamental operation: convolution.

Convolution is the mechanism through which CNNs extract features from images. It allows a network to identify patterns at different levels of complexity and gradually build a meaningful representation of the input image.

In this tutorial, we will explore convolution from the ground up. We will understand how images are represented in computer memory, how filters detect edges, how convolution produces feature maps, and how CNNs work with grayscale and RGB images. We will also examine how multiple filters produce multiple feature maps and how the dimensions of these feature maps are calculated.

2. Understanding the Architecture of a CNN

Before exploring convolution mathematically, let’s first understand the overall idea behind a Convolutional Neural Network.

A CNN is a neural network with a specialized architecture that includes three important types of layers:

  1. Convolutional layers
  2. Pooling layers
  3. Fully connected layers

Each layer has a different responsibility.

  • Convolutional layers extract features from images.
  • Pooling layers reduce the spatial dimensions of feature maps.
  • Fully connected layers use the extracted features to perform tasks such as classification.

A simplified CNN architecture looks like this:

The convolutional and pooling layers are often repeated several times before the network reaches its fully connected layers.

2.1 How CNNs learn visual features

The working principle of CNNs is inspired by how the human visual system processes visual information. When we look at an image, we do not immediately identify every object by examining the entire image as a single entity. Our visual system processes different visual patterns and combines them to recognize more complex structures.

CNNs follow a somewhat similar approach. Consider a photograph of a person’s face. At the beginning of the network, convolutional layers may identify simple visual patterns such as:

  • Horizontal edges
  • Vertical edges
  • Diagonal edges
  • Basic intensity changes

As we move deeper into the network, these simple features are combined into more complex patterns. For example:

The important idea is that CNNs progressively learn more complex representations. Early layers generally learn low-level features, while deeper layers learn higher-level features by combining information from earlier layers. This is why convolutional layers are so important to CNNs.

3. Understanding How Images Are Represented

To understand convolution, we first need to understand how a computer represents an image. An image is made up of small individual elements called pixels. Each pixel represents the intensity or color information at a particular location in the image. For computational purposes, an image can be represented as a matrix or a multidimensional array of numbers.

There are two common types of images that we need to understand:

  1. Grayscale images
  2. RGB images

3.1 Grayscale images

A grayscale image contains different shades of gray, ranging from black to white. Each pixel represents an intensity value. In a conventional 8-bit grayscale image, pixel values range from 0 to 255.

Pixel valueRepresentation
0Black
64Dark gray
128Medium gray
192Light gray
255White

A grayscale image can therefore be represented as a two-dimensional matrix.

Consider the following simplified example:

Grayscale Image

+-----+-----+-----+-----+-----+
|  0  |  0  |  0  |  0  |  0  |
+-----+-----+-----+-----+-----+
|  0  | 50  | 80  | 50  |  0  |
+-----+-----+-----+-----+-----+
|  0  | 80  | 150 | 80  |  0  |
+-----+-----+-----+-----+-----+
|  0  | 50  | 80  | 50  |  0  |
+-----+-----+-----+-----+-----+
|  0  |  0  |  0  |  0  |  0  |
+-----+-----+-----+-----+-----+

The numbers represent the intensity of individual pixels. A value of 0 represents black, while a value of 255 represents white. Values between these two extremes represent different shades of gray. A grayscale image of dimensions 28 × 28 contains:

28×28=784 pixels 28 \times 28 = 784 \text{ pixels}

Each pixel contributes one numerical value. Therefore, the complete image can be represented using a two-dimensional array containing 784 values. This is how datasets such as MNIST represent handwritten digits. For example, a handwritten digit can be represented as a 28 × 28 matrix, where the pixel values describe the shape of the digit. In practice, pixel values are sometimes normalized from the range 0–255 to the range 0–1.

The normalization formula is:

xnormalized=x255x_{\text{normalized}} = \frac{x}{255}

For example:

255255=1 \frac{255}{255}=1
128255≈0.502\frac{128}{255}\approx 0.502
0255=0 \frac{0}{255}=0

Normalization makes numerical values easier to work with during neural network training.

3.2 RGB images

Grayscale images contain only one intensity value per pixel. Color images require additional information. Most commonly used digital color images use the RGB color model.

RGB stands for:

  • Red
  • Green
  • Blue

An RGB image consists of three separate color channels. Each channel represents the intensity of one primary color. We can visualize an RGB image as three overlapping image planes. Each channel is essentially a grayscale image containing intensity values for its respective color. For an 8-bit RGB image, each channel contains values between 0 and 255. The three channels are combined to produce the final color image. For example:

An RGB image with dimensions 228 × 228 has the following shape:

228×228×3 228 \times 228 \times 3

The first dimension represents height, the second represents width, and the third represents the number of color channels. Therefore, an RGB image contains:

228×228×3228 \times 228 \times 3

individual numerical values. The distinction between grayscale and RGB images is important because convolution filters must account for the number of input channels.

4. What Is Feature Extraction?

Before understanding convolution, we need to understand what we mean by feature extraction. A feature is a meaningful visual pattern that can help a neural network understand an image.

Consider a photograph of a car. Some of the important features in that image might include:

  • Horizontal and vertical edges
  • Circular shapes representing wheels
  • Windows
  • Headlights
  • The overall shape of the vehicle

A CNN does not initially know what a car looks like. It must learn useful visual patterns from the training data. One of the simplest and most fundamental visual patterns is an edge.

4.1 What is an edge?

An edge is a region in an image where the intensity values change significantly between neighboring pixels. Consider a simple image containing a black region followed by a white region.

On the left side, pixel intensities are low. On the right side, they are high. The transition between these two regions represents an edge. Edges are important because they help identify the boundaries and shapes of objects. For example, the outline of a face, the boundary of a window, and the edges of a vehicle all contain changes in pixel intensity. Therefore, detecting edges is one of the fundamental operations involved in image processing.

4.2 Types of edges

Depending on the direction of intensity change, we can identify different types of edges.

  • Horizontal edges: These occur when pixel intensity changes vertically as we move from one row to another.
  • Vertical edges: These occur when pixel intensity changes horizontally as we move from one column to another.
  • Diagonal edges: These occur when the intensity changes along a diagonal direction. Different filters can be designed to detect these different patterns.

5. Understanding Filters and Kernels

A convolution filter is a small matrix of numerical values that is applied to an image to extract a particular feature. Filters are also commonly called kernels.

A filter typically has a small spatial dimension, such as:

  • 3 × 3
  • 5 × 5
  • 7 × 7

For example, consider the following 3 × 3 filter:

K=[−1−1−1000111] K = \begin{bmatrix} -1 & -1 & -1 \\ 0 & 0 & 0 \\ 1 & 1 & 1 \end{bmatrix}

This filter is designed to detect horizontal edges. Let’s understand why.

The first row contains negative values, the middle row contains zeros, and the last row contains positive values.

When this filter is applied to an image:

  • The top row of the image region is multiplied by negative weights.
  • The middle row contributes nothing because its weights are zero.
  • The bottom row is multiplied by positive weights.

If the image intensity changes significantly between the top and bottom regions, the filter produces a large response. This indicates the presence of a horizontal edge.

The important point is that a filter is a mathematical pattern used to identify a particular pattern in an image. Other filters can be used to detect vertical edges, diagonal edges, or other visual structures. However, in modern CNNs, we generally do not need to manually design all these filters. The network learns their values during training.

6. What Is the Convolution Operation?

Convolution is the operation through which a filter is applied to an image to extract visual features.

The basic idea is simple:

  1. Take a small filter.
  2. Place it over a corresponding region of the image.
  3. Multiply each image value by its corresponding filter value.
  4. Add all the multiplication results.
  5. Store the result in the output feature map.
  6. Move the filter to the next position and repeat.

The resulting matrix is called a feature map. Let’s understand this operation using a small numerical example.

6.1 Creating a sample input image

Consider a grayscale image of size 6 × 6. Suppose the upper three rows are black and the lower three rows are white. The image can be represented as:

I=[000000000000000000255255255255255255255255255255255255255255255255255255]I = \begin{bmatrix} 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 255 & 255 & 255 & 255 & 255 & 255 \\ 255 & 255 & 255 & 255 & 255 & 255 \\ 255 & 255 & 255 & 255 & 255 & 255 \end{bmatrix}

The upper region contains black pixels, while the lower region contains white pixels. There is a horizontal edge between the third and fourth rows. Our objective is to identify this edge using a convolution filter.

6.2 Applying the filter

We will use the following 3 × 3 filter:

K=[−1−1−1000111]K = \begin{bmatrix} -1 & -1 & -1 \\ 0 & 0 & 0 \\ 1 & 1 & 1 \end{bmatrix}

We will apply this filter to the 6 × 6 image. Initially, we place the filter over the top-left corner of the image.

Input Image (6 × 6)

+-----+-----+-----+-----+-----+-----+
|  0  |  0  |  0  |  0  |  0  |  0  |
+-----+-----+-----+-----+-----+-----+
|  0  |  0  |  0  |  0  |  0  |  0  |
+-----+-----+-----+-----+-----+-----+
|  0  |  0  |  0  |  0  |  0  |  0  |
+-----+-----+-----+-----+-----+-----+
| 255 | 255 | 255 | 255 | 255 | 255 |
+-----+-----+-----+-----+-----+-----+
| 255 | 255 | 255 | 255 | 255 | 255 |
+-----+-----+-----+-----+-----+-----+
| 255 | 255 | 255 | 255 | 255 | 255 |
+-----+-----+-----+-----+-----+-----+

Filter (3 × 3)

+-----+-----+-----+
| -1  | -1  | -1  |
+-----+-----+-----+
|  0  |  0  |  0  |
+-----+-----+-----+
|  1  |  1  |  1  |
+-----+-----+-----+

At the first position, the filter overlaps the following region of the input image:

[000000000]\begin{bmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix}

Now we perform element-wise multiplication between the image region and the filter.

R=(0×−1)+(0×−1)+(0×−1)+(0×0)+(0×0)+(0×0)+(0×1)+(0×1)+(0×1)\begin{aligned} R &= (0 \times -1) + (0 \times -1) + (0 \times -1) \\ &\quad + (0 \times 0) + (0 \times 0) + (0 \times 0) \\ &\quad + (0 \times 1) + (0 \times 1) + (0 \times 1) \end{aligned}

Therefore:

R=0R = 0

The first output value is 0.

6.3 Moving the filter

After calculating the first value, we move the filter one position to the right. The filter now overlaps another 3 × 3 region. Since the image contains the same pixel values across each row, the result is still 0. We continue moving the filter horizontally until we reach the rightmost valid position. Once we finish the first row, we move the filter down by one row and repeat the same process.

The movement looks like this:

The filter moves across the image, calculating one output value at every valid position. This sliding operation is the fundamental mechanism behind convolution in CNNs.

6.4 Calculating the output values

Let’s examine the first few vertical positions. At the first position, all three rows contain zeros:

R1=0R_1 = 0

At the second vertical position, the filter overlaps two black rows and one white row:

[000000255255255]\begin{bmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 255 & 255 & 255 \end{bmatrix}

The calculation becomes:

R2=(0×−1)+(0×−1)+(0×−1)+(0×0)+(0×0)+(0×0)+(255×1)+(255×1)+(255×1) R_2 = (0 \times -1) + (0 \times -1) + (0 \times -1) + (0 \times 0) + (0 \times 0) + (0 \times 0) + (255 \times 1) + (255 \times 1) + (255 \times 1)

Therefore:

R2=765 R_2 = 765

At the next vertical position, the filter overlaps one black row and two white rows.

The result is also:

R3=765R_3 = 765

Finally, when the filter reaches the bottom, all three rows contain white pixels.

The negative and positive contributions cancel each other:

R4=(−255−255−255)+(255+255+255)R_4 = (-255-255-255) + (255+255+255)
R4=0 R_4 = 0

Since the image has identical values across all columns, the same calculations occur at every horizontal position.

The resulting feature map is:

F=[00007657657657657657657657650000] F = \begin{bmatrix} 0 & 0 & 0 & 0 \\ 765 & 765 & 765 & 765 \\ 765 & 765 & 765 & 765 \\ 0 & 0 & 0 & 0 \end{bmatrix}

This output is called a feature map.

Notice that the middle rows contain large positive values. These values indicate that the filter has detected the horizontal transition between the black and white regions. The upper and lower regions produce zero because there is no intensity transition within those regions. This example demonstrates how convolution can extract a specific visual feature from an image.

An important implementation detail: Deep learning libraries commonly use cross-correlation rather than mathematically flipped convolution when applying CNN kernels. The sliding, element-wise multiplication, and summation procedure shown here describes the operation used by typical CNN implementations.

7. Understanding Feature Maps

A feature map is the output generated when a filter is applied to an input image. It represents the locations and strengths of the visual pattern detected by that filter. In our previous example, the filter was designed to detect horizontal edges. The resulting feature map contains high values around the horizontal boundary.

The feature map does not simply represent a smaller version of the original image. Instead, it represents the response of the filter at different spatial locations. A large positive value indicates a strong positive response from the filter. A value near zero indicates little response. A large negative value indicates a strong response in the opposite direction.

7.1 Positive and negative activations

Different filter responses can be visualized using different colors.

For example, a feature visualization might use:

  • Red to represent positive activations.
  • Blue to represent negative activations.
  • Neutral colors to represent values near zero.

These colors are only a visualization convention. The actual feature map contains numerical values. Suppose a filter detects a particular edge orientation. If the image contains that edge in the expected direction, the filter produces a positive response. If the edge occurs in the opposite direction, the response may be negative. This distinction can be useful because the sign and magnitude of the output contain information about the detected pattern.

7.2 Applying ReLU to the feature map

In CNN architectures, convolution is frequently followed by an activation function. One commonly used activation function is ReLU (Rectified Linear Unit). It is defined as:

ReLU⁡(x)=max⁡(0,x) \operatorname{ReLU}(x) = \max(0,x)

In simple terms:

  • Positive values remain unchanged.
  • Negative values become zero.

For example:

ReLU⁡(−5)=0 \operatorname{ReLU}(-5)=0
ReLU⁡(10)=10 \operatorname{ReLU}(10)=10

Consider this feature map:

F=[−503−27−1] F = \begin{bmatrix} -5 & 0 & 3 \\ -2 & 7 & -1 \end{bmatrix}

After applying ReLU:

F′=[003070] F’ = \begin{bmatrix} 0 & 0 & 3 \\ 0 & 7 & 0 \end{bmatrix}

This removes negative activations while retaining positive responses. The combination of convolution and activation functions helps CNNs learn useful nonlinear representations.

8. Do We Need to Manually Design Filters?

At this point, you might wonder how we know which values should be placed inside a filter. For example, we manually created this horizontal edge detection filter:

K=[−1−1−1000111]K = \begin{bmatrix} -1 & -1 & -1 \\ 0 & 0 & 0 \\ 1 & 1 & 1 \end{bmatrix}

These filters are useful for demonstrating the mathematics of edge detection. However, modern CNNs generally do not require us to manually define the filter values. CNNs learn the filter values automatically during training. This is one of the most important properties of deep learning.

8.1 Filters contain learnable parameters

A 3 × 3 filter contains nine numerical values. These values are trainable parameters of the neural network. Initially, the filter values are usually initialized using a suitable weight initialization method. During training, the network makes predictions and calculates a loss. Backpropagation computes gradients that indicate how the filter weights should change to reduce that loss. An optimizer then updates the weights.

Over multiple training iterations, the filter values gradually adjust to become useful for the learning task.

For example, a network trained for image classification might learn filters that respond to edges, textures, corners, and other useful visual patterns. The network determines which filters are useful based on the training data and the objective it is trying to optimize. This means that we do not need to tell the CNN explicitly that a particular filter should detect horizontal edges or vertical edges. We define the architecture, initialize its parameters, and allow the training process to learn suitable filter values.

9. Calculating the Output Size of a Convolution

One important aspect of convolution is that the output feature map is generally smaller than the input image when we use a filter without padding. Let’s understand why.

Suppose we have:

  • Input image: 6 × 6
  • Filter: 3 × 3

The filter must fit entirely inside the image. Initially, it can be placed at the top-left corner. It can then move horizontally and vertically, but it cannot move beyond the image boundaries.

For a 6 × 6 image and a 3 × 3 filter:

  • There are four valid horizontal positions.
  • There are four valid vertical positions.

Therefore, the output feature map has dimensions:

4×44 \times 4

We can visualize this as:

Input Image       Filter         Output

  6 × 6            3 × 3          4 × 4

+---------+      +-----+        +-------+
|         |      |     |        |       |
|         |  *   |     |   =    |       |
|         |      |     |        |       |
|         |      +-----+        +-------+
|         |
|         |
+---------+

9.1 General output size formula

Suppose the input image has dimensions:

n×n n \times n

And the filter has dimensions:

m×m m \times m

Assuming:

  • Stride = 1
  • Padding = 0

The output feature map will have dimensions:

(n−m+1)×(n−m+1) (n-m+1)\times(n-m+1)

10. Using Multiple Filters in a CNN

In practical CNN architectures, we generally do not use just one filter. Instead, a convolutional layer contains multiple filters.

Why?

Because an image contains many different types of visual patterns. One filter might learn to detect horizontal edges, another might learn to detect vertical edges, and another might learn to detect textures or other patterns. Each filter extracts a different feature.

Let’s consider an RGB image with dimensions:

6×6×36\times6\times3

Suppose we apply two filters:

K1=3×3×3 K_1 = 3\times3\times3
K2=3×3×3K_2 = 3\times3\times3

The first filter produces one feature map. The second filter produces another feature map. Since both filters operate on the same input image, their outputs have the same spatial dimensions. The resulting output has two channels. The reason is simple: each filter produces one feature map.

Therefore:

Number of output channels=Number of filters \text{Number of output channels} = \text{Number of filters}

If we use 10 filters, the output will contain 10 feature maps. If we use 32 filters, the output will contain 32 feature maps.

10.1 Understanding the output volume

Imagine stacking all the feature maps on top of one another. For example, if we have four filters, each feature map contains the response of one filter. Together, they form the output volume that becomes the input to the next layer.

This is how CNNs build progressively richer feature representations.

11. Understanding the Number of Learnable Parameters

Now that we understand multiple filters, we can calculate how many parameters a convolutional layer contains.

Suppose we have:

  • Input channels = 3
  • Filter size = 3 × 3
  • Number of filters = 10

Each filter contains:

3×3×3=273\times3\times3=27

weights.

Since there are ten filters:

27×10=27027\times10=270

If each filter also has one bias term, the total number of learnable parameters is:

270+10=280 270+10=280

Therefore:

Parameters=(F×F×C+1)×K \boxed{ \text{Parameters} = (F\times F\times C+1)\times K }

Where:

  • F = Filter height and width (assuming square filters)
  • C = Number of input channels
  • K = Number of filters
  • 1 = One bias per filter

This parameter count does not depend on the input image’s height and width. For example, the same convolutional layer can process images of different spatial sizes while using the same filter parameters, provided the other architectural constraints are satisfied. This property is one of the reasons CNNs are parameter-efficient compared with fully connected networks operating directly on large images.

12. Putting Everything Together

Let’s summarize the complete convolution process using an RGB image. Suppose we have an RGB image of dimensions:

228×228×3 228\times228\times3

We apply a convolutional layer with:

  • Filter size: 3 × 3
  • Number of filters: 32
  • Stride: 1
  • Padding: 0

Each filter has dimensions:

3×3×3 3\times3\times3

Since the filter covers all three input channels, every filter produces one two-dimensional feature map.

The output height is:

228−3+1=226 228-3+1=226

The output width is:

228−3+1=226 228-3+1=226

The output depth is equal to the number of filters:

32 32

Therefore, the output shape is:

226×226×32 \boxed{226\times226\times32}

Each filter extracts a different pattern from the image. The output volume contains all these extracted features and provides a richer representation of the original image. A subsequent convolutional layer can use this representation to identify more complex patterns.

This process continues as the network becomes deeper.