English NewsTuesday, 24 November 2026
Latest
AI technology

Convolutional Neural Networks (CNN): A Complete Guide from Basics to Deployment

What is a convolutional neural network?

A convolutional neural network (CNN) is a deep learning architecture designed mainly for processing structured, grid-like data such as images, video and spatial signals.

Typical architecture of a CNN (illustrative diagram).
Typical architecture of a CNN (illustrative diagram).

Core architecture and layers

  • Convolutional layer: applies learnable filters (kernels) that slide across the input to extract local spatial features such as edges, textures and shapes, using element-wise multiplications.
  • Activation layer (ReLU): adds non-linearity by turning negative values into zero and keeping positive values unchanged, which lets the network learn complex patterns.
  • Pooling layer: downsamples the feature map, commonly with max pooling, to reduce spatial dimensions, lower computation and build translation invariance.
  • Flatten layer: converts multi-dimensional feature maps into a 1D vector so they can feed traditional layers.
  • Fully connected (dense) layer: combines the extracted features to do high-level reasoning and outputs the final classification probabilities through a softmax function.

Key design principles

  • Parameter sharing: the same kernel weights are reused at different positions in the input, which cuts the number of trainable parameters drastically compared with a standard neural network.
  • Local connectivity: each neuron processes only a small local patch, its receptive field, so it captures close-range spatial correlations.
  • Hierarchical learning: early layers detect low-level details such as edges and colour gradients, while deeper layers assemble them into complex semantic objects such as faces, text or medical anomalies.

An interactive tool called CNN Explainer gives a visual breakdown of how data flows through these layers. How a CNN is built depends heavily on your type of data and on the coding framework you prefer, so the next two sections cover both.

Applications: how your data shapes the network

Different real-world problems need different convolution dimensions and output layers.

  • Image classification: uses 2D convolutions (Conv2D) that scan height and width across the colour channels to give one label to a whole image, for example a cat or a dog.
  • Medical imaging: often uses 3D convolutions (Conv3D) for volumetric scans such as MRI or CT, together with specialised encoder-decoder architectures like U-Net that outline the exact pixel boundaries of tumours or organs.
  • Time-series and audio data: uses 1D convolutions (Conv1D) that slide along a single time axis to spot local trends in stock prices, sensor readings or audio waveforms.

Choosing a framework: PyTorch or TensorFlow

Both frameworks are industry standards, but they give different workflows when you start writing code.

FeaturePyTorchTensorFlow (with Keras)
Coding stylePythonic and object-oriented; gives explicit, line-by-line control over the training loop.High-level and declarative; lets you stack layers quickly with minimal boilerplate code.
Best forAcademic research, custom layer architectures and intuitive step-by-step debugging.Rapid prototyping, enterprise production pipelines and mobile or edge deployment (TFLite).
Core CNN syntaxtorch.nn.Conv2d(...)tf.keras.layers.Conv2D(...)

A basic CNN, in PyTorch and in TensorFlow

1. Basic CNN in PyTorch

PyTorch uses an object-oriented approach: you define your layers inside __init__ and describe how data flows through them in forward.

import torch
import torch.nn as nn
import torch.nn.functional as F

class BasicCNN(nn.Module):
    def __init__(self, num_classes=10):
        super(BasicCNN, self).__init__()
        # Input: 3 color channels (RGB), Output: 16 feature maps, 3x3 kernel
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1)
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
        self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1)
        # Assuming input image is 32x32, after two 2x2 pools it becomes 8x8
        self.fc1 = nn.Linear(32 * 8 * 8, 128)
        self.fc2 = nn.Linear(128, num_classes)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))  # Output: [batch, 16, 16, 16]
        x = self.pool(F.relu(self.conv2(x)))  # Output: [batch, 32, 8, 8]
        x = x.view(-1, 32 * 8 * 8)            # Flatten into 1D vector
        x = F.relu(self.fc1(x))
        x = self.fc2(x)                       # Raw logits (Softmax applied in loss)
        return x

# Example usage with a dummy batch of 4 RGB images (32x32)
model = BasicCNN(num_classes=10)
dummy_input = torch.randn(4, 3, 32, 32)
output = model(dummy_input)
print("PyTorch Output Shape:", output.shape)  # Expected: [4, 10]

2. Basic CNN in TensorFlow (Keras)

TensorFlow's Keras API lets you stack layers sequentially with minimal boilerplate, and it infers the input shapes between layers automatically.

import tensorflow as tf
from tensorflow.keras import layers, models

def build_basic_cnn(input_shape=(32, 32, 3), num_classes=10):
    model = models.Sequential([
        # First Convolutional Block
        layers.Conv2D(16, (3, 3), padding='same', activation='relu', input_shape=input_shape),
        layers.MaxPooling2D((2, 2)),
        # Second Convolutional Block
        layers.Conv2D(32, (3, 3), padding='same', activation='relu'),
        layers.MaxPooling2D((2, 2)),
        # Classification Head
        layers.Flatten(),
        layers.Dense(128, activation='relu'),
        layers.Dense(num_classes, activation='softmax')
    ])
    return model

# Example usage
model = build_basic_cnn()
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()

Specialised CNN architectures: ResNet and U-Net

Basic CNNs stack layers one after another, but complex real-world tasks need special structural patterns to overcome training bottlenecks and to keep spatial detail.

ResNet (Residual Network)

  • Core innovation: skip connections (residual blocks) that add the original input of a block straight to its output, F(x) + x.
  • Problem solved: the vanishing gradient problem in very deep networks of 50, 101 or 152+ layers, where early layers stop learning because the error signal shrinks to zero during backpropagation.
  • Best for: deep image classification, object detection backbones and transfer learning tasks that need rich, high-level visual features.

U-Net

  • Core innovation: a symmetric encoder-decoder shaped like the letter “U”, joined by skip connections across the network that copy high-resolution feature maps from the encoder straight to the decoder.
  • Problem solved: standard CNNs lose exact pixel locations during pooling. U-Net restores full spatial resolution so the model knows where an object is, not just what it is.
  • Best for: semantic segmentation (labelling every pixel of an image), medical imaging such as finding tumours or cell boundaries, and diffusion models for image generation.

Training loops

Training a neural network means feeding batches of data through the model, calculating how wrong the predictions are (the loss), and updating the model's weights to reduce that error.

PyTorch training loop

PyTorch makes you write out the forward pass, zero the gradients, run backpropagation and step the optimizer yourself.

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

# 1. Create dummy dataset (100 RGB images of size 32x32, 10 classes)
X_train = torch.randn(100, 3, 32, 32)
y_train = torch.randint(0, 10, (100,))
train_loader = DataLoader(TensorDataset(X_train, y_train), batch_size=16, shuffle=True)

# 2. Initialize model, loss function, and optimizer (using BasicCNN from earlier)
model = BasicCNN(num_classes=10)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# 3. Run the training loop
epochs = 5
model.train()  # Set model to training mode
for epoch in range(epochs):
    running_loss = 0.0
    for inputs, labels in train_loader:
        optimizer.zero_grad()              # Clear old gradients
        outputs = model(inputs)            # Forward pass
        loss = criterion(outputs, labels)  # Calculate loss
        loss.backward()                    # Backward pass (compute gradients)
        optimizer.step()                   # Update weights
        running_loss += loss.item()
    print(f"Epoch {epoch+1}/{epochs} - Loss: {running_loss/len(train_loader):.4f}")

TensorFlow (Keras) training loop

TensorFlow wraps the training steps inside a single .fit() method once you have compiled the model.

import numpy as np
import tensorflow as tf

# 1. Create dummy dataset (100 RGB images of size 32x32, 10 classes)
X_train = np.random.randn(100, 32, 32, 3).astype(np.float32)
y_train = np.random.randint(0, 10, size=(100,))

# 2. Build and compile the model (using build_basic_cnn from earlier)
model = build_basic_cnn(input_shape=(32, 32, 3), num_classes=10)
model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

# 3. Train the model
history = model.fit(
    X_train, y_train,
    batch_size=16,
    epochs=5,
    validation_split=0.2  # Automatically hold out 20% for validation
)

Transfer learning with a pretrained ResNet

Transfer learning takes a model already trained on millions of images, such as on the ImageNet dataset, and adapts it to your own dataset. You freeze the early convolutional layers so they keep their edge-and-shape detection skills, and replace only the final classification layer.

Pretrained ResNet-50 in PyTorch

With torchvision.models you load the pretrained weights, freeze all parameters and overwrite the final fully connected layer (model.fc).

import torch.nn as nn
import torchvision.models as models

# 1. Load ResNet-50 with default ImageNet weights
weights = models.ResNet50_Weights.DEFAULT
model = models.resnet50(weights=weights)

# 2. Freeze all existing convolutional layers
for param in model.parameters():
    param.requires_grad = False

# 3. Replace the final classification head for your custom number of classes
num_custom_classes = 5
in_features = model.fc.in_features
model.fc = nn.Linear(in_features, num_custom_classes)

# Only model.fc parameters will be updated during training
optimizer = torch.optim.Adam(model.fc.parameters(), lr=0.001)

Pretrained ResNet-50 in TensorFlow (Keras)

With tf.keras.applications you load the base model without its top classification layer (include_top=False), freeze it and attach your own pooling and dense layers.

import tensorflow as tf
from tensorflow.keras import layers, models

# 1. Load ResNet-50 base without the original 1000-class ImageNet head
base_model = tf.keras.applications.ResNet50(
    weights='imagenet',
    include_top=False,
    input_shape=(224, 224, 3)
)

# 2. Freeze the base model weights
base_model.trainable = False

# 3. Attach a new classification head for your custom classes
num_custom_classes = 5
model = models.Sequential([
    base_model,
    layers.GlobalAveragePooling2D(),
    layers.Dense(128, activation='relu'),
    layers.Dense(num_custom_classes, activation='softmax')
])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy', metrics=['accuracy'])

Evaluating and debugging a trained CNN

Accuracy alone can hide serious problems, such as a model ignoring rare classes or cheating by looking at background clues instead of the object.

Confusion matrices and classification metrics

  • What it does: a confusion matrix compares the model's predicted labels with the true ground-truth labels in a grid, showing the exact counts of true positives, false positives and false negatives for each class.
  • Key derived metrics: precision measures how often positive predictions are correct, while recall measures how many of the actual positives the model caught.
  • Quick Python implementation: once you have collected predictions from your validation set, you can generate the matrix with scikit-learn.
from sklearn.metrics import confusion_matrix, classification_report
import numpy as np

# Example true labels and model predictions
y_true = np.array([0, 1, 2, 2, 0, 1])
y_pred = np.array([0, 2, 2, 2, 0, 1])

print("Confusion Matrix:\n", confusion_matrix(y_true, y_pred))
print("\nDetailed Report:\n", classification_report(y_true, y_pred))

Grad-CAM (Gradient-weighted Class Activation Mapping)

  • What it does: Grad-CAM produces a colour-coded heatmap over your input image that highlights the exact pixels that contributed most to the CNN's final decision.
  • Why it matters: it catches “shortcut learning”, for example finding that a model recognises boats by looking at the water instead of the boat itself.
  • How it works: it tracks the gradients flowing into the final convolutional layer, which still keeps spatial locations, and weights each feature map by how important it is to the target class.

Preparing and augmenting real image datasets

Raw images vary in size, lighting and orientation, so they must be standardised and artificially expanded before they enter a CNN.

Essential preprocessing steps

  • Resizing: standardises all images to fixed dimensions, such as 224×224, so they can stack into uniform batches.
  • Normalization: scales pixel intensity values from [0, 255] down to [0, 1], or standardises them with the dataset's mean and standard deviation, so gradients update smoothly.
  • Dataset splitting: divides the data into Training (70 to 80%, for learning weights), Validation (10 to 15%, for tuning hyperparameters) and Test (10 to 15%, held out strictly for the final evaluation).

Data augmentation pipelines

Data augmentation applies random, realistic transformations on the fly during training so the model never sees exactly the same image twice, which reduces overfitting. In PyTorch (torchvision.transforms):

from torchvision import transforms

train_transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.RandomHorizontalFlip(p=0.5),
    transforms.RandomRotation(degrees=15),
    transforms.ColorJitter(brightness=0.2, contrast=0.2),
    transforms.ToTensor(),  # Converts [0, 255] image to [0.0, 1.0] tensor
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

In TensorFlow (tf.keras.layers):

import tensorflow as tf
from tensorflow.keras import layers

data_augmentation = tf.keras.Sequential([
    layers.Resizing(224, 224),
    layers.Rescaling(1./255),
    layers.RandomFlip("horizontal"),
    layers.RandomRotation(0.05),  # ~18 degrees
    layers.RandomContrast(0.2)
])

Grad-CAM code

To generate a Grad-CAM heatmap you capture the feature maps of the final convolutional layer together with the gradients flowing back into that layer during backpropagation.

PyTorch Grad-CAM (manual hooks)

Forward and backward hooks let you extract activations and gradients from any target layer without changing your model class. The pytorch-grad-cam library is another option.

import torch
import torch.nn.functional as F
import numpy as np
import cv2

def generate_gradcam_pytorch(model, input_tensor, target_layer, class_idx=None):
    model.eval()
    activations = []
    gradients = []

    # 1. Register hooks to capture forward activations and backward gradients
    def forward_hook(module, inp, out):
        activations.append(out)

    def backward_hook(module, grad_in, grad_out):
        gradients.append(grad_out[0])

    handle_f = target_layer.register_forward_hook(forward_hook)
    handle_b = target_layer.register_full_backward_hook(backward_hook)

    # 2. Forward pass and backward pass for the target class
    output = model(input_tensor)
    if class_idx is None:
        class_idx = output.argmax(dim=1).item()

    model.zero_grad()
    output[0, class_idx].backward()

    # 3. Compute importance weights via Global Average Pooling of gradients
    grads = gradients[0].detach()[0]
    acts = activations[0].detach()[0]
    weights = grads.mean(dim=(1, 2), keepdim=True)

    # 4. Weighted combination of feature maps + ReLU
    cam = F.relu((weights * acts).sum(dim=0)).cpu().numpy()
    cam = cv2.resize(cam, (input_tensor.shape[3], input_tensor.shape[2]))
    cam = (cam - cam.min()) / (cam.max() - cam.min() + 1e-8)  # Normalize 0 to 1

    # Clean up hooks
    handle_f.remove()
    handle_b.remove()
    return cam

# Usage example with ResNet-50:
# heatmap = generate_gradcam_pytorch(resnet_model, image_tensor, resnet_model.layer4[-1])

TensorFlow (Keras) Grad-CAM with tf.GradientTape

In TensorFlow you create a temporary sub-model that outputs both the last convolutional layer and the final predictions, then record the gradients inside a GradientTape.

import tensorflow as tf
import numpy as np
import cv2

def generate_gradcam_tf(model, img_array, last_conv_layer_name, class_idx=None):
    # 1. Build a model mapping input -> [last conv layer output, final predictions]
    grad_model = tf.keras.models.Model(
        inputs=model.inputs,
        outputs=[model.get_layer(last_conv_layer_name).output, model.output]
    )

    # 2. Record gradients of the predicted class with respect to the conv layer
    with tf.GradientTape() as tape:
        conv_outputs, predictions = grad_model(img_array)
        if class_idx is None:
            class_idx = tf.argmax(predictions[0])
        class_score = predictions[:, class_idx]

    grads = tape.gradient(class_score, conv_outputs)

    # 3. Pool gradients across spatial dimensions and weight the feature maps
    pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
    conv_outputs = conv_outputs[0]
    heatmap = conv_outputs @ pooled_grads[..., tf.newaxis]
    heatmap = tf.squeeze(heatmap)

    # 4. Apply ReLU and normalize between 0 and 1
    heatmap = tf.maximum(heatmap, 0) / (tf.math.reduce_max(heatmap) + 1e-8)
    heatmap = cv2.resize(heatmap.numpy(), (img_array.shape[2], img_array.shape[1]))
    return heatmap

Exporting and deploying a trained CNN

Training frameworks carry heavy dependencies that exist for backpropagation. For production you export the model into a lightweight, inference-only format.

ONNX (Open Neural Network Exchange)

ONNX is an open standard format that lets you train a model in PyTorch (or TensorFlow) and run it anywhere with ONNX Runtime, C++, C# or web browsers, without PyTorch installed. PyTorch export and inference:

import torch
import onnxruntime as ort
import numpy as np

# 1. Export trained PyTorch model to .onnx file
model.eval()
dummy_input = torch.randn(1, 3, 224, 224)
torch.onnx.export(
    model,
    dummy_input,
    "cnn_model.onnx",
    input_names=["input"],
    output_names=["output"],
    dynamic_axes={"input": {0: "batch_size"}, "output": {0: "batch_size"}}
)

# 2. Run fast inference with ONNX Runtime (no PyTorch required)
session = ort.InferenceSession("cnn_model.onnx")
sample_image = np.random.randn(1, 3, 224, 224).astype(np.float32)
predictions = session.run(["output"], {"input": sample_image})[0]

TensorFlow Lite (LiteRT)

TensorFlow Lite is Google's lightweight inference engine for mobile phones (iOS and Android), Raspberry Pi and microcontrollers. It supports quantization, shrinking 32-bit floats to 8-bit integers, which cuts model file size by up to 75% and speeds up inference. TensorFlow conversion and inference:

import tensorflow as tf
import numpy as np

# 1. Convert Keras model to TFLite with default optimizations (quantization)
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()

# Save to disk
with open("cnn_model.tflite", "wb") as f:
    f.write(tflite_model)

# 2. Run inference using the lightweight TFLite Interpreter
interpreter = tf.lite.Interpreter(model_path="cnn_model.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

sample_image = np.random.randn(1, 224, 224, 3).astype(np.float32)
interpreter.set_tensor(input_details[0]['index'], sample_image)
interpreter.invoke()
predictions = interpreter.get_tensor(output_details[0]['index'])

Target hardware and an end-to-end project checklist

Different deployment environments have strict limits on memory, battery life and latency. Choosing the right CNN architecture early prevents performance bottlenecks later, so hardware constraints shape every decision from architecture selection to final deployment.

1. Target hardware and architecture strategy

Target environmentRecommended CNN backboneExport formatPrimary optimization goal
Cloud / Web API (GPU or multi-core CPU server)ResNet-50, ConvNeXt or EfficientNet-B4ONNX or TensorRTHigh throughput (batching many user requests at once) and peak accuracy.
Mobile app (iOS / Android smartphones)MobileNetV3 or EfficientNet-LiteTFLite (LiteRT) or Core MLSmall app download size (under 15 MB) and low battery drain.
Edge device (Raspberry Pi, Jetson or microcontrollers)MobileNetV2, ShuffleNet or Tiny-YOLOTFLite (INT8) or ONNX RuntimeMinimal RAM usage and real-time frame rates without internet access.

2. The five-phase checklist

Follow these five phases in order to take any computer vision project from raw data to production.

Phase 1: data collection and baseline setup

  • Define input specs: lock in a fixed input resolution (for example 224×224 for standard classification, or 128×128 for ultra-fast edge devices) and a colour format (RGB or grayscale).
  • Audit class balance: check whether any category has far fewer images than the others, and apply class weights or targeted data augmentation if needed.
  • Create clean splits: separate the data into Train (70%), Validation (15%) and Test (15%) before applying any augmentation, to prevent data leakage.

Phase 2: model prototyping and transfer learning

  • Start with a pretrained backbone: load a pretrained model that matches your target hardware, such as MobileNetV3 for mobile or ResNet-50 for a web server, rather than training from scratch.
  • Train the classification head first: freeze the convolutional base and train only your new dense layers for 5 to 10 epochs until the validation loss stabilises.
  • Fine-tune the top layers: unfreeze the last one or two convolutional blocks and train with a very low learning rate (for example 1e-5) to adapt the high-level features to your dataset.

Phase 3: validation and error auditing

  • Check confusion matrices: find which pairs of classes the model confuses most often and collect more training examples for those edge cases.
  • Run Grad-CAM spot checks: overlay Grad-CAM heatmaps on 10 to 20 misclassified validation images to confirm the model is focusing on the object and not on background artefacts.
  • Verify on the held-out test set: run one final evaluation on your untouched test set to confirm real-world accuracy.

Phase 4: compression and format export

  • Export to a runtime format: convert your PyTorch or Keras weights to ONNX, TFLite or Core ML.
  • Apply post-training quantization: convert 32-bit floating-point weights to FP16 (half precision, minimal accuracy loss) or INT8 (integer precision, 4x smaller and faster on mobile and edge CPUs).
  • Validate the exported accuracy: run your test set through the exported .onnx or .tflite file to make sure compression did not reduce accuracy.

Phase 5: deployment and production integration

  • For a web API: wrap the ONNX Runtime session inside a lightweight Python framework such as FastAPI, containerise it with Docker and expose a /predict endpoint that accepts image uploads and returns JSON probabilities.
  • For a mobile app: bundle the .tflite or .mlpackage file directly into your app assets and run inference on the device with native Swift or Kotlin bindings, or Flutter or React Native plugins.
  • For an edge device: use OpenCV to capture live camera frames, resize and normalise pixels in a continuous loop, and feed the tensors straight into the TFLite Interpreter or an NVIDIA TensorRT engine.

A FastAPI and ONNX web server (live REST API)

This template builds a production-ready REST API. It loads your exported .onnx model once at startup, accepts uploaded images at a /predict endpoint, preprocesses them and returns JSON class predictions. First install the prerequisites:

pip install fastapi uvicorn onnxruntime pillow numpy python-multipart

Then app.py, the complete API server:

from fastapi import FastAPI, File, UploadFile, HTTPException
import onnxruntime as ort
import numpy as np
from PIL import Image
import io

app = FastAPI(title="CNN Image Classifier API")

# 1. Load ONNX model once when the server starts
MODEL_PATH = "cnn_model.onnx"
session = ort.InferenceSession(MODEL_PATH, providers=["CPUExecutionProvider"])
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name

# Replace with your actual class labels
CLASS_NAMES = ["Class_0", "Class_1", "Class_2", "Class_3", "Class_4"]

def preprocess_image(image_bytes: bytes) -> np.ndarray:
    """Resizes, normalizes, and formats an image into a [1, 3, 224, 224] float32 tensor."""
    image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
    image = image.resize((224, 224))

    # Convert to numpy array and scale pixels to [0, 1]
    img_array = np.array(image, dtype=np.float32) / 255.0

    # Standard ImageNet normalization
    mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
    std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
    img_array = (img_array - mean) / std

    # Rearrange from (H, W, C) to (C, H, W) and add batch dimension -> (1, 3, 224, 224)
    img_array = np.transpose(img_array, (2, 0, 1))
    return np.expand_dims(img_array, axis=0)

def softmax(logits: np.ndarray) -> np.ndarray:
    exp_scores = np.exp(logits - np.max(logits))
    return exp_scores / np.sum(exp_scores)

@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Uploaded file must be an image.")

    image_bytes = await file.read()
    input_tensor = preprocess_image(image_bytes)

    # Run ONNX inference
    outputs = session.run([output_name], {input_name: input_tensor})
    probabilities = softmax(outputs[0][0])
    predicted_idx = int(np.argmax(probabilities))

    return {
        "predicted_class": CLASS_NAMES[predicted_idx],
        "confidence": round(float(probabilities[predicted_idx]), 4),
        "all_probabilities": {
            CLASS_NAMES[i]: round(float(probabilities[i]), 4) for i in range(len(CLASS_NAMES))
        }
    }

# Run the server from your terminal with:
# uvicorn app:app --host 0.0.0.0 --port 8000

A Raspberry Pi and OpenCV live webcam script (TFLite)

This script captures frames continuously from a USB webcam or Pi Camera with OpenCV, runs lightweight inference with a quantized .tflite model, and overlays the live prediction and FPS on the video feed. Install the prerequisites first:

pip install opencv-python-headless numpy tflite-runtime

Then edge_webcam_inference.py, the complete edge script:

import cv2
import numpy as np
import time

# Use tflite_runtime on Raspberry Pi, or fall back to full tensorflow on desktop
try:
    import tflite_runtime.interpreter as tflite
except ImportError:
    import tensorflow.lite as tflite

# 1. Initialize TFLite Interpreter (use 4 threads on Raspberry Pi 4/5)
MODEL_PATH = "cnn_model.tflite"
interpreter = tflite.Interpreter(model_path=MODEL_PATH, num_threads=4)
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
input_shape = input_details[0]['shape']  # e.g., [1, 224, 224, 3]
height, width = input_shape[1], input_shape[2]
is_quantized = (input_details[0]['dtype'] == np.uint8)

CLASS_NAMES = ["Class_0", "Class_1", "Class_2", "Class_3", "Class_4"]

# 2. Open webcam stream (0 is usually the default USB/built-in camera)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
    raise RuntimeError("Could not open webcam.")

print("Starting live inference. Press 'q' to quit.")

while True:
    start_time = time.time()
    ret, frame = cap.read()
    if not ret:
        break

    # 3. Preprocess frame (OpenCV uses BGR, convert to RGB)
    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    resized = cv2.resize(rgb_frame, (width, height))

    if is_quantized:
        input_data = np.expand_dims(resized, axis=0).astype(np.uint8)
    else:
        input_data = np.expand_dims(resized.astype(np.float32) / 255.0, axis=0)

    # 4. Run TFLite inference
    interpreter.set_tensor(input_details[0]['index'], input_data)
    interpreter.invoke()
    predictions = interpreter.get_tensor(output_details[0]['index'])[0]

    # 5. Extract top prediction and calculate FPS
    top_idx = int(np.argmax(predictions))
    confidence = float(predictions[top_idx])
    if is_quantized:
        confidence /= 255.0  # Rescale uint8 output to 0.0 - 1.0

    fps = 1.0 / (time.time() - start_time)
    label_text = f"{CLASS_NAMES[top_idx]} ({confidence*100:.1f}%) | FPS: {fps:.1f}"

    # 6. Draw overlay onto the display frame
    cv2.rectangle(frame, (10, 10), (480, 50), (0, 0, 0), -1)
    cv2.putText(frame, label_text, (20, 38), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

    cv2.imshow("Edge CNN Inference", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Containerising the FastAPI server with Docker

Containerising your FastAPI server packages your Python environment, ONNX Runtime and trained model into a portable image that runs the same way on any cloud provider. Keep your files inside one project folder before building the container:

cnn-api/
├── app.py               # Your FastAPI server code
├── cnn_model.onnx       # Your exported ONNX model
├── requirements.txt     # Python dependencies
└── Dockerfile           # Container build instructions

requirements.txt:

fastapi==0.115.0
uvicorn==0.30.6
onnxruntime==1.19.2
pillow==10.4.0
numpy==1.26.4
python-multipart==0.0.12

The production Dockerfile uses a slim Python base image to keep the container small and quick to download during cloud deployment:

# Use an official lightweight Python runtime
FROM python:3.11-slim

# Prevent Python from writing .pyc files and enable unbuffered logs
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Set the working directory inside the container
WORKDIR /app

# Install system dependencies needed by Pillow
RUN apt-get update && apt-get install -y --no-install-recommends \
    libjpeg62-turbo-dev \
    zlib1g-dev \
    && rm -rf /var/lib/apt/lists/*

# Copy and install Python dependencies first (caches layer for faster rebuilds)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy your FastAPI code and exported ONNX model into the container
COPY app.py .
COPY cnn_model.onnx .

# Expose port 8000 for incoming HTTP traffic
EXPOSE 8000

# Start the Uvicorn server
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

Run these commands from inside your cnn-api/ directory. Step 1, build and start the container:

# Build the Docker image
docker build -t cnn-classifier-api .

# Run the container locally, mapping port 8000 on your machine to port 8000 in Docker
docker run -d -p 8000:8000 --name cnn-service cnn-classifier-api

Step 2, test the endpoint with cURL by sending a sample image (test_image.jpg) in a POST request to the running container:

curl -X POST "http://localhost:8000/predict" \
     -H "accept: application/json" \
     -H "Content-Type: multipart/form-data" \
     -F "file=@test_image.jpg;type=image/jpeg"

The expected JSON response:

{
    "predicted_class": "Class_2",
    "confidence": 0.9412,
    "all_probabilities": {
        "Class_0": 0.0105,
        "Class_1": 0.0241,
        "Class_2": 0.9412,
        "Class_3": 0.0150,
        "Class_4": 0.0092
    }
}

Closing thoughts

A CNN is built from a small set of ideas: convolution, ReLU, pooling and a dense classifier on top, with parameter sharing and local connectivity doing the heavy lifting. From that base, ResNet and U-Net solve depth and resolution, transfer learning saves data and time, Grad-CAM keeps the model honest, and ONNX, TFLite, FastAPI and Docker carry it from a notebook to a server, a phone or a camera.

More AI technology news