TilakSrajal.pdf
TilakSrajal.pdf
MINI PROJECT
S.no. Title Signature
1. Face Detection and Recognition Using OpenCV
MICRO PROJECT
S.no. Title Signature
1. Object Detection using Contour Detection
MACRO PROJECT
S.no. Title Signature
1. Image Processing and Object Segmentation
Mini Project
Title: Face Detection and Recognition Using OpenCV
Introduction: This project utilizes OpenCV and machine learning techniques to
detect and recognize faces in real time. By leveraging Haar cascade classifiers
for face detection and an SVM classifier for recognition, the system processes
live video input and identifies known individuals .
Technologies Used
2. Face Recognition:
:
Classifies detected faces using an SVM model.
Working Mechanism
1. Frame Capture & Processing
:
o Captures video frames using OpenCV.
o Converts frames to grayscale and applies histogram equalization.
2. Pose Detection
:
o Classifies detected faces using an SVM model.
o Identifies known individuals and labels them with confidence scores.
3. Face Recognition:
Key Features
Potential Applications:
Code:
import cv2
import numpy as np
import os
from sklearn.svm import SVC
import pickle
# Create directories if they don't exist
if not os.path.exists('faces'):
os.makedirs('faces')
if not os.path.exists('models'):
os.makedirs('models')
class SimpleFaceRecognition:
def _init_(self):
# Load face detection model (Haar Cascade)
self.face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Initialize classifier
self.classifier = SVC(kernel='linear', probability=True)
self.faces_db = {}
self.labels = []
self.faces = []
self.unique_people = set()
cap = cv2.VideoCapture(0)
count = 0
# Detect faces
faces = self.face_detector.detectMultiScale(
preprocessed,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
print(f"Saved {count}/{num_samples}")
# Display progress
cv2.putText(frame, f"Samples: {count}/{num_samples}", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.imshow('Face Collection', frame)
cap.release()
cv2.destroyAllWindows()
print(f"Collected {count} samples for {name}")
def load_training_data(self):
"""Load face images from the faces directory"""
self.faces = []
self.labels = []
self.unique_people = set()
# Load image
img_path = os.path.join('faces', file)
face_img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
def train_model(self):
"""Train face recognition model"""
if len(self.faces) == 0:
print("No training data. Please collect face samples first.")
return False
def recognize_faces(self):
"""Run real-time face recognition"""
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
# Detect faces
faces = self.face_detector.detectMultiScale(
preprocessed,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Predict face
prediction = self.classifier.predict_proba(face_features)[0]
idx = np.argmax(prediction)
confidence = prediction[idx] * 100
# Get name
name = self.classifier.classes_[idx]
0.5, color, 2)
cap.release()
cv2.destroyAllWindows()
# Main function
def main():
system = SimpleFaceRecognition()
while True:
print("\n----- Face Recognition System -----")
print("1. Collect face samples")
print("2. Train recognition model")
print("3. Run face recognition")
print("4. Exit")
if choice == '1':
name = input("Enter person's name: ")
system.collect_faces(name)
else:
print("Invalid option! Please try again.")
Result and Conclusion: This project successfully combines face detection
and recognition into a single system using OpenCV and machine learning
applications.
Micro Project
Title: Object Detection using Contour Detection
Introduction Object detection is a key task in computer vision that aims to
identify and locate objects within an image. In this project, we use contour
detection to find and outline the boundaries of objects. Contour detection is an
edge-detection technique that identifies the outlines of objects based on
differences in pixel intensity. This method is particularly useful for identifying
distinct shapes or objects in images, even in noisy environments.
Objective The main goal of this project is to use contour detection to identify
objects in an image by detecting their boundaries and drawing contours
around them. This technique can be applied to applications like object
tracking, shape recognition, and image analysis.
Contour Detection
Contours are curves or boundaries in an image that represent the edges of
objects. They are useful for object detection and shape analysis. OpenCV
provides a robust algorithm to find contours in an image. The process
involves the following steps:
Edge Detection: Detect edges in the image using methods like Canny edge detection
Contour Extraction: Find the contours of the detected edges.
Contour Drawing: Draw contours on the original image to outline objects.
Methodology
Load the Image: Read the image from the file system.
Preprocess the Image: Convert the image to grayscale to simplify the analysis.
Apply Gaussian Blur: Reduce noise in the image to improve edge detection.
Detect Edges: Use edge detection (e.g., Canny edge detection) to identify potential
boundaries of objects.
Find Contours: Use OpenCV's findContours() function to extract the contours.
Draw Contours: Draw the contours on the original image to visualize the detected
objects
Code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Find contours
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
plt.subplot(1, 2, 1)
plt.title("Original Image")
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.subplot(1, 2, 2)
plt.title("Contour Detection")
plt.imshow(cv2.cvtColor(contour_image, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.show()
Results & Conclusion
The experiment was conducted using an image of a box and objects inside it. The contour
detection successfully outlined the boundaries of the objects. Here's what we observed:
Effective Object Detection: The contour detection method successfully identified the
objects in the image, drawing clear outlines around them.
Edge Detection Precision: The Canny edge detection highlighted the borders of objects
effectively, making it easier to identify their contours.
Methodology
The image processing workflow consists of the following steps:
Preprocessing
Convert the image to grayscale to reduce complexity and computational
cost.
Apply Gaussian Blur to smooth the image and reduce noise.
Edge Detection
Canny Edge Detection: Detects edges by computing gradients and
applying non-maximum suppression.
Sobel Edge Detection (X & Y): Computes gradients in horizontal and
vertical directions.
Laplacian Edge Detection: Captures variations in intensity to detect
edges.
Morphological Operations
Dilation: Expands white regions, making objects more visible.
Erosion: Shrinks white regions, removing noise and small details.
Opening: Erosion followed by dilation, used to remove small noise.
Closing: Dilation followed by erosion, used to fill small holes.
Object Segmentation
Apply thresholding to create a binary image.
Find external contours using cv2.findContours.
Draw contours on a blank image to highlight segmented objects.
Code:
import cv2
import numpy as np
import os
def preprocess_image(image):
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Gaussian Blur
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
return blurred
def edge_detection(image):
edges_canny = cv2.Canny(image, 100, 200)
edges_sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=5)
edges_sobely = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=5)
edges_laplacian = cv2.Laplacian(image, cv2.CV_64F)
return edges_canny, edges_sobelx, edges_sobely, edges_laplacian
def morphological_operations(image):
kernel = np.ones((5,5), np.uint8)
dilation = cv2.dilate(image, kernel, iterations=1)
erosion = cv2.erode(image, kernel, iterations=1)
opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)
return dilation, erosion, opening, closing
def object_segmentation(image):
_, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
segmented = np.zeros_like(image)
cv2.drawContours(segmented, contours, -1, (255, 255, 255), thickness=cv2.FILLED)
return segmented, contours
def process_images_in_folder(folder_path):
output_folder = os.path.join(folder_path, 'processed')
os.makedirs(output_folder, exist_ok=True)
# Example usage
folder_path = "./images-2" # Change this to the path of your images folder
process_images_in_folder(folder_path)
Results & Conclusion:
Original Image: