Deep Learning for Vision Lab Manual 2024
Deep Learning for Vision Lab Manual 2024
Aim:
The aim of this program is to perform basic image processing operations, including Feature
Representation and Feature Extraction. Specifically, the program will:
Algorithm:
1. Load Image: Load the input image from the file system.
2. Convert to Grayscale: Convert the image to grayscale to simplify processing, as color
information isn't necessary for edge detection and corner detection.
3. Edge Detection: Apply the Canny edge detection algorithm to highlight the boundaries
(edges) in the image.
4. Feature Extraction (Corners): Use Harris Corner Detection to identify key points
(corners) in the image. These are points where there is a significant change in intensity.
5. Display Results: Show the original image, edge-detected image, and the image with
corners highlighted.
6. Save Results (Optional): Save the images of the edges and features as output files.
Program:
import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.show()
Result:
It focuses on performing basic image processing tasks such as edge detection (using the Canny
edge detector) and feature extraction (using Harris Corner detection), followed by displaying the
results with highlighted features in the images.
EX : 2 2. Implementation of simple neural network
Aim:
The aim of this task is to implement a simple neural network using Python. The neural network
will be designed to classify data based on a simple dataset (like the Iris dataset or a basic
binary classification problem). This example will use Keras (a high-level neural network API)
and TensorFlow as the backend for creating the neural network.
Algorithm:
1. Import Required Libraries: Import libraries like TensorFlow, Keras, and other
necessary modules for neural network creation.
2. Load and Preprocess Data: Load a dataset for classification, and preprocess it
(normalize, split into training and testing sets).
3. Build Neural Network Model:
○ Define the architecture of the neural network (input layer, hidden layers, output
layer).
○ Use activation functions like ReLU for hidden layers and softmax or sigmoid for
the output layer depending on the problem (multi-class or binary).
4. Compile the Model: Choose a loss function and optimizer (e.g.,
categorical_crossentropy for multi-class classification or binary_crossentropy for binary
classification).
5. Train the Model: Use the training data to train the neural network.
6. Evaluate the Model: Test the trained model on unseen test data to measure its
performance.
7. Output Results: Display accuracy and loss metrics.
Program :
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
import tensorflow as tf
# Step 1: Load the Iris dataset
iris = datasets.load_iris()
X = iris.data # Features
y = iris.target # Labels
# Input layer and first hidden layer with 10 neurons and ReLU activation
model.add(Dense(10, input_dim=4, activation='relu'))
# Output layer with 3 neurons (one for each class) and softmax activation
model.add(Dense(3, activation='softmax'))
# Output results
print(f"Test Loss: {loss:.4f}")
print(f"Test Accuracy: {accuracy:.4f}")
Output :
Epoch 1/100
24/24 ━━━━━━━━━━━━━━━━━━━━2s 4ms/step - accuracy: 0.3858 - loss: 1.2491
Epoch 2/100
24/24 ━━━━━━━━━━━━━━━━━━━━0s 4ms/step - accuracy: 0.7343 - loss: 0.8896
Epoch 3/100
24/24 ━━━━━━━━━━━━━━━━━━━━0s 5ms/step - accuracy: 0.6574 - loss: 0.8656
Epoch 4/100
.
.
.
.
.
.
.
24/2━━━━━━━━━━━━━0s 3ms/step - accuracy: 0.9697 - loss: 0.0752
Epoch 100/100
24/24 ━━━━━━━━━━━━━━━━━━━━0s 3ms/step - accuracy: 0.9831 - loss: 0.0714
1/1 ━━━━━━━━━━━━━━━━━━━━0s 279ms/step - accuracy: 0.9667 - loss: 0.0997
Test Loss: 0.0997
Test Accuracy: 0.9667
Result:
1. Training Progress: During the training, you will see the loss and accuracy for each
epoch. As training progresses, the model improves, and the loss decreases while
accuracy increases.
2. Test Accuracy: After training, the model's accuracy on the test set is displayed. The
higher the accuracy, the better the model has learned to classify the data. For this
example, we may see an accuracy of around 96.67% on the test set, which indicates
that the model is performing well.
3. Loss: The test loss is also reported, showing how far off the model's predictions were
from the actual labels on the test data. A lower test loss indicates a better-performing
model.
EX : 3 3. Study of Pretrained Deep Neural Network Model for
Images
Aim:
● Objective: The primary aim is to leverage a pretrained deep neural network model to
perform image classification, detection, segmentation, or any other image-related task.
● Goal: Use a pretrained model to achieve high accuracy in image-related tasks without
the need for extensive training from scratch, saving both time and computational
resources.
Algorithm:
The basic algorithm for using a pretrained deep neural network typically follows these steps:
Output :
Aim:
The aim of this experiment is to implement a Convolutional Neural Network (CNN) for image
classification. The CNN will learn to recognize patterns in images and classify them into
categories. We will use a dataset like CIFAR-10 to train and test the model.
Algorithm:
Program :
# Import libraries
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import cifar10
Output :
Epoch 1/10
Epoch 2/10
….
..
Epoch 10/10
Result :
The CNN successfully classifies images from the CIFAR-10 dataset, achieving a test accuracy
of approximately 71.63% after 10 epochs. The training accuracy improved significantly over the
epochs, showing that the model effectively learned to recognize patterns in the images.
EX : 5 5. CNN for image Segmentation
Aim:
The aim of this experiment is to implement a Convolutional Neural Network (CNN) for image
segmentation. Image segmentation involves dividing an image into multiple segments or
regions to simplify its analysis. The goal is to classify each pixel in an image into a predefined
category.
Algorithm:
1. Input Image:
○ Start by loading the image that needs to be segmented.
2. Preprocessing:
○ Resize the image to match the input size expected by the model (e.g., 128x128
pixels).
○ Normalize the pixel values to be between 0 and 1.
3. Build CNN Model for Segmentation:
○ Use convolutional layers to extract features from the image.
○ Use pooling layers to reduce the image dimensions and keep important features.
○ Use an upsampling or deconvolution layer to bring back the image to its original
size.
○ The final output layer should have as many channels as the number of classes
(e.g., background and object).
4. Activation Function:
○ Use a softmax activation for multi-class segmentation (for pixel-wise
classification).
5. Loss Function:
○ Use categorical cross-entropy loss for multi-class segmentation tasks.
6. Optimizer:
○ Use an optimizer like Adam to minimize the loss function.
7. Training:
○ Train the CNN model with ground truth data to learn to segment the image.
8. Output:
○ The model will output segmented images with each pixel labeled according to the
predicted class.
Program:
# Import libraries
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing import image
# Original image
plt.subplot(1, 2, 1)
plt.imshow(img)
plt.title("Original Image")
plt.axis('off')
plt.show()
Inference:
Output:
Example:
Aim:
To develop a Recurrent Neural Network (RNN) model for video processing, extracting
temporal features to classify actions or detect events in a video sequence.
Algorithm:
1. Data Preparation:
● Load video files and split them into individual frames.
● Preprocess frames (resize, normalize, and convert to tensors).
● Organize frames into sequences corresponding to video clips.
2. Model Design:
● Use a Convolutional Neural Network (CNN) to extract spatial features from
individual frames.
● Feed the extracted features into an RNN (e.g., LSTM or GRU) to capture
temporal dependencies between frames.
3. Training:
● Split the dataset into training and validation sets.
● Train the RNN on sequences of features extracted from the video frames.
● Use a suitable loss function (e.g., categorical crossentropy for
classification tasks).
4. Evaluation:
● Test the trained model on unseen video sequences.
● Evaluate performance metrics like accuracy or F1-score.
5. Prediction:
● Use the trained model to predict actions or events on new video
sequences.
Program:
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
import cv2
import os
# Step 1: Load and preprocess video data
def load_video(video_path, frame_size=(64, 64), max_frames=30):
cap = cv2.VideoCapture(video_path)
frames = []
while len(frames) < max_frames:
ret, frame = cap.read()
if not ret:
break
frame = cv2.resize(frame, frame_size) # Resize frame
frame = frame / 255.0 # Normalize
frames.append(frame)
cap.release()
frames = np.array(frames)
if len(frames) < max_frames:
# Padding if less frames
padding = np.zeros((max_frames - len(frames), *frames[0].shape))
frames = np.concatenate((frames, padding))
return frames
# Step 4: Training
# cnn_model.fit(video_sequences, labels, epochs=10) # Example training
# Step 5: Prediction
predictions = cnn_model.predict(video_sequences)
print("Predictions:", predictions)
Output:
1. Predictions:
The output is a classification probability for the video sequence, e.g.,
2. Predictions: [[0.85]]
3. Visual Output:
Not directly provided in this code but can be added to visualize feature extraction
or prediction results.
Result:
The RNN model successfully processed video sequences and predicted the
classification result for the input video. The performance of the model depends on the
quality of the training dataset and the temporal resolution of the video clips.
EX : 7 7. Implementation of Deep Generative model for Image
editing
Aim:
To develop a deep generative model that can perform image editing tasks, such as
modifying specific attributes (e.g., changing color, adding objects) or transforming one
image into another (e.g., style transfer or image-to-image translation).
Algorithm:
1. Data Collection:
● Collect a dataset of images that represent the type of editing you want to
perform (e.g., faces for facial attribute editing, landscapes for image-to-
image translation).
2. Model Architecture:
● Use a Generative Adversarial Network (GAN) or Variational Autoencoder
(VAE) to learn the distribution of images.
● The generator network creates modified images, while the discriminator
evaluates how realistic the generated images are.
● For image-to-image translation, models like pix2pix or CycleGAN are
useful.
3. Training:
● Train the model on the collected image dataset, ensuring the generator
learns to produce realistic edits and transformations.
● Use loss functions like adversarial loss (from the discriminator) and L1
loss (for pixel accuracy).
4. Image Editing:
● Provide an image as input and apply the desired transformations or edits
based on learned features.
5. Evaluation:
● Evaluate the model by comparing generated images with ground truth
images (real images or manually edited images).
● Assess quality using metrics like Inception Score (IS) or Fréchet Inception
Distance (FID).
Program
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import transforms, datasets, utils
from torchvision.models import vgg19
import os
# Define Generator
class Generator(nn.Module):
def __init__(self, in_channels, out_channels):
super(Generator, self).__init__()
self.encoder = nn.Sequential(
self._conv_block(in_channels, 64, 4, 2, 1),
self._conv_block(64, 128, 4, 2, 1),
self._conv_block(128, 256, 4, 2, 1),
self._conv_block(256, 512, 4, 2, 1)
)
self.decoder = nn.Sequential(
self._deconv_block(512, 256, 4, 2, 1),
self._deconv_block(256, 128, 4, 2, 1),
self._deconv_block(128, 64, 4, 2, 1),
nn.ConvTranspose2d(64, out_channels, kernel_size=4, stride=2, padding=1),
nn.Tanh()
)
# Define Discriminator
class Discriminator(nn.Module):
def __init__(self, in_channels):
super(Discriminator, self).__init__()
self.model = nn.Sequential(
self._conv_block(in_channels, 64, 4, 2, 1),
self._conv_block(64, 128, 4, 2, 1),
self._conv_block(128, 256, 4, 2, 1),
nn.Conv2d(256, 1, kernel_size=4, stride=1, padding=1)
)
# Hyperparameters
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
lr = 2e-4
batch_size = 16
epochs = 100
image_size = 128
in_channels = 3
out_channels = 3
# Data Preparation
transform = transforms.Compose([
transforms.Resize((image_size, image_size)),
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
# Initialize Models
generator = Generator(in_channels, out_channels).to(device)
discriminator = Discriminator(in_channels + out_channels).to(device)
# Training Loop
for epoch in range(epochs):
for i, (input_image, target_image) in enumerate(dataloader):
input_image, target_image = input_image.to(device), target_image.to(device)
real_labels = torch.ones((input_image.size(0), 1), requires_grad=False).to(device)
fake_labels = torch.zeros((input_image.size(0), 1), requires_grad=False).to(device)
# Train Generator
optimizer_G.zero_grad()
generated_image = generator(input_image)
disc_fake = discriminator(torch.cat((input_image, generated_image), dim=1))
g_loss = adversarial_loss(disc_fake, real_labels) + pixel_loss(generated_image,
target_image)
g_loss.backward()
optimizer_G.step()
# Train Discriminator
optimizer_D.zero_grad()
disc_real = discriminator(torch.cat((input_image, target_image), dim=1))
real_loss = adversarial_loss(disc_real, real_labels)
disc_fake = discriminator(torch.cat((input_image, generated_image.detach()), dim=1))
fake_loss = adversarial_loss(disc_fake, fake_labels)
d_loss = (real_loss + fake_loss) / 2
d_loss.backward()
optimizer_D.step()
# Logging
if i % 50 == 0:
print(f"Epoch [{epoch}/{epochs}] Batch {i}/{len(dataloader)} - Loss D: {d_loss.item()},
Loss G: {g_loss.item()}")
# Save Models
torch.save(generator.state_dict(), "generator.pth")
torch.save(discriminator.state_dict(), "discriminator.pth")
print("Training Complete!")
Inference :
# Generator (Autoencoder)
class Generator(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(nn.Conv2d(3, 64, 4, 2, 1), nn.ReLU())
self.decoder = nn.Sequential(nn.ConvTranspose2d(64, 3, 4, 2, 1), nn.Tanh())
Result:
After running the training loop, the model will output a trained generator capable of performing
image edits.
The generator can take an input image, process it through the learned network, and produce
the transformed or edited version of the image (e.g., modifying facial features or changing the
style of a landscape).
The saved model files (generator.pth, discriminator.pth) can be used for inference in future image
editing tasks.