0% found this document useful (0 votes)
19 views

Lab Manual1

The Computer Vision Lab Manual provides a comprehensive guide for hands-on experiments in computer vision using OpenCV and Python for the academic year 2023-2024. It includes ten lab experiments covering topics such as image manipulation, edge detection, object detection, and deep learning for image classification. The manual also contains an appendix with installation instructions and useful OpenCV functions.

Uploaded by

khaleel2791
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Lab Manual1

The Computer Vision Lab Manual provides a comprehensive guide for hands-on experiments in computer vision using OpenCV and Python for the academic year 2023-2024. It includes ten lab experiments covering topics such as image manipulation, edge detection, object detection, and deep learning for image classification. The manual also contains an appendix with installation instructions and useful OpenCV functions.

Uploaded by

khaleel2791
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

# **Computer Vision Lab Manual**

**Department of Computer Science & Engineering**

**Academic Year: 2023-2024**

---

## **Table of Contents**

1. **Introduction to Computer Vision**

2. **Lab Experiments**

- Experiment 1: Image Reading and Display

- Experiment 2: Image Manipulation (Grayscale, Resizing, Cropping)

- Experiment 3: Edge Detection (Sobel, Canny)

- Experiment 4: Feature Detection (Harris Corner, SIFT)

- Experiment 5: Object Detection using Haar Cascades

- Experiment 6: Image Segmentation (Thresholding, K-Means)

- Experiment 7: Optical Flow and Motion Detection

- Experiment 8: Face Recognition using PCA (Eigenfaces)

- Experiment 9: Deep Learning for Image Classification (CNN)

- Experiment 10: Real-time Object Detection (YOLO/SSD)

3. **Appendix: Python & OpenCV Basics**

---

## **1. Introduction to Computer Vision**

Computer Vision (CV) is a field of artificial intelligence that enables machines


to interpret and process visual data. This lab manual provides hands-on
experiments using **OpenCV, Python, and deep learning frameworks** to
implement key CV techniques.
---

## **2. Lab Experiments**

### **Experiment 1: Image Reading and Display**

**Objective:** Load and display an image using OpenCV.

**Code:**

```python

import cv2

# Read an image

img = cv2.imread('image.jpg')

# Display the image

cv2.imshow('Sample Image', img)

cv2.waitKey(0)

cv2.destroyAllWindows()

```

**Tasks:**

- Try reading different image formats (JPEG, PNG).

- Check image properties (shape, dtype).

---
### **Experiment 2: Image Manipulation**

**Objective:** Convert an image to grayscale, resize, and crop.

**Code:**

```python

gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

resized_img = cv2.resize(img, (200, 200))

cropped_img = img[50:200, 100:300] # y1:y2, x1:x2

```

**Tasks:**

- Apply Gaussian blur to smooth the image.

- Rotate the image by 45 degrees.

---

### **Experiment 3: Edge Detection**

**Objective:** Detect edges using Sobel and Canny filters.

**Code:**

```python

sobel_x = cv2.Sobel(gray_img, cv2.CV_64F, 1, 0, ksize=5)

canny_edges = cv2.Canny(gray_img, 100, 200)

```

**Tasks:**

- Compare Sobel and Canny results.


- Adjust thresholds in Canny edge detection.

---

### **Experiment 4: Feature Detection**

**Objective:** Detect keypoints using Harris Corner and SIFT.

**Code (Harris Corner):**

```python

corners = cv2.cornerHarris(gray_img, 2, 3, 0.04)

img[corners > 0.01 * corners.max()] = [0, 0, 255] # Mark corners in red

```

**Code (SIFT):**

```python

sift = cv2.SIFT_create()

keypoints = sift.detect(gray_img, None)

img_with_keypoints = cv2.drawKeypoints(img, keypoints, None)

```

**Tasks:**

- Compare Harris and SIFT performance.

- Try ORB or FAST for faster detection.

---

### **Experiment 5: Object Detection using Haar Cascades**


**Objective:** Detect faces using a pre-trained Haar Cascade.

**Code:**

```python

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade_frontalface_default.xml')

faces = face_cascade.detectMultiScale(gray_img, 1.3, 5)

for (x, y, w, h) in faces:

cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

```

**Tasks:**

- Detect eyes and smiles using respective Haar cascades.

- Apply real-time face detection using a webcam.

---

### **Experiment 6: Image Segmentation**

**Objective:** Segment an image using thresholding and K-Means.

**Code (Otsu’s Thresholding):**

```python

_, thresh = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY +


cv2.THRESH_OTSU)

```
**Code (K-Means Clustering):**

```python

pixels = img.reshape((-1, 3))

k=3

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100,


0.2)

_, labels, centers = cv2.kmeans(pixels.astype(np.float32), k, None, criteria,


10, cv2.KMEANS_RANDOM_CENTERS)

segmented_img = centers[labels.flatten()].reshape(img.shape)

```

**Tasks:**

- Compare different clustering values (k=2, k=4).

- Apply GrabCut for interactive segmentation.

---

### **Experiment 7: Optical Flow and Motion Detection**

**Objective:** Track motion using Lucas-Kanade method.

**Code:**

```python

prev_pts = cv2.goodFeaturesToTrack(prev_gray, maxCorners=100,


qualityLevel=0.3, minDistance=7)

next_pts, status, _ = cv2.calcOpticalFlowPyrLK(prev_gray, next_gray,


prev_pts, None)

```
**Tasks:**

- Implement dense optical flow using Farneback’s method.

- Detect moving objects in a video.

---

### **Experiment 8: Face Recognition using PCA (Eigenfaces)**

**Objective:** Recognize faces using Principal Component Analysis.

**Code:**

```python

from sklearn.decomposition import PCA

# Assume X_train contains flattened face images

pca = PCA(n_components=100)

X_train_pca = pca.fit_transform(X_train)

```

**Tasks:**

- Train a simple SVM classifier on eigenfaces.

- Compare with LBPH (Local Binary Patterns Histograms).

---

### **Experiment 9: Deep Learning for Image Classification (CNN)**

**Objective:** Train a CNN model on CIFAR-10 dataset.


**Code (Using TensorFlow/Keras):**

```python

model = Sequential([

Conv2D(32, (3,3), activation='relu', input_shape=(32,32,3)),

MaxPooling2D((2,2)),

Flatten(),

Dense(10, activation='softmax')

])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

model.fit(X_train, y_train, epochs=10)

```

**Tasks:**

- Improve accuracy using deeper CNN architectures.

- Test on custom images.

---

### **Experiment 10: Real-time Object Detection (YOLO/SSD)**

**Objective:** Detect objects in real-time using YOLOv3.

**Code:**

```python

net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")

blob = cv2.dnn.blobFromImage(img, 1/255, (416,416), swapRB=True,


crop=False)
net.setInput(blob)

output_layers = net.getUnconnectedOutLayersNames()

detections = net.forward(output_layers)

```

**Tasks:**

- Compare YOLO with SSD.

- Deploy on a live camera feed.

---

## **3. Appendix: Python & OpenCV Basics**

- **Installation:**

```bash

pip install opencv-python numpy matplotlib tensorflow keras scikit-learn

```

- **Useful OpenCV Functions:**

- `cv2.imread()`, `cv2.imshow()`, `cv2.imwrite()`

- `cv2.cvtColor()`, `cv2.resize()`, `cv2.rotate()`

- `cv2.findContours()`, `cv2.drawContours()`

---

### **Conclusion**

This lab manual covers fundamental to advanced computer vision


techniques. Students are encouraged to modify parameters, explore
alternative algorithms, and implement real-world applications.
**Happy Coding!** 🚀

You might also like