1
---
2
name: Computer Vision
3
description: Implement computer vision tasks including image classification, object detection, segmentation, and pose estimation using PyTorch and TensorFlow
4
---
5
6
# Computer Vision
7
8
## Overview
9
10
Computer vision enables machines to understand visual information from images and videos, powering applications like autonomous driving, medical imaging, and surveillance.
11
12
## When to Use
13
14
- Image classification and object recognition tasks
15
- Object detection and localization in images
16
- Semantic or instance segmentation projects
17
- Pose estimation and human activity recognition
18
- Face recognition and biometric systems
19
- Medical imaging analysis and diagnostics
20
21
## Computer Vision Tasks
22
23
- **Image Classification**: Categorizing images into classes
24
- **Object Detection**: Locating and classifying objects in images
25
- **Semantic Segmentation**: Pixel-level classification
26
- **Instance Segmentation**: Detecting individual object instances
27
- **Pose Estimation**: Identifying human body joints
28
- **Face Recognition**: Identifying individuals in images
29
30
## Popular Architectures
31
32
- **Classification**: ResNet, VGG, EfficientNet, Vision Transformer
33
- **Detection**: YOLO, Faster R-CNN, SSD, RetinaNet
34
- **Segmentation**: U-Net, DeepLab, Mask R-CNN
35
- **Pose**: OpenPose, PoseNet, HRNet
36
37
## Python Implementation
38
39
```python
40
import numpy as np
41
import pandas as pd
42
import matplotlib.pyplot as plt
43
import matplotlib.patches as patches
44
from PIL import Image, ImageDraw
45
import torch
46
import torch.nn as nn
47
from torch.utils.data import DataLoader, TensorDataset
48
from torchvision import transforms, models, datasets
49
import tensorflow as tf
50
from tensorflow import keras
51
from tensorflow.keras import layers
52
import cv2
53
from sklearn.metrics import accuracy_score, confusion_matrix
54
import seaborn as sns
55
import warnings
56
warnings.filterwarnings('ignore')
57
58
print("=== 1. Image Classification CNN ===")
59
60
# Define image classification model
61
class ImageClassifierCNN(nn.Module):
62
def __init__(self, num_classes=10):
63
super().__init__()
64
self.features = nn.Sequential(
65
nn.Conv2d(3, 32, kernel_size=3, padding=1),
66
nn.ReLU(inplace=True),
67
nn.BatchNorm2d(32),
68
nn.MaxPool2d(2, 2),
69
70
nn.Conv2d(32, 64, kernel_size=3, padding=1),
71
nn.ReLU(inplace=True),
72
nn.BatchNorm2d(64),
73
nn.MaxPool2d(2, 2),
74
75
nn.Conv2d(64, 128, kernel_size=3, padding=1),
76
nn.ReLU(inplace=True),
77
nn.BatchNorm2d(128),
78
nn.MaxPool2d(2, 2),
79
)
80
81
self.classifier = nn.Sequential(
82
nn.Linear(128 * 4 * 4, 256),
83
nn.ReLU(inplace=True),
84
nn.Dropout(0.5),
85
nn.Linear(256, num_classes)
86
)
87
88
def forward(self, x):
89
x = self.features(x)
90
x = x.view(x.size(0), -1)
91
x = self.classifier(x)
92
return x
93
94
model = ImageClassifierCNN(num_classes=10)
95
print(f"Model parameters: {sum(p.numel() for p in model.parameters()):,}")
96
97
# 2. Object Detection setup
98
print("\n=== 2. Object Detection Framework ===")
99
100
class ObjectDetector(nn.Module):
101
def __init__(self):
102
super().__init__()
103
# Backbone
104
self.backbone = nn.Sequential(
105
nn.Conv2d(3, 32, 3, padding=1),
106
nn.ReLU(),
107
nn.MaxPool2d(2, 2),
108
nn.Conv2d(32, 64, 3, padding=1),
109
nn.ReLU(),
110
nn.MaxPool2d(2, 2),
111
)
112
113
# Bounding box regression
114
self.bbox_head = nn.Sequential(
115
nn.Linear(64 * 8 * 8, 128),
116
nn.ReLU(),
117
nn.Linear(128, 4) # x, y, w, h
118
)
119
120
# Class prediction
121
self.class_head = nn.Sequential(
122
nn.Linear(64 * 8 * 8, 128),
123
nn.ReLU(),
124
nn.Linear(128, 10) # 10 classes
125
)
126
127
def forward(self, x):
128
features = self.backbone(x)
129
features_flat = features.view(features.size(0), -1)
130
131
bboxes = self.bbox_head(features_flat)
132
classes = self.class_head(features_flat)
133
134
return bboxes, classes
135
136
detector = ObjectDetector()
137
print(f"Detector parameters: {sum(p.numel() for p in detector.parameters()):,}")
138
139
# 3. Semantic Segmentation
140
print("\n=== 3. Semantic Segmentation U-Net ===")
141
142
class UNet(nn.Module):
143
def __init__(self, num_classes=5):
144
super().__init__()
145
# Encoder
146
self.enc1 = self._conv_block(3, 32)
147
self.pool1 = nn.MaxPool2d(2, 2)
148
self.enc2 = self._conv_block(32, 64)
149
self.pool2 = nn.MaxPool2d(2, 2)
150
151
# Bottleneck
152
self.bottleneck = self._conv_block(64, 128)
153
154
# Decoder
155
self.upconv2 = nn.ConvTranspose2d(128, 64, 2, stride=2)
156
self.dec2 = self._conv_block(128, 64)
157
self.upconv1 = nn.ConvTranspose2d(64, 32, 2, stride=2)
158
self.dec1 = self._conv_block(64, 32)
159
160
# Final output
161
self.out = nn.Conv2d(32, num_classes, 1)
162
163
def _conv_block(self, in_channels, out_channels):
164
return nn.Sequential(
165
nn.Conv2d(in_channels, out_channels, 3, padding=1),
166
nn.ReLU(inplace=True),
167
nn.Conv2d(out_channels, out_channels, 3, padding=1),
168
nn.ReLU(inplace=True)
169
)
170
171
def forward(self, x):
172
enc1 = self.enc1(x)
173
enc2 = self.enc2(self.pool1(enc1))
174
bottleneck = self.bottleneck(self.pool2(enc2))
175
176
dec2 = self.dec2(torch.cat([self.upconv2(bottleneck), enc2], 1))
177
dec1 = self.dec1(torch.cat([self.upconv1(dec2), enc1], 1))
178
179
return self.out(dec1)
180
181
unet = UNet(num_classes=5)
182
print(f"U-Net parameters: {sum(p.numel() for p in unet.parameters()):,}")
183
184
# 4. Transfer Learning
185
print("\n=== 4. Transfer Learning with Pre-trained Models ===")
186
187
try:
188
# Load pre-trained ResNet18
189
pretrained_model = models.resnet18(pretrained=True)
190
num_ftrs = pretrained_model.fc.in_features
191
pretrained_model.fc = nn.Linear(num_ftrs, 10)
192
193
print(f"Pre-trained ResNet18 adapted for 10 classes")
194
print(f"Parameters: {sum(p.numel() for p in pretrained_model.parameters()):,}")
195
except:
196
print("Pre-trained models not available")
197
198
# 5. Image preprocessing and augmentation
199
print("\n=== 5. Image Preprocessing and Augmentation ===")
200
201
transform_basic = transforms.Compose([
202
transforms.Resize((224, 224)),
203
transforms.ToTensor(),
204
transforms.Normalize(mean=[0.485, 0.456, 0.406],
205
std=[0.229, 0.224, 0.225])
206
])
207
208
transform_augmented = transforms.Compose([
209
transforms.RandomRotation(20),
210
transforms.RandomHorizontalFlip(),
211
transforms.ColorJitter(brightness=0.2, contrast=0.2),
212
transforms.RandomAffine(degrees=0, translate=(0.1, 0.1)),
213
transforms.Resize((224, 224)),
214
transforms.ToTensor(),
215
transforms.Normalize(mean=[0.485, 0.456, 0.406],
216
std=[0.229, 0.224, 0.225])
217
])
218
219
print("Augmentation transforms defined")
220
221
# 6. Synthetic image data
222
print("\n=== 6. Synthetic Image Data Creation ===")
223
224
def create_synthetic_images(num_images=100, img_size=32):
225
"""Create synthetic images with shapes"""
226
images = []
227
labels = []
228
229
for _ in range(num_images):
230
img = np.ones((img_size, img_size, 3)) * 255
231
232
# Randomly draw shapes
233
shape_type = np.random.randint(0, 3)
234
235
if shape_type == 0: # Circle
236
center = (np.random.randint(5, img_size-5), np.random.randint(5, img_size-5))
237
radius = np.random.randint(3, 10)
238
cv2.circle(img, center, radius, (0, 0, 0), -1)
239
labels.append(0)
240
241
elif shape_type == 1: # Rectangle
242
pt1 = (np.random.randint(0, img_size-10), np.random.randint(0, img_size-10))
243
pt2 = (pt1[0] + np.random.randint(5, 15), pt1[1] + np.random.randint(5, 15))
244
cv2.rectangle(img, pt1, pt2, (0, 0, 0), -1)
245
labels.append(1)
246
247
else: # Triangle
248
pts = np.array([[np.random.randint(0, img_size), np.random.randint(0, img_size)],
249
[np.random.randint(0, img_size), np.random.randint(0, img_size)],
250
[np.random.randint(0, img_size), np.random.randint(0, img_size)]])
251
cv2.drawContours(img, [pts], 0, (0, 0, 0), -1)
252
labels.append(2)
253
254
images.append(img.astype(np.float32) / 255.0)
255
256
return np.array(images), np.array(labels)
257
258
X_images, y_labels = create_synthetic_images(num_images=300, img_size=32)
259
print(f"Synthetic dataset: {X_images.shape}, Labels: {y_labels.shape}")
260
print(f"Class distribution: {np.bincount(y_labels)}")
261
262
# 7. Visualization
263
print("\n=== 7. Visualization ===")
264
265
fig, axes = plt.subplots(3, 3, figsize=(12, 10))
266
267
# Display synthetic images
268
for i in range(9):
269
idx = i % len(X_images)
270
axes[i // 3, i % 3].imshow(X_images[idx])
271
axes[i // 3, i % 3].set_title(f"Class {y_labels[idx]}")
272
axes[i // 3, i % 3].axis('off')
273
274
plt.suptitle("Synthetic Image Dataset", fontsize=14, fontweight='bold')
275
plt.tight_layout()
276
plt.savefig('synthetic_images.png', dpi=100, bbox_inches='tight')
277
print("Synthetic images saved as 'synthetic_images.png'")
278
279
# 8. Model architectures comparison
280
print("\n=== 8. Architecture Comparison ===")
281
282
architectures_info = {
283
'CNN': ImageClassifierCNN(),
284
'ObjectDetector': ObjectDetector(),
285
'U-Net': UNet(),
286
}
287
288
arch_data = {
289
'Architecture': list(architectures_info.keys()),
290
'Parameters': [sum(p.numel() for p in m.parameters()) for m in architectures_info.values()],
291
'Use Case': ['Classification', 'Object Detection', 'Segmentation']
292
}
293
294
arch_df = pd.DataFrame(arch_data)
295
print("\nArchitecture Comparison:")
296
print(arch_df.to_string(index=False))
297
298
# Visualization
299
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
300
301
# Parameters comparison
302
axes[0].barh(arch_df['Architecture'], arch_df['Parameters'], color='steelblue')
303
axes[0].set_xlabel('Number of Parameters')
304
axes[0].set_title('Model Complexity Comparison')
305
axes[0].set_xscale('log')
306
307
# Use cases
308
use_cases = ['Classification', 'Detection', 'Segmentation',
309
'Classification', 'Detection', 'Segmentation']
310
colors_map = {'Classification': 'green', 'Detection': 'orange', 'Segmentation': 'red'}
311
bar_colors = [colors_map[uc] for uc in arch_df['Use Case']]
312
axes[1].bar(arch_df['Architecture'], [1, 1, 1], color=bar_colors, alpha=0.7)
313
axes[1].set_ylabel('Primary Task')
314
axes[1].set_title('Architecture Use Cases')
315
axes[1].set_ylim([0, 1.5])
316
317
plt.tight_layout()
318
plt.savefig('cv_architecture_comparison.png', dpi=100, bbox_inches='tight')
319
print("\nArchitecture comparison saved as 'cv_architecture_comparison.png'")
320
321
# 9. Bounding box visualization
322
print("\n=== 9. Bounding Box Visualization ===")
323
324
fig, ax = plt.subplots(figsize=(10, 8))
325
ax.imshow(X_images[0])
326
327
# Draw sample bounding boxes
328
bboxes = [
329
(5, 5, 15, 15), # x1, y1, x2, y2
330
(18, 10, 28, 20),
331
(8, 20, 18, 28)
332
]
333
334
for bbox in bboxes:
335
rect = patches.Rectangle((bbox[0], bbox[1]), bbox[2]-bbox[0], bbox[3]-bbox[1],
336
linewidth=2, edgecolor='red', facecolor='none')
337
ax.add_patch(rect)
338
339
ax.set_title('Bounding Box Detection Example')
340
ax.axis('off')
341
plt.savefig('bounding_boxes.png', dpi=100, bbox_inches='tight')
342
print("Bounding box visualization saved as 'bounding_boxes.png'")
343
344
print("\nComputer vision setup completed!")
345
```
346
347
## Common CV Architectures
348
349
- **Classification**: ResNet, EfficientNet, Vision Transformer
350
- **Detection**: YOLO v5, Faster R-CNN, RetinaNet
351
- **Segmentation**: U-Net, DeepLab v3, Mask R-CNN
352
- **Tracking**: SORT, DeepSORT, ByteTrack
353
354
## Image Preprocessing
355
356
- Resizing to standard dimensions
357
- Normalization with ImageNet stats
358
- Data augmentation (rotation, flip, crop)
359
- Color space conversion
360
361
## Evaluation Metrics
362
363
- **Classification**: Accuracy, Precision, Recall, F1
364
- **Detection**: mAP (mean Average Precision), IoU
365
- **Segmentation**: IoU, Dice coefficient, Hausdorff distance
366
367
## Deliverables
368
369
- Trained vision model
370
- Inference pipeline
371
- Performance evaluation
372
- Visualization results
373
- Model optimization report
374
- Deployment guide
375