Computer Vision AI
Computer Vision AI
About 80% of the information humans acquire comes from vision.
When you see a photo, you can immediately recognize how many people are in it, what they are doing, and whether the background is indoors or outdoors.
But to a computer, this photo is just a bunch of numbers—each pixel is represented by three values: red, green, and blue, that's all.
Computer Vision (CV) is the technology that allows computers to understand images.
From facial recognition on mobile phones to traffic condition recognition in autonomous driving, and even lesion analysis in medical imaging, computer vision is everywhere.
This module will take you from basic convolutional neural networks all the way to the latest vision-language models.
Learning Path: Convolutional Neural Networks → Vision Transformer → Object Detection → Image Segmentation → Diffusion Models → CLIP → Vision-Language Models. Each step includes runnable code examples.
Convolutional Neural Networks (CNN)
CNN is a foundational technology in computer vision, mimicking the way the human visual cortex works by extracting image features through local receptive fields.
Principle of Convolution Operation
The core idea of convolution is to scan an image with a small sliding window (convolutional kernel) to extract local features.
For example, a 3x3 convolutional kernel looks at 9 pixels on the image each time, calculates their weighted sum, and produces an output value.
This process is repeated as the convolutional kernel slides across the image from left to right and top to bottom, ultimately generating a "feature map."
Example
============================================
Implement the simplest convolution operation using NumPy
Demonstrate how convolution extracts edge features
============================================
import
numpy
as
np
def
simple_convolution
(
image: np.
ndarray
,
kernel: np.
ndarray
)
np.
ndarray
:
"""
Implements the most basic 2D convolution operation (without padding and stride)
Parameters:
image: Input image (H, W), single-channel grayscale image
kernel: Convolution kernel (kH, kW)
Returns:
The feature map after convolution
"""
Get the dimensions of the image and the kernel
img_h
,
img_w
=
image.
shape
kernel_h
,
kernel_w
=
kernel.
shape
Calculate the size of the output feature map
Output size = Input size - Kernel size + 1
out_h
=
img_h - kernel_h +
1
out_w
=
img_w - kernel_w +
1
Initialize output feature map
output
=
np.
zeros
(
(
out_h
,
out_w
)
)
Perform calculation with sliding convolution kernel
for
i
in
range
(
out_h
)
:
for
j
in
range
(
out_w
)
:
Extract the local region corresponding to the convolution kernel from the image
region
=
image
[
i:i+kernel_h
,
j:j+kernel_w
]
Sum of the product of corresponding elements (this is the convolution operation)
output
[
i
,
j
]
=
np.
sum
(
region * kernel
)
return
output
Create a simple test image: a white square in the center surrounded by black
Shape: 8x8 grayscale image
test_image
=
np.
array
(
[
[
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
]
,
[
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
]
,
[
0
,
0
,
1
,
1
,
1
,
1
,
0
,
0
]
,
[
0
,
0
,
1
,
1
,
1
,
1
,
0
,
0
]
,
[
0
,
0
,
1
,
1
,
1
,
1
,
0
,
0
]
,
[
0
,
0
,
1
,
1
,
1
,
1
,
0
,
0
]
,
[
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
]
,
[
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
]
,
]
)
(
"Original image:"
)
(
test_image
)
Define an edge detection convolution kernel (a simplified version of the Sobel operator)
This kernel can detect vertical edges
edge_kernel
=
np.
array
(
[
[
1
,
0
,
1
]
,
[
2
,
0
,
2
]
,
[
1
,
0
,
1
]
,
]
)
Execute convolution
feature_map
=
simple_convolution
(
test_image
,
edge_kernel
)
(
"\nFeature map after convolution (vertical edges detected):"
)
(
np.
round
(
feature_map
,
2
)
)
The key to convolution operation is: the parameters of the convolution kernel are learned, not manually designed.
During training, the model automatically adjusts the values of the convolution kernel so that it can extract features useful for the task.
Pooling
The purpose of pooling is to compress the size of the feature map, reduce computational load, while keeping important features unchanged.
The most commonly used is Max Pooling: dividing the feature map into several small blocks and retaining only the maximum value in each block.
Example
============================================
Implement max pooling operation
============================================
def
max_pooling
(
feature_map: np.
ndarray
,
pool_size:
int
=
2
)
np.
ndarray
:
"""
Implements max pooling operation
Parameters:
feature_map: Input feature map (H, W)
pool_size: Pooling window size, default 2x2
Returns:
The pooled feature map
"""
h
,
w
=
feature_map.
shape
Calculate output size
out_h
=
h // pool_size
out_w
=
w // pool_size
output
=
np.
zeros
(
(
out_h
,
out_w
)
)
for
i
in
range
(
out_h
)
:
for
j
in
range
(
out_w
)
:
Extract the pooled window region
region
=
feature_map
[
i*pool_size:
(
i+
1
)
*pool_size
,
j*pool_size:
(
j+
1
)
*pool_size
]
Get maximum value
output
[
i
,
j
]
=
np.
max
(
region
)
return
output
Perform pooling on the feature map just generated
(
"Feature map before pooling:"
)
(
feature_map
)
pooled
=
max_pooling
(
feature_map
,
pool_size
=
2
)
(
"\n2×2 max pooled feature map:"
)
(
pooled
)
Classic Architecture Comparison
There have been several milestone architectures in the history of CNNs, each representing the design philosophy of a different era.
| Architecture | Year | Core innovation | Features |
|---|---|---|---|
| AlexNet | 2012 | ReLU activation, Dropout, data augmentation | Initiator of the deep learning era, first significantly outperformed traditional methods on ImageNet |
| VGG | 2014 | Unified use of 3x3 small convolutional kernels | Simple and elegant structure, easy to understand and implement |
| ResNet | 2015 | Residual connection (Skip Connection) | Solves the vanishing gradient problem in deep networks, allowing networks to reach hundreds of layers |
| EfficientNet | 2019 | Compound scaling method | Scales depth, width, and resolution simultaneously, with extremely high parameter efficiency |
Residual Connection (Skip Connection)
The core innovation of ResNet is the residual connection, which solves the problem of "deeper networks being harder to train."
The learning objective of traditional network layers is: to directly learn the mapping from input x to output y.
The learning objective of residual networks is: to learn the difference (residual) between the output y and the input x.
Formula expression: y = F(x) + x, where F(x) is the residual to be learned.
Intuition of residual connections: letting the network learn "how much to change from the existing state" is much easier than letting it "learn the complete mapping from scratch."
Example
============================================
Implement a complete CNN image classifier using PyTorch
Including convolution, pooling, and residual connections
============================================
import
torch
import
torch.
nn
as
nn
import
torch.
nn
.
functional
as
F
class
ResidualBlock
(
nn.
Module
)
:
"""A simple residual block"""
def
init
(
self
,
in_channels:
int
,
out_channels:
int
,
stride:
int
=
1
)
:
super
(
)
.
init
(
)
The first convolutional layer
self
.
conv1
=
nn.
Conv2d
(
in_channels
,
out_channels
,
kernel_size
=
3
,
stride
=
stride
,
padding
=
1
,
bias
=
False
)
self
.
bn1
=
nn.
BatchNorm2d
(
out_channels
)
The second convolutional layer
self
.
conv2
=
nn.
Conv2d
(
out_channels
,
out_channels
,
kernel_size
=
3
,
stride
=
1
,
padding
=
1
,
bias
=
False
)
self
.
bn2
=
nn.
BatchNorm2d
(
out_channels
)
Quick connection (used for matching dimension changes)
self
.
shortcut
=
nn.
Sequential
(
)
if
stride
!=
1
or
in_channels
!=
out_channels:
self
.
shortcut
=
nn.
Sequential
(
nn.
Conv2d
(
in_channels
,
out_channels
,
kernel_size
=
1
,
stride
=
stride
,
bias
=
False
)
,
nn.
BatchNorm2d
(
out_channels
)
)
def
forward
(
self
,
x: torch.
Tensor
)
torch.
Tensor
:
Main path: Conv → BN → ReLU → Conv → BN
out
=
F.
relu
(
self
.
bn1
(
self
.
conv1
(
x
)
)
)
out
=
self
.
bn2
(
self
.
conv2
(
out
)
)
Residual connection: add the input (or the input after dimension transformation)
out +
=
self
.
shortcut
(
x
)
The final ReLU
out
=
F.
relu
(
out
)
return
out
class
SimpleCNN
(
nn.
Module
)
:
"""A simple CNN for image classification (with residual connections)"""
def
init
(
self
,
num_classes:
int
=
10
)
:
super
(
)
.
init
(
)
Initial convolutional layer
self
.
conv1
=
nn.
Conv2d
(
3
,
32
,
kernel_size
=
3
,
stride
=
1
,
padding
=
1
)
self
.
bn1
=
nn.
BatchNorm2d
(
32
)
Residual layer
self
.
layer1
=
ResidualBlock
(
32
,
32
)
self
.
layer2
=
ResidualBlock
(
32
,
64
,
stride
=
2
)
self
.
layer3
=
ResidualBlock
(
64
,
64
)
Global average pooling
self
.
global_pool
=
nn.
AdaptiveAvgPool2d
(
(
1
,
1
)
)
Category header
self
.
fc
=
nn.
Linear
(
64
,
num_classes
)
def
forward
(
self
,
x: torch.
Tensor
)
torch.
Tensor
:
x shape: (batch_size, 3, 32, 32)
x
=
F.
relu
(
self
.
bn1
(
self
.
conv1
(
x
)
)
)
x
=
self
.
layer1
(
x
)
(batch_size, 32, 32, 32)
x
=
self
.
layer2
(
x
)
(batch_size, 64, 16, 16)
x
=
self
.
layer3
(
x
)
(batch_size, 64, 16, 16)
x
=
self
.
global_pool
(
x
)
(batch_size, 64, 1, 1)
x
=
x.
view
(
x.
size
(
0
)
,
1
)
(batch_size, 64)
x
=
self
.
fc
(
x
)
(batch_size, num_classes)
return
x
Create model and test
model
=
SimpleCNN
(
num_classes
=
10
)
(
"Model structure:"
)
(
model
)
Test forward propagation
Create a fake batch: 4 images, each 3x32x32 (RGB 32x32)
test_input
=
torch.
randn
(
4
,
3
,
32
,
32
)
test_output
=
model
(
test_input
)
(
f
"\nInput shape: {test_input.shape}"
)
(
f
"Output shape: {test_output.shape} (batch_size, num_classes)"
)
Vision Transformer (ViT)
In 2020, Google published the paper "An Image is Worth 16x16 Words," moving the Transformer architecture from the language domain to the vision domain.
Image Patch Embedding
Transformers process sequence data, but images are 2D grid data.
The solution for ViT is simple: slice the image into small patches, treating each patch as a word.
For example, a 224×224 image sliced into 16×16 patches yields 14×14 = 196 patches.
Each patch is flattened into a one-dimensional vector, then projected into an embedding via a linear layer, which can then be fed into the Transformer.
Example
============================================
Implement Patch Embedding (Image Patching)
============================================
class
PatchEmbedding
(
nn.
Module
)
:
"""
Split the image into patches and embed
Parameters:
img_size: Input image size (square)
patch_size: Size of each patch (square)
in_channels: Number of input channels (3 for RGB)
embed_dim: Output embedding dimension
"""
def
init
(
self
,
img_size:
int
=
224
,
patch_size:
int
=
16
,
in_channels:
int
=
3
,
embed_dim:
int
=
768
)
:
super
(
)
.
init
(
)
self
.
img_size
=
img_size
self
.
patch_size
=
patch_size
Calculate the number of patches: (224/16)^2 = 14^2 = 196
self
.
num_patches
=
(
img_size // patch_size
)
**
2
Implement patch division and embedding using convolution
This is equivalent to: slice patch -> flatten -> linear projection
self
.
proj
=
nn.
Conv2d
(
in_channels
,
embed_dim
,
kernel_size
=
patch_size
,
stride
=
patch_size
)
def
forward
(
self
,
x: torch.
Tensor
)
torch.
Tensor
:
x shape: (batch_size, in_channels, img_size, img_size)
x
=
self
.
proj
(
x
)
(batch_size, embed_dim, num_patches^0.5, num_patches^0.5)
x
=
x.
flatten
(
2
)
(batch_size, embed_dim, num_patches)
x
=
x.
transpose
(
1
,
2
)
(batch_size, num_patches, embed_dim)
return
x
Test Patch Embedding
patch_embed
=
PatchEmbedding
(
img_size
=
224
,
patch_size
=
16
,
embed_dim
=
768
)
test_image
=
torch.
randn
(
1
,
3
,
224
,
224
)
1 RGB image of size 224×224
patches
=
patch_embed
(
test_image
)
(
f
"Input image shape: {test_image.shape}"
)
(
f
"Patch sequence shape: {patches.shape} (batch_size, num_patches, embed_dim)"
)
Full ViT architecture
The full ViT architecture also needs to include a class token and positional encoding.
The class token is a learnable vector whose function is to "summarize" the information of all patches.
Positional encoding is also learnable; it tells the model "which position each patch is in the image".
Instance
============================================
Implement a simplified Vision Transformer
============================================
class
MultiHeadAttention
(
nn.
Module
)
:
"""Multi-head self-attention"""
def
init
(
self
,
dim:
int
,
num_heads:
int
)
:
super
(
)
.
init
(
)
self
.
num_heads
=
num_heads
self
.
head_dim
=
dim // num_heads
assert
self
.
head_dim
- num_heads
==
dim
,
"Dimension must be divisible by the number of heads"
Q, K, V projection matrices
self
.
qkv
=
nn.
Linear
(
dim
,
dim *
3
)
Output projection
self
.
proj
=
nn.
Linear
(
dim
,
dim
)
def
forward
(
self
,
x: torch.
Tensor
)
torch.
Tensor
:
batch_size
,
seq_len
,
dim
=
x.
shape
Calculate Q, K, V
qkv
=
self
.
qkv
(
x
)
(batch_size, seq_len, dim*3)
qkv
=
qkv.
reshape
(
batch_size
,
seq_len
,
3
,
self
.
num_heads
,
self
.
head_dim
)
(batch_size, seq_len, 3, num_heads, head_dim)
q
,
k
,
v
=
qkv.
unbind
(
2
)
Each shape: (batch_size, seq_len, num_heads, head_dim)
Adjust the order for attention calculation
q
=
q.
transpose
(
1
,
2
)
(batch_size, num_heads, seq_len, head_dim)
k
=
k.
transpose
(
1
,
2
)
v
=
v.
transpose
(
1
,
2
)
Calculate attention score
attention
=
q
@
k.
transpose
(
2
,
1
)
/
(
self
.
head_dim
**
0.5
)
attention
=
attention.
softmax
(
dim
=
1
)
Aggregated value
out
=
attention
@
v
(batch_size, num_heads, seq_len, head_dim)
out
=
out.
transpose
(
1
,
2
)
(batch_size, seq_len, num_heads, head_dim)
out
=
out.
flatten
(
2
)
(batch_size, seq_len, dim)
Output projection
out
=
self
.
proj
(
out
)
return
out
class
TransformerBlock
(
nn.
Module
)
:
"""A Transformer block"""
def
init
(
self
,
dim:
int
,
num_heads:
int
,
mlp_ratio:
float
=
4.0
)
:
super
(
)
.
init
(
)
self
.
norm1
=
nn.
LayerNorm
(
dim
)
self
.
attn
=
MultiHeadAttention
(
dim
,
num_heads
)
self
.
norm2
=
nn.
LayerNorm
(
dim
)
MLP
mlp_hidden
=
int
(
dim * mlp_ratio
)
self
.
mlp
=
nn.
Sequential
(
nn.
Linear
(
dim
,
mlp_hidden
)
,
nn.
GELU
(
)
,
nn.
Linear
(
mlp_hidden
,
dim
)
)
def
forward
(
self
,
x: torch.
Tensor
)
torch.
Tensor
:
Residual Connection 1
x
=
x +
self
.
attn
(
self
.
norm1
(
x
)
)
Residual Connection 2
x
=
x +
self
.
mlp
(
self
.
norm2
(
x
)
)
return
x
class
SimpleViT
(
nn.
Module
)
:
"""Simplified Vision Transformer"""
def
init
(
self
,
img_size:
int
=
224
,
patch_size:
int
=
16
,
in_channels:
int
=
3
,
num_classes:
int
=
10
,
embed_dim:
int
=
192
,
depth:
int
=
6
,
num_heads:
int
=
6
)
:
super
(
)
.
init
(
)
Patch embedding
self
.
patch_embed
=
PatchEmbedding
(
img_size
,
patch_size
,
in_channels
,
embed_dim
)
num_patches
=
self
.
patch_embed
.
num_patches
Class token
self
.
cls_token
=
nn.
Parameter
(
torch.
zeros
(
1
,
1
,
embed_dim
)
)
Positional encoding
self
.
pos_embed
=
nn.
Parameter
(
torch.
zeros
(
1
,
num_patches +
1
,
embed_dim
)
)
Transformer layer
self
.
blocks
=
nn.
ModuleList
(
[
TransformerBlock
(
embed_dim
,
num_heads
)
for
_
in
range
(
depth
)
]
)
The final LayerNorm and classification head
self
.
norm
=
nn.
LayerNorm
(
embed_dim
)
self
.
head
=
nn.
Linear
(
embed_dim
,
num_classes
)
def
forward
(
self
,
x: torch.
Tensor
)
torch.
Tensor
:
batch_size
=
x.
shape
[
0
]
Patch embedding
x
=
self
.
patch_embed
(
x
)
(batch_size, num_patches, embed_dim)
Add class token
cls_tokens
=
self
.
cls_token
.
expand
(
batch_size
,
1
,
1
)
x
=
torch.
cat
(
(
cls_tokens
,
x
)
,
dim
=
1
)
(batch_size, 1+num_patches, embed_dim)
Add positional encoding
x
=
x +
self
.
pos_embed
Through Transformer layer
for
block
in
self
.
blocks
:
x
=
block
(
x
)
Only use class token for classification
x
=
self
.
norm
(
x
)
cls_output
=
x
[
:
,
0
]
Take the first position (class token)
x
=
self
.
head
(
cls_output
)
return
x
Create ViT model and test
vit
=
SimpleViT
(
img_size
=
32
,
Use a smaller image for easier testing
patch_size
=
8
,
8x8 patch
embed_dim
=
128
,
depth
=
4
,
num_heads
=
4
,
num_classes
=
10
)
(
"Simplified ViT structure:"
)
(
vit
)
test_input
=
torch.
randn
(
2
,
3
,
32
,
32
)
2 pieces of 32x32 image
test_output
=
vit
(
test_input
)
(
f
"\nInput shape: {test_input.shape}"
)
(
f
"Output shape: {test_output.shape}"
)
CNN vs ViT Comparison
Both architectures have their strengths and weaknesses; the choice depends on your specific scenario.
| Features | CNN | ViT |
|---|---|---|
| Inductive Bias | Strong (locality, translation invariance) | Weak (learned from data) |
| Data requirements | Can work with small data | Requires large amounts of data to show advantage |
| Computational efficiency | Usually faster, mature hardware optimization | Large number of parameters, computationally intensive |
| Interpretability | Convolution kernels are easy to visualize | Attention maps are interpretable, but the overall structure is difficult |
| Long-range dependencies | Requires multiple layers to establish | Naturally supports a global receptive field |
| Applicable scenarios | Limited data volume, high real-time requirements | Large datasets, complex vision tasks |
Rule of thumb: Use CNN (ResNet, EfficientNet) when data volume is small; consider ViT when data volume is over millions. Hybrid architectures (like ConvNeXt) combining the advantages of both are also available.
Object Detection
Image classification answers "What is in this picture," while object detection answers "What is in this picture, and where are they located."
The output of object detection is a series of bounding boxes, each corresponding to an object class.
Two-stage detection: R-CNN series
The idea behind two-stage detection is: first find regions that might contain objects, and then classify these regions.
First stage: Generate region proposals, which might be hundreds of boxes saying "something might be here."
Second stage: Extract features for each candidate region to determine what object it is, while simultaneously adjusting the box's position.
Evolution of the R-CNN series:
| Model | Core improvements | Speed |
|---|---|---|
| R-CNN | Replacing traditional features with CNN | Slow (tens of seconds per image) |
| Fast R-CNN | ROI Pooling, shared feature computation | Medium (a few seconds per image) |
| Faster R-CNN | RPN (Region Proposal Network) | Fast (a few hundred milliseconds per image) |
| Mask R-CNN | Add segmentation branch | Medium |
Single-stage detection: YOLO series
The idea of single-stage detection is to directly predict densely on the image without separately generating candidate regions.
YOLO (You Only Look Once) is a representative of single-stage detection, which is extremely fast and suitable for real-time applications.
YOLO divides the image into an S×S grid, and each grid is responsible for predicting objects whose center point falls into that cell.
Each grid predicts: B bounding boxes (including confidence) and the probability for C classes.
End-to-end detection: DETR
DETR (DEtection TRansformer) is a new paradigm proposed by Facebook AI, which uses the Transformer to turn object detection into a direct sequence prediction problem.
Its biggest feature is that it does not require Non-Maximum Suppression (NMS) and does not require anchors; the output is the final result.
Practical application: YOLOv11 object detection
Now we will use Ultralytics YOLOv11 to create a complete object detection example.
Example
============================================
YOLOv11 Object Detection Practice
Includes model loading, detection, and visualization
============================================
import
torch
import
numpy
as
np
from
PIL
import
Image
,
ImageDraw
,
ImageFont
import
matplotlib.
pyplot
as
plt
class
SimpleYOLO:
"""Simplified YOLO demo (using pre-trained model)"""
def
init
(
self
,
model_name:
str
=
"yolo11n.pt"
)
:
"""
Initialize YOLO model
Parameters:
model_name: Model name, such as yolo11n.pt (nano, small) or yolo11s.pt (small)
"""
self
.
model_name
=
model_name
self
.
model
=
None
80 categories of the COCO dataset
self
.
coco_names
=
[
'person'
,
'bicycle'
,
'car'
,
'motorcycle'
,
'airplane'
,
'bus'
,
'train'
,
'truck'
,
'boat'
,
'traffic light'
,
'fire hydrant'
,
'stop sign'
,
'parking meter'
,
'bench'
,
'bird'
,
'cat'
,
'dog'
,
'horse'
,
'sheep'
,
'cow'
,
'elephant'
,
'bear'
,
'zebra'
,
'giraffe'
,
'backpack'
,
'umbrella'
,
'handbag'
,
'tie'
,
'suitcase'
,
'frisbee'
,
'skis'
,
'snowboard'
,
'sports ball'
,
'kite'
,
'baseball bat'
,
'baseball glove'
,
'skateboard'
,
'surfboard'
,
'tennis racket'
,
'bottle'
,
'wine glass'
,
'cup'
,
'fork'
,
'knife'
,
'spoon'
,
'bowl'
,
'banana'
,
'apple'
,
'sandwich'
,
'orange'
,
'broccoli'
,
'carrot'
,
'hot dog'
,
'pizza'
,
'donut'
,
'cake'
,
'chair'
,
'couch'
,
'potted plant'
,
'bed'
,
'dining table'
,
'toilet'
,
'tv'
,
'laptop'
,
'mouse'
,
'remote'
,
'keyboard'
,
'cell phone'
,
'microwave'
,
'oven'
,
'toaster'
,
'sink'
,
'refrigerator'
,
'book'
,
'clock'
,
'vase'
,
'scissors'
,
'teddy bear'
,
'hair drier'
,
'toothbrush'
]
Color for each category
self
.
colors
=
np.
random
.
randint
(
0
,
255
,
(
80
,
3
)
)
def
load_model
(
self
)
:
"""Load pre-trained model (using simulation here to demonstrate the concept)"""
(
f
"Loading model {self.model_name}..."
)
(
"Hint: When actually using, please install ultralytics and call:"
)
(
" from ultralytics import YOLO"
)
(
" model = YOLO('yolo11n.pt')"
)
self
.
model
=
"pretrained_model_loaded"
(
"Model loading complete!"
)
return
self
def
predict_dummy
(
self
,
image: np.
ndarray
)
list
:
"""
Simulated detection results (for demonstration)
In actual use, call model(image)
Returns:
A list of detection results, where each element is a dictionary:
{'bbox': [x1, y1, x2, y2], 'class_id': int, 'score': float, 'class_name': str}
"""
Here we simulate detecting several objects
h
,
w
=
image.
shape
[
:
2
]
dummy_results
=
[
{
'bbox'
:
[
w*
0.1
,
h*
0.2
,
w*
0.3
,
h*
0.6
]
,
'class_id'
:
0
,
'score'
:
0.92
,
'class_name'
:
'person'
}
,
{
'bbox'
:
[
w*
0.35
,
h*
0.4
,
w*
0.7
,
h*
0.8
]
,
'class_id'
:
2
,
'score'
:
0.85
,
'class_name'
:
'car'
}
,
{
'bbox'
:
[
w*
0.75
,
h*
0.3
,
w*
0.9
,
h*
0.55
]
,
'class_id'
:
16
,
'score'
:
0.78
,
'class_name'
:
'dog'
}
,
]
return
dummy_results
def
visualize
(
self
,
image: np.
ndarray
,
results:
list
)
np.
ndarray
:
"""
Draw detection boxes and labels on the image
Parameters:
image: original image (H, W, 3)
results: list of detection results
Returns:
annotated image
"""
if
isinstance
(
image
,
np.
ndarray
)
:
image
=
Image.
fromarray
(
image
)
draw
=
ImageDraw.
Draw
(
image
)
for
result
in
results:
bbox
=
result
[
'bbox'
]
class_id
=
result
[
'class_id'
]
score
=
result
[
'score'
]
class_name
=
result
[
'class_name'
]
color
=
tuple
(
self
.
colors
[
class_id %
80
]
.
tolist
(
)
)
Draw frame
draw.
rectangle
(
bbox
,
outline
=
color
,
width
=
3
)
Label background
label
=
f
"{class_name} {score:.2f}"
try
:
font
=
ImageFont.
truetype
(
"arial.ttf"
,
16
)
except
:
font
=
ImageFont.
load_default
(
)
Calculate text size
bbox_label
=
draw.
textbbox
(
(
0
,
0
)
,
label
,
font
=
font
)
text_w
=
bbox_label
[
2
]
- bbox_label
[
0
]
text_h
=
bbox_label
[
3
]
- bbox_label
[
1
]
Draw label background
label_bg
=
[
bbox
[
0
]
,
bbox
[
1
]
-text_h-
5
,
bbox
[
0
]
+text_w+
5
,
bbox
[
1
]
]
draw.
rectangle
(
label_bg
,
fill
=
color
)
Draw text
draw.
text
(
(
bbox
[
0
]
2
,
bbox
[
1
]
-text_h-
3
)
,
label
,
fill
=
(
255
,
255
,
255
)
,
font
=
font
)
return
np.
array
(
image
)
Create a simulated image (for demonstration)
def
create_test_image
(
)
np.
ndarray
:
"""Create a test image"""
h
,
w
=
480
,
640
image
=
np.
zeros
(
(
h
,
w
,
3
)
,
dtype
=
np.
uint8
)
Gradient background
image
[
:
,
:
,
0
]
=
np.
linspace
(
100
,
200
,
w
)
[
np.
newaxis
,
:
]
image
[
:
,
:
,
1
]
=
np.
linspace
(
150
,
100
,
h
)
[
:
,
np.
newaxis
]
image
[
:
,
:
,
2
]
=
180
return
image
Demo YOLO detection process
(
"="
60
)
(
"RUNOOB YOLOv11 Object Detection Demo"
)
(
"="
60
)
Initialization
detector
=
SimpleYOLO
(
)
.
load_model
(
)
Create test image
test_image
=
create_test_image
(
)
(
f
"\nInput image size: {test_image.shape}"
)
Simulate detection
results
=
detector.
predict_dummy
(
test_image
)
(
f
"Detected {len(results)} objects:"
)
for
i
,
r
in
enumerate
(
results
,
1
)
:
(
f
" {i}. {r['class_name']} (confidence: {r['score']:.2f})"
)
Visualization
visualized
=
detector.
visualize
(
test_image
,
results
)
(
f
Visualization complete, output image size: {visualized.shape}
)
============================================
Actual code using YOLOv11 (requires installing ultralytics)
============================================
(
"\n"
"="
60
)
(
"Code example using YOLOv11 in practice:"
)
(
"="
60
)
(
"""
Installation: pip install ultralytics
from ultralytics import YOLO
1. Load model
model = YOLO('yolo11n.pt') # Can also use 'yolo11s.pt', 'yolo11m.pt', etc.
2. Predict
results = model('test_image.jpg') # Can be an image path, video, or 0 (camera)
3. Process results
for result in results:
# Bounding boxes
boxes = result.boxes
# Segmentation masks (if using a segmentation model)
masks = result.masks
# Display results
result.show()
# Save results
result.save('result.jpg')
4. Training (Optional)
model.train(data='coco128.yaml', epochs=100, imgsz=640)
"""
)
Image Segmentation
Object detection uses bounding boxes to mark objects, while image segmentation requires pixel-level precision to mark which object each pixel belongs to.
Semantic Segmentation vs Instance Segmentation
Image segmentation has two main branches: semantic segmentation and instance segmentation.
| Task | Goal | Example | Representative model |
|---|---|---|---|
| Semantic segmentation | Classify each pixel (regardless of instance) | Mark all people as red and all cars as blue | FCN, U-Net, DeepLab |
| Instance Segmentation | Classify each pixel and distinguish different instances | Label person 1 as red and person 2 as orange | Mask R-CNN, YOLOv8-Seg |
| Panoptic Segmentation | Semantic + Instance, unified representation | Simultaneously label all "things" and "background" | Panoptic FPN, MaskFormer |
A classic example: assume there are two people and two dogs.
Semantic segmentation says: there are "people" and "dogs" (only classifying categories, not counting).
Instance segmentation says: there is "person 1", "person 2", "dog 1", and "dog 2" (each individual entity is distinct).
Segment Anything Model (SAM)
In 2023, Meta AI released SAM (Segment Anything Model), which turned segmentation into a prompt-driven interactive task.
SAM's input can be: a point, a box, a piece of text, or a rough mask.
SAM's output is: a precise segmentation mask corresponding to the object.
SAM's design philosophy is: promptable, generalizable, and zero-shot.
Instance
============================================
SAM Segmentation Concept Demo
Demonstrates segmentation using prompts like points and boxes
============================================
class
SimpleSAM:
"""Simplified SAM concept demonstration"""
def
init
(
self
)
:
self
.
image_embedding
=
None
(
"SAM Concept Demo Initialization"
)
def
set_image
(
self
,
image: np.
ndarray
)
:
"""Encode the image (do only once)"""
(
"Encoding image into embedding..."
)
self
.
image_embedding
=
"image_encoded"
return
self
def
predict_from_point
(
self
,
point:
tuple
,
point_label:
int
=
1
)
:
"""
Split from a point
Parameters:
point: (x, y) coordinates
point_label: 1 indicates foreground, 0 indicates background
"""
(
f
"Segmenting from point {point} ({'foreground' if point_label == 1 else 'background'})"
)
return
"mask_from_point"
def
predict_from_box
(
self
,
box:
tuple
)
:
"""Segment from a bounding box"""
x1
,
y1
,
x2
,
y2
=
box
(
f
"Splitting from box [{x1}, {y1}, {x2}, {y2}]"
)
return
"mask_from_box"
def
predict_from_points
(
self
,
points:
list
,
labels:
list
)
:
"Divide from multiple points"
(
f
"Divide from {len(points)} points"
)
return
"mask_from_points"
Demonstrate SAM usage flow
(
"="
60
)
(
"RUNOOB SAM Segmentation Concept Demonstration"
)
(
"="
60
)
sam
=
SimpleSAM
(
)
1. Set image (encode once)
test_img
=
create_test_image
(
)
sam.
set_image
(
test_img
)
2. Split with different prompts
(
)
mask1
=
sam.
predict_from_point
(
(
100
,
200
)
,
point_label
=
1
)
(
)
mask2
=
sam.
predict_from_box
(
(
50
,
50
,
200
,
300
)
)
(
)
mask3
=
sam.
predict_from_points
(
[
(
100
,
100
)
,
(
150
,
150
)
]
,
[
1
,
1
]
)
============================================
Code example for actual use of SAM
============================================
(
"\n"
"="
60
)
(
"Code example using SAM:"
)
(
"="
60
)
(
"""
Installation: pip install segment-anything torch torchvision opencv-python
import cv2
import numpy as np
from segment_anything import sam_model_registry, SamPredictor
1. Load model
Download checkpoint: https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
sam = sam_model_registry"vit_h"
sam.to(device="cuda")
predictor = SamPredictor(sam)
2. Set the image
image = cv2.imread("test_image.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
predictor.set_image(image)
3. Segment using point prompts
input_point = np.array([[300, 250]]) # Prompt point coordinates
input_label = np.array([1]) # 1 = foreground, 0 = background
masks, scores, logits = predictor.predict(
point_coords=input_point,
point_labels=input_label,
multimask_output=True
)
4. Visualize results
for i, mask in enumerate(masks):
color = np.array([30, 144, 255])
h, w = mask.shape
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
cv2.imwrite(f"mask_{i}.jpg", mask_image)
"""
)
Applications of segmentation in industry
Image segmentation is a core technology for many industrial applications:
| Field | Application Scenarios | Task Types |
|---|---|---|
| Medical Imaging | Tumor Segmentation, Organ Measurement | Semantic Segmentation |
| Autonomous Driving | Drivable Area, Lane Line Recognition | Semantic Segmentation |
| Remote sensing imagery | Land cover classification, building extraction | Semantic segmentation |
| Smart manufacturing | Defect detection, part measurement | Instance segmentation |
| Video editing | Person cutout, background replacement | Instance Segmentation |
Diffusion Models
Diffusion models are the core technology for AI image generation, and Stable Diffusion, DALL-E 3, and Midjourney are all based on it.
Forward Diffusion Process (Noising)
Forward diffusion is a simple process: gradually adding Gaussian noise to an image until it becomes pure noise.
This is a deterministic process, where only a small amount of noise is added at each step, and we can precisely calculate the amount of noise at any moment using mathematical formulas.
Instance
============================================
Demonstrate the forward process of diffusion models (noise addition)
============================================
import
numpy
as
np
import
matplotlib.
pyplot
as
plt
class
ForwardDiffusion:
"""Demonstration of the forward diffusion process"""
def
init
(
self
,
num_timesteps:
int
=
1000
)
:
self
.
num_timesteps
=
num_timesteps
Define beta scheduling (linear increase from beta_start to beta_end)
self
.
beta_start
=
0.0001
self
.
beta_end
=
0.02
self
.
betas
=
np.
linspace
(
self
.
beta_start
,
self
.
beta_end
,
num_timesteps
)
Calculate alpha and alpha_bar
self
.
alphas
=
1.0
self
.
betas
self
.
alphas_bar
=
np.
cumprod
(
self
.
alphas
)
def
q_sample
(
self
,
x0: np.
ndarray
,
t:
int
)
tuple
:
"""
Calculate xt at time t directly from x0
Parameters:
x0: original image (H, W, 3)
t: timestep (0 <= t < num_timesteps)
Returns:
xt: image at time t
noise: added noise
"""
sqrt_alpha_bar_t
=
np.
sqrt
(
self
.
alphas_bar
[
t
]
)
sqrt_one_minus_alpha_bar_t
=
np.
sqrt
(
1
self
.
alphas_bar
[
t
]
)
Generate random noise of the same shape
noise
=
np.
random
.
randn
(
*x0.
shape
)
Calculate xt in one step
xt
=
sqrt_alpha_bar_t * x0 + sqrt_one_minus_alpha_bar_t * noise
return
xt
,
noise
Create a simple test image: a bright circle in the middle
def
create_diffusion_test_image
(
)
:
h
,
w
=
64
,
64
x
=
np.
linspace
(
1
,
1
,
w
)
y
=
np.
linspace
(
1
,
1
,
h
)
xx
,
yy
=
np.
meshgrid
(
x
,
y
)
r
=
np.
sqrt
(
xx**
2
- yy**
2
)
image
=
np.
exp
(
-r**
2
/
0.1
)
Gaussian distribution bright circle
image
=
(
image - image.
min
(
)
)
/
(
image.
max
(
)
- image.
min
(
)
)
Normalize to [0, 1]
image
=
np.
stack
(
[
image
,
image*
0.8
,
image*
0.5
]
,
axis
=
1
)
becomes 3 channels
return
image
(
"="
60
)
(
"RUNOOB Forward Diffusion Process Demonstration"
)
(
"="
60
)
Initialize diffusion process
diffusion
=
ForwardDiffusion
(
num_timesteps
=
1000
)
Create a test image
x0
=
create_diffusion_test_image
(
)
(
f
Original image shape: {x0.shape}
)
Display the denoising results at different timesteps
timesteps_to_show
=
[
0
,
100
,
200
,
300
,
500
,
1000
]
(
"Noise level at different time steps:"
)
for
t
in
timesteps_to_show:
if
t
<
1000
:
xt
,
noise
=
diffusion.
q_sample
(
x0
,
t
)
alpha_bar
=
diffusion.
alphas_bar
[
t
]
(
f
" t={t:4d}: alpha_bar={alpha_bar:.4f}, Signal-to-Noise Ratio={alpha_bar/(1-alpha_bar):.4f}"
)
else
:
(
f
" t={t:4d}: pure noise"
)
(
"\nCore formula of forward diffusion:"
)
(
" q(x_t | x_0) = N(x_t; sqrt(alpha_bar_t) * x0, (1 - alpha_bar_t) * I)"
)
(
"\nThis formula allows us to calculate x_t at any time t directly from x0, without step-by-step iteration!"
)
Reverse denoising process
The reverse process is the inverse of the forward process: starting from pure noise, gradually predicting and removing noise to finally obtain the image.
This is what we train the model to learn: given xt and t, predict what noise was added.
Training objective: minimize the mean squared error between the noise predicted by the model and the true noise.
U-Net architecture
The core of the diffusion model is a U-Net network, which has a U-shape: downsampling compression on the left, and upsampling recovery on the right.
The key of U-Net is the Skip Connection, which directly passes features from the downsampling stage to the corresponding layer in the upsampling stage, preserving detail information.
DDPM vs DDIM sampling
After training the model, we need to sample and generate images from noise, and different samplers have different speeds and qualities.
| Sampler | Full name | Steps | Features |
|---|---|---|---|
| DDPM | Denoising Diffusion Probabilistic Models | 1000 | Original method, good quality but slow |
| DDIM | Denoising Diffusion Implicit Models | 50-100 | Deterministic sampling, fast speed |
| LMS | Linear Multistep Method | 30-50 | Fast speed, good quality |
| DPM-Solver | DPM-Solver | 10-20 | Ultra-fast, good results in just a few steps |
The current Stable Diffusion defaults to DPM-Solver++, usually achieving high-quality results in 20-30 steps, which is dozens of times faster than the earliest DDPM.
Stable Diffusion Architecture
Stable Diffusion does not work directly in pixel space, but in the latent space, which makes it faster and more efficient.
The complete Stable Diffusion consists of three parts:
-
VAE (Variational Autoencoder): Compresses an image into a latent vector, or reconstructs an image from a latent vector.
-
UNet: The core denoising network, which receives the latent vector, timestep, and prompt embedding to predict noise.
-
Text Encoder (CLIP): Converts text prompts into embeddings, telling the model what to generate.
Example
============================================
Stable Diffusion Concept Demonstration
Demonstrates the complete generation process
============================================
class
SimpleStableDiffusion:
Simplified Stable Diffusion concept demonstration
def
init
(
self
)
:
(
"Stable Diffusion Concept Demo Initialization"
)
def
encode_text
(
self
,
prompt:
str
)
:
"""Encode text prompt"""
(
f
"Encoded prompt: '{prompt}'"
)
return
"text_embedding"
def
encode_image
(
self
,
image: np.
ndarray
)
:
"""VAE encodes image to latent space"""
(
"Encode image to latent space (VAE encoder)"
)
return
"latent_code"
def
decode_latent
(
self
,
latent:
str
)
:
"""VAE decodes images from the latent space"""
(
"Decoding image from latent space (VAE decoder)"
)
return
"decoded_image"
def
denoise_step
(
self
,
latent:
str
,
text_embedding:
str
,
t:
int
)
:
"One step denoising"
(
f
" Denoising step t={t}"
)
return
"denoised_latent"
def
generate
(
self
,
prompt:
str
,
num_inference_steps:
int
=
50
)
:
"""Complete generation process"""
(
"="
60
)
(
f
"Starting generation: '{prompt}'"
)
(
"="
60
)
1. Encode text
text_emb
=
self
.
encode_text
(
prompt
)
2. Start from random noise
(
"Initializing random noise..."
)
latent
=
"random_noise"
3. Step-by-step denoising
(
f
"\nStarting denoising loop ({num_inference_steps} steps):"
)
for
t
in
reversed
(
range
(
num_inference_steps
)
)
:
latent
=
self
.
denoise_step
(
latent
,
text_emb
,
t
)
4. Decode to get the image
(
"\nDecoding latent vector to image..."
)
image
=
self
.
decode_latent
(
latent
)
(
"\nGeneration complete!"
)
return
image
Demonstration generation process
sd
=
SimpleStableDiffusion
(
)
image
=
sd.
generate
(
prompt
=
A cute orange cat in the garden
,
num_inference_steps
=
20
)
============================================
Code examples for actual use of Stable Diffusion
============================================
(
"\n"
"="
60
)
(
"Code example for actual use of Stable Diffusion:"
)
(
"="
60
)
(
"""
Installation: pip install diffusers transformers accelerate torch
from diffusers import StableDiffusionPipeline
import torch
1. Load the model
model_id = "runwayml/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(
model_id,
torch_dtype=torch.float16
)
pipe = pipe.to("cuda")
2. Text-to-Image
prompt = "a cute orange cat in a garden"
image = pipe(prompt).images[0]
3. Save results
image.save("cat_garden.png")
4. Image-to-image
from diffusers import StableDiffusionImg2ImgPipeline
from PIL import Image
img_pipe = StableDiffusionImg2ImgPipeline.from_pretrained(
model_id,
torch_dtype=torch.float16
).to("cuda")
init_image = Image.open("input.jpg").convert("RGB")
init_image = init_image.resize((512, 512))
image = img_pipe(
prompt="make it look like a painting",
image=init_image,
strength=0.75 # degree of change
).images[0]
image.save("painted.png")
5. Inpainting (Local Modification)
from diffusers import StableDiffusionInpaintPipeline
inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained(
model_id,
torch_dtype=torch.float16
).to("cuda")
image = inpaint_pipe(
prompt="put a hat on the cat",
image=init_image,
mask_image=mask_image # Mask image, the white area is the part to be modified
).images[0]
"""
)
CLIP: Multimodal Alignment Basics
CLIP (Contrastive Language-Image Pre-training) is a work published by OpenAI in 2021, which first aligned text and images into the same vector space.
Contrastive learning principle
CLIP's training method is contrastive learning: making the similarity of correct image-text pairs high and the similarity of incorrect image-text pairs low.
During training, a batch contains N images and N texts (one-to-one correspondence), forming N×N possible image-text pairs.
The diagonal represents the matched positive samples, and all others are unmatched negative samples.
The training objective is: to make the similarity of positive samples as large as possible and the similarity of negative samples as small as possible.
Image-text alignment training
CLIP includes two encoders:
-
1. Image Encoder: Encodes images into vectors (can be ResNet or ViT).
-
2. Text Encoder: Encodes text into vectors (Transformer).
After projecting both vectors into the same space, the degree of image-text matching is calculated using cosine similarity.
Example
============================================
CLIP Concept Demonstration: Contrastive Learning and Image-Text Alignment
============================================
import
torch
import
torch.
nn
.
functional
as
F
class
SimpleCLIP:
"""Simplified CLIP concept demonstration"""
def
init
(
self
,
embed_dim:
int
=
512
)
:
self
.
embed_dim
=
embed_dim
Simple simulation: not real encoding, just random projection
(
"CLIP concept demonstration initialization"
)
(
f
"Embedding dimension: {embed_dim}"
)
def
encode_image
(
self
,
image:
str
)
torch.
Tensor
:
"""Simulated image encoding"""
In practice, this would be a Vision Transformer or ResNet
return
torch.
randn
(
1
,
self
.
embed_dim
)
def
encode_text
(
self
,
text:
str
)
torch.
Tensor
:
"""Simulate text encoding"""
In reality, this is a Text Transformer
return
torch.
randn
(
1
,
self
.
embed_dim
)
def
compute_similarity
(
self
,
image_emb: torch.
Tensor
,
text_emb: torch.
Tensor
)
float
:
"""Calculate cosine similarity"""
image_emb
=
F.
normalize
(
image_emb
,
dim
=
1
)
text_emb
=
F.
normalize
(
text_emb
,
dim
=
1
)
return
(
image_emb
@
text_emb.
T
)
.
item
(
)
Demonstrate CLIP inference process
(
"="
60
)
(
"RUNOOB CLIP Zero-shot Classification Demo"
)
(
"="
60
)
clip
=
SimpleCLIP
(
embed_dim
=
512
)
Assume there is an image
(
"\n1. Encoding image..."
)
image_emb
=
clip.
encode_image
(
"A picture of a cat"
)
Assume there are several candidate categories
candidates
=
[
"A picture of a dog"
,
"A picture of a cat"
,
"A car"
,
"a person"
]
(
f
"\n2. Candidate encoded text: {candidates}"
)
Calculate similarity
(
"\n3. Calculate text and image similarity:"
)
for
text
in
candidates:
text_emb
=
clip.
encode_text
(
text
)
sim
=
clip.
compute_similarity
(
image_emb
,
text_emb
)
(
f
" '{text}' → Similarity: {sim:.3f}"
)
(
(In practice, 'a picture of a cat' will have the highest similarity)
)
============================================
Code example using CLIP in practice
============================================
(
"\n"
"="
60
)
(
"Code example using CLIP in practice:"
)
(
"="
60
)
(
"""
Installation: pip install clip torch torchvision
import clip
import torch
from PIL import Image
1. Load model
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
2. Prepare image
image = preprocess(Image.open("cat.jpg")).unsqueeze(0).to(device)
3. Prepare text
text = clip.tokenize([
"a photo of a dog",
"a photo of a cat",
"a photo of a car",
"a photo of a person"
]).to(device)
4. Inference
with torch.no_grad():
image_features = model.encode_image(image)
text_features = model.encode_text(text)
logits_per_image, logits_per_text = model(image, text)
probs = logits_per_image.softmax(dim=-1).cpu().numpy()
5. Output results
print("Prediction probabilities:")
for i, p in enumerate(probs[0]):
print(f" {i+1}. {p:.2%}")
"""
)
Zero-Shot Classification Capability
The most exciting capability of CLIP is Zero-Shot Classification: it can classify directly without needing to train on the target dataset.
Traditional ImageNet trained models can only classify the 1000 classes of ImageNet, and adding new classes requires retraining.
CLIP can use any text description to define a class, such as: "a photo of a cat", "an orange cat sitting on the grass", or "a sketch of a cat".
The significance of CLIP is not just in zero-shot classification, but in establishing a universal "vision-language" interface upon which many subsequent models (such as Stable Diffusion and vision-language models) are built.
Vision-Language Model (VLM)
Vision-Language Model (Vision-Language Model, VLM) combines image understanding and language generation, allowing the model to "talk about pictures."
LLaVA Architecture
LLaVA (Large Language and Vision Assistant) is an open-source VLM with a simple and clear design, making it suitable for beginners to learn.
The LLaVA architecture is divided into three parts:
-
1. Vision Encoder: The CLIP visual encoder, which converts images into embeddings.
-
2. Projection Layer: Projects the visual embeddings into the same dimension as the LLM input.
-
3. LLM: A large language model (such as Vicuna or LLaMA) that receives the concatenated image and text input to generate a response.
Training in two steps:
-
1. Pre-training stage: Only train the Projection Layer using a large amount of image-text pairs for alignment.
-
2. Instruction fine-tuning stage: Train the entire model using a visual instruction dataset (such as LLaVA-Instruct).
Connection between the visual Encoder and LLM
The key to connecting vision and language is: representing images as a sequence of tokens that the language model can understand.
There are several common connection methods:
| Method | Feature | Model representation |
|---|---|---|
| Special token | Use one [IMG] token to represent the entire image | Early models |
| Sequence concatenation | Directly concatenate image patch embeddings before the text | LLaVA, GPT-4V |
| Cross-attention | Incorporating cross-attention on visual features in LLMs | BLIP-2, Flamingo |
Examples
============================================
Visual Language Model (VLM) concept demonstration
Demonstrating how to concatenate visual and language inputs
============================================
class
SimpleVLM:
"""Simplified Vision-Language Model"""
def
init
(
self
,
vocab_size:
int
=
50000
,
hidden_size:
int
=
768
)
:
self
.
vocab_size
=
vocab_size
self
.
hidden_size
=
hidden_size
(
"Simplified VLM Initialization"
)
def
encode_vision
(
self
,
image:
str
)
torch.
Tensor
:
"""Encode image into sequence"""
Assume there are 256 visual tokens
return
torch.
randn
(
1
,
256
,
self
.
hidden_size
)
def
encode_text
(
self
,
text:
str
)
torch.
Tensor
:
"""Encodes text into a sequence"""
Assume the text has 16 tokens
return
torch.
randn
(
1
,
16
,
self
.
hidden_size
)
def
generate
(
self
,
image:
str
,
question:
str
)
str
:
"""Image and text concatenation to generate answers"""
(
"="
60
)
(
f
"Question: {question}"
)
(
"="
60
)
1. Encode image and text
(
"\n1. Encoding image..."
)
vision_emb
=
self
.
encode_vision
(
image
)
(
"2. Encoding text..."
)
text_emb
=
self
.
encode_text
(
question
)
3. Concatenate: [Visual Sequence] + [Text Sequence]
(
"\n3. Concatenate visual and text sequences..."
)
(
f
Vision embedding shape: {vision_emb.shape}
)
(
f
" Text embedding shape: {text_emb.shape}"
)
combined
=
torch.
cat
(
[
vision_emb
,
text_emb
]
,
dim
=
1
)
(
f
" Concatenated shape: {combined.shape}"
)
4. LLM generates answer
(
"\n4. LLM generates answer..."
)
return
"This is a cute orange cat, and it looks very happy."
Demonstrate VLM Q&A
vlm
=
SimpleVLM
(
)
answer
=
vlm.
generate
(
image
=
"A photo of an orange cat"
,
question
=
What is in this picture? Please describe it.
)
(
f
"\nAnswer: {answer}"
)
============================================
Code example for actual use of LLaVA
============================================
(
"\n"
"="
60
)
(
"Code example for actual use of LLaVA:"
)
(
"="
60
)
(
"""
LLaVA requires a large amount of VRAM, it is recommended to use the transformers or llava library
from transformers import AutoProcessor, AutoModelForVisionAndLanguageGeneration
import torch
from PIL import Image
1. Load model and processor
model_id = "llava-hf/llava-1.5-7b-hf"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForVisionAndLanguageGeneration.from_pretrained(
model_id,
torch_dtype=torch.float16,
device_map="auto"
)
2. Prepare input
image = Image.open("cat.jpg")
prompt = "USER:What is in this picture? Please describe it. ASSISTANT:"
inputs = processor(images=image, text=prompt, return_tensors="pt").to("cuda")
3. Generate
with torch.no_grad():
output = model.generate(**inputs, max_new_tokens=500)
answer = processor.decode(output[0], skip_special_tokens=True)
print(answer)
"""
)
Practical: Complete Project for Image Classification + Object Detection
Now we will integrate the knowledge learned before to create a complete practical project.
Example
============================================
Practical Project: Complete Vision AI Pipeline
Includes image classification, object detection, and result visualization
============================================
import
torch
import
torch.
nn
as
nn
import
torch.
nn
.
functional
as
F
from
torch.
utils
.
data
import
Dataset
,
DataLoader
import
numpy
as
np
from
PIL
import
Image
import
json
from
pathlib
import
Path
class
VisionPipeline:
"""
A complete visual AI pipeline
Functions:
1. Image classification
2. Object detection
3. Results Summary and Visualization
"""
def
init
(
self
,
device:
str
=
"cpu"
)
:
self
.
device
=
device
self
.
classifier
=
None
self
.
detector
=
None
(
f
"RUNOOB Vision Pipeline Initialization (Device: {device})"
)
def
build_classifier
(
self
,
num_classes:
int
=
10
)
:
"""Build image classifier"""
(
"\nBuilding image classifier..."
)
Use the previously defined SimpleCNN
self
.
classifier
=
SimpleCNN
(
num_classes
=
num_classes
)
.
to
(
self
.
device
)
(
"Classifier built successfully!"
)
return
self
def
build_detector
(
self
)
:
"""Build object detector"""
(
"Building object detector..."
)
self
.
detector
=
SimpleYOLO
(
)
(
"Detector built successfully!"
)
return
self
def
load_pretrained_weights
(
self
,
classifier_path:
str
=
None
)
:
"""Load pre-trained weights"""
if
classifier_path
and
self
.
classifier
:
(
f
"\nLoading classifier weights: {classifier_path}"
)
In practice: self.classifier.load_state_dict(torch.load(classifier_path))
return
self
def
classify_image
(
self
,
image: np.
ndarray
)
tuple
:
"""
Image classification
Returns:
(pred_class_id, pred_class_name, confidence)
"""
if
self
.
classifier
is
None
:
raise
ValueError
(
"First build the classifier: build_classifier()"
)
Preprocessing
if
isinstance
(
image
,
np.
ndarray
)
:
if
image.
ndim
==
2
:
Grayscale image
image
=
np.
stack
(
[
image
]
3
,
axis
=
1
)
image
=
torch.
from_numpy
(
image
)
.
permute
(
2
,
0
,
1
)
.
float
(
)
/
255.0
image
=
F.
interpolate
(
image.
unsqueeze
(
0
)
,
size
=
(
32
,
32
)
,
mode
=
'bilinear'
)
image
=
image.
to
(
self
.
device
)
Inference
self
.
classifier
.
eval
(
)
with
torch.
no_grad
(
)
:
logits
=
self
.
classifier
(
image
)
probs
=
F.
softmax
(
logits
,
dim
=
1
)
confidence
,
pred_idx
=
probs.
max
(
dim
=
1
)
Return result
class_names
=
[
'airplane'
,
'automobile'
,
'bird'
,
'cat'
,
'deer'
,
'dog'
,
'frog'
,
'horse'
,
'ship'
,
'truck'
]
pred_class
=
class_names
[
pred_idx.
item
(
)
]
return
pred_idx.
item
(
)
,
pred_class
,
confidence.
item
(
)
def
detect_objects
(
self
,
image: np.
ndarray
)
list
:
"Object Detection"
if
self
.
detector
is
None
:
raise
ValueError
(
"Please build the detector first: build_detector()"
)
Use simulation detection
return
self
.
detector
.
predict_dummy
(
image
)
def
process_image
(
self
,
image: np.
ndarray
)
dict
:
"""
Process a complete image
Returns:
A dictionary containing all results
"""
(
"\n"
"="
60
)
(
"Starting image processing"
)
(
"="
60
)
results
=
{
}
1. Image Classification
if
self
.
classifier
is
not
None
:
(
"[1/3] Running image classification..."
)
class_id
,
class_name
,
conf
=
self
.
classify_image
(
image
)
results
[
'classification'
]
=
{
'class_id'
: class_id
,
'class_name'
: class_name
,
'confidence'
: conf
}
(
f
" → Classification result: {class_name} (Confidence: {conf:.2%})"
)
2. Object Detection
if
self
.
detector
is
not
None
:
(
"\n[2/3] Running object detection..."
)
detections
=
self
.
detect_objects
(
image
)
results
[
'detections'
]
=
detections
(
f
" → Detected {len(detections)} objects:"
)
for
det
in
detections:
(
f
" - {det['class_name']} ({det['score']:.2f})"
)
3. Visualization
(
"\n[3/3] Generating visualization..."
)
if
self
.
detector
is
not
None
:
vis_image
=
self
.
detector
.
visualize
(
image
,
detections
)
results
[
'visualization'
]
=
vis_image
(
" → Visualization complete"
)
(
"\n"
"="
60
)
(
"Image processing complete!"
)
(
"="
60
)
return
results
def
save_results
(
self
,
results:
dict
,
output_dir:
str
=
"output"
)
:
"""Save results to file"""
output_path
=
Path
(
output_dir
)
output_path.
mkdir
(
exist_ok
=
True
)
Save JSON result
json_result
=
{
'classification'
: results.
get
(
'classification'
)
,
'detections'
:
[
{
k: v
for
k
,
v
in
det.
items
(
)
if
k
!=
'bbox'
}
for
det
in
results.
get
(
'detections'
,
[
]
)
]
}
with
open
(
output_path /
"results.json"
,
"w"
)
as
f:
json.
dump
(
json_result
,
f
,
indent
=
2
,
ensure_ascii
=
False
)
Save visualization image
if
'visualization'
in
results:
vis
=
Image.
fromarray
(
results
[
'visualization'
]
)
vis.
save
(
output_path /
"visualization.jpg"
)
(
f
"\nResults saved to: {output_path}/"
)
Complete training example
class
SimpleDataset
(
Dataset
)
:
"""Simple mock dataset"""
def
init
(
self
,
num_samples:
int
=
100
)
:
self
.
num_samples
=
num_samples
Generate fake data
self
.
images
=
torch.
randn
(
num_samples
,
3
,
32
,
32
)
self
.
labels
=
torch.
randint
(
0
,
10
,
(
num_samples
,
)
)
def
len
(
self
)
:
return
self
.
num_samples
def
getitem
(
self
,
idx
)
:
return
self
.
images
[
idx
]
,
self
.
labels
[
idx
]
def
train_classifier
(
pipeline: VisionPipeline
,
num_epochs:
int
=
5
)
:
"""Complete training process for the classifier"""
(
"\n"
"="
60
)
(
"Start training classifier"
)
(
"="
60
)
1. Prepare data
(
"\nPreparing dataset..."
)
train_dataset
=
SimpleDataset
(
1000
)
val_dataset
=
SimpleDataset
(
200
)
train_loader
=
DataLoader
(
train_dataset
,
batch_size
=
32
,
shuffle
=
True
)
val_loader
=
DataLoader
(
val_dataset
,
batch_size
=
32
)
(
f
"Training set: {len(train_dataset)} samples"
)
(
f
"Validation set: {len(val_dataset)} samples"
)
2. Optimizer and Loss Function
optimizer
=
torch.
optim
.
Adam
(
pipeline.
classifier
.
parameters
(
)
,
lr
=
1e-3
)
criterion
=
nn.
CrossEntropyLoss
(
)
3. Training Loop
(
"Starting training..."
)
for
epoch
in
range
(
num_epochs
)
:
pipeline.
classifier
.
train
(
)
total_loss
=
0.0
correct
=
0
total
=
0
for
images
,
labels
in
train_loader:
images
,
labels
=
images.
to
(
pipeline.
device
)
,
labels.
to
(
pipeline.
device
)
optimizer.
zero_grad
(
)
outputs
=
pipeline.
classifier
(
images
)
loss
=
criterion
(
outputs
,
labels
)
loss.
backward
(
)
optimizer.
step
(
)
total_loss +
=
loss.
item
(
)
_
,
predicted
=
outputs.
max
(
1
)
total +
=
labels.
size
(
0
)
correct +
=
predicted.
eq
(
labels
)
.
sum
(
)
.
item
(
)
train_acc
=
correct / total
avg_loss
=
total_loss /
len
(
train_loader
)
Validation
pipeline.
classifier
.
eval
(
)
correct
=
0
total
=
0
with
torch.
no_grad
(
)
:
for
images
,
labels
in
val_loader:
images
,
labels
=
images.
to
(
pipeline.
device
)
,
labels.
to
(
pipeline.
device
)
outputs
=
pipeline.
classifier
(
images
)
_
,
predicted
=
outputs.
max
(
1
)
total +
=
labels.
size
(
0
)
correct +
=
predicted.
eq
(
labels
)
.
sum
(
)
.
item
(
)
val_acc
=
correct / total
(
f
"Epoch {epoch+1}/{num_epochs} - "
f
"Loss: {avg_loss:.4f}, "
f
"Training accuracy: {train_acc:.2%}, "
f
"Validation accuracy: {val_acc:.2%}"
)
(
"Training completed!"
)
============================================
Run a complete practical project
============================================
(
"="
60
)
(
"RUNOOB Vision AI Complete Practical Project"
)
(
"="
60
)
1. Create pipeline
pipeline
=
VisionPipeline
(
device
=
"cuda"
if
torch.
cuda
.
is_available
(
)
else
"cpu"
)
2. Build model
pipeline.
build_classifier
(
num_classes
=
10
)
pipeline.
build_detector
(
)
3. Train Classifier
train_classifier
(
pipeline
,
num_epochs
=
3
)
4. Process image
test_image
=
create_test_image
(
)
results
=
pipeline.
process_image
(
test_image
)
5. Save results
pipeline.
save_results
(
results
,
output_dir
=
"runoob_output"
)
(
"\n"
"="
60
)
(
"Project execution completed!"
)
(
"="
60
)
(
"\nNext learning suggestions:"
)
(
" 1. Try training on a real dataset (such as CIFAR-10)"
)
(
" 2. Fine-tune using pre-trained models"
)
(
" 3. Try more complex model architectures"
)
(
" 4. Deploy to actual applications"
)