Computer Vision for Beginners: Building an Image Classifier
Computer vision enables AI to understand and process visual information. This guide walks through building your first image classifier.
What is Computer Vision?
Computer vision is the field of AI that trains computers to interpret and understand the visual world. Applications include:
- Image classification (what's in this photo?)
- Object detection (where are the objects?)
- Image segmentation (which pixels belong to which object?)
- Face recognition (who is this person?)
Setting Up
pip install tensorflow matplotlib numpy pillow
Loading Data
We'll use the CIFAR-10 dataset (60,000 32x32 color images in 10 classes):
import tensorflow as tf
from tensorflow import keras
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
# Normalize pixel values
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
Building a Convolutional Neural Network
model = keras.Sequential([
keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(32,32,3)),
keras.layers.MaxPooling2D(2,2),
keras.layers.Conv2D(64, (3,3), activation='relu'),
keras.layers.MaxPooling2D(2,2),
keras.layers.Flatten(),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
Training
history = model.fit(
x_train, y_train,
batch_size=64,
epochs=10,
validation_data=(x_test, y_test)
)
Using Transfer Learning
For better results with less data, use a pre-trained model:
base_model = keras.applications.MobileNetV2(
input_shape=(224,224,3),
include_top=False,
weights='imagenet'
)
base_model.trainable = False # Freeze base layers
model = keras.Sequential([
keras.layers.Resizing(224,224),
base_model,
keras.layers.GlobalAveragePooling2D(),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
Object Detection with YOLO
For detecting multiple objects in images, use YOLO (You Only Look Once):
pip install ultralytics
yolo predict model=yolov8n.pt source='image.jpg'
Real-World Application: Moroccan Agriculture
A team of Moroccan researchers built a vision system using transfer learning that:
- Identifies crop diseases from smartphone photos
- Achieves 94% accuracy on local crop varieties
- Works offline on mobile devices
- Helps farmers diagnose problems early
Next Steps
- Try real-time video processing
- Build a mobile app with on-device vision
- Explore image generation with diffusion models
Our AI Builder Bootcamp covers computer vision with real-world projects.