Mini Report
Mini Report
1. INTRODUCTION
Emotions play a vital role in human communication, influencing decision-making, behavior, and
interpersonal interactions. While traditional emotion recognition methods rely on facial
expressions, speech, and physiological signals, handwriting analysis offers a unique and less
intrusive approach to understanding emotions. Handwriting carries distinct characteristics—such
as stroke pressure, slant, spacing, and thickness—that can reflect a writer's emotional state.
This project focuses on Handwriting-Based Emotion Detection Using Deep Learning and
Image Processing, leveraging computer vision and machine learning techniques to classify
emotions from handwritten text. The system extracts key handwriting features and combines them
with deep learning models to improve accuracy in emotion classification.
The project aims to provide a robust system for emotion detection through handwriting
analysis, which has potential applications in psychology, forensics, education, and AI-driven
sentiment analysis. Future improvements may include expanding the dataset, optimizing
hyperparameters, and real-time deployment for practical use.
• Deep Learning and Neural Networks – CNNs (e.g., MobileNetV2) enabled automatic
feature extraction from handwriting images, significantly improving classification
accuracy.
• Real-Time AI-Powered Emotion Detection – Modern AI models integrate deep
learning and computer vision for real-time, automated emotion recognition, with
applications in mental health and forensic analysis.
1. Graphology-Based Methods
• Uses algorithms like Naïve Bayes, Support Vector Machines (SVMs), and
Decision Trees for classification.
• Limited Accuracy – Struggles with different handwriting styles, ink pressure, and
writing speed.
• Eliminates the need for manual feature selection used in traditional graphology
methods.
2.Literature Survey
Handwriting-based emotion detection has been an evolving research area, integrating graphology,
machine learning, and deep learning techniques to improve accuracy and reliability. Various
studies have explored different approaches to analysing handwriting for emotional state detection.
• Early studies focused on manual handwriting analysis to assess emotions and personality
traits.
• Features such as stroke slant, letter spacing, and baseline alignment were interpreted
subjectively.
Study: Emotion Recognition from Handwriting Using SVM and Naïve Bayes (2015)
• Applied Support Vector Machines (SVM) and Naïve Bayes classifiers for emotion
detection.
Study: Handwriting Recognition Using Image Processing and Deep Learning (2017)
• Used OpenCV and edge detection algorithms to extract structural handwriting features.
Study: Handwriting Emotion Detection Using CNNs and Transfer Learning (2020–Present)
• CNNs (Convolutional Neural Networks) and transfer learning models (e.g., MobileNetV2,
ResNet) were applied to handwriting images.
• Eliminated the need for manual feature selection by automatically extracting deep features
from handwriting patterns.
• Combined CNNs with handwriting-specific feature analysis (e.g., stroke density, pressure
variation).
• Hybrid models combining CNNs with handwriting-specific features yield the best results
for emotion classification.
Existing handwriting-based emotion detection methods often rely on machine learning models that
require manual feature extraction and struggle with handwriting variations across different
individuals. These approaches lack automation, scalability, and the ability to generalize effectively
across diverse handwriting styles. Additionally, previous research in this area has failed to integrate
deep learning techniques, limiting the accuracy and robustness of existing systems.
To overcome these challenges, this project proposes a hybrid deep learning-based handwriting
emotion detection system. The model integrates CNN-based image processing (MobileNetV2) and
handwriting-specific feature extraction using OpenCV to automatically analyse handwriting
patterns. It also leverages data augmentation techniques (such as rotation, shearing, noise addition,
and scaling) to improve model performance. The system is designed to enable real-time,
automated, and scalable emotion detection with potential applications in mental health assessment,
forensic analysis, and AI-driven sentiment analysis.
1. Operating System
2. Programming Language
• Scikit-learn (pip install scikit-learn) – For data preprocessing and model evaluation
4. IDE/Text Editor
5. Optional Tools
• GPU Support: NVIDIA CUDA & cuDNN (for TensorFlow GPU acceleration)
• The system extracts handwriting features (stroke thickness, slant, pressure, etc.) and
combines them with image-based analysis for emotion classification.
• Uses deep learning (MobileNetV2) and traditional handwriting feature analysis for
emotion detection.
3.4 Importance
In education, this technology can help teachers and counsellors assess students' emotional well-
being by analysing their handwritten assignments or notes. Early identification of stress or
anxiety through handwriting can facilitate timely intervention, improving mental health support
in academic institutions. Additionally, in forensic and behavioural studies, handwriting-based
emotion detection can assist in analysing suspect behaviour, identifying distress signals, and
enhancing criminal investigations. Such applications demonstrate the project's potential in both
academic and professional fields.
From a technological perspective, this project integrates computer vision, machine learning, and
feature extraction to develop a robust emotion classification model. By combining image-based
handwriting analysis with statistical feature extraction, it improves accuracy compared to
standalone methods. The implementation of this system can pave the way for future research in
emotion recognition, human-computer interaction, and AI-driven mental health diagnostics. Its
significance extends beyond academia, with applications in healthcare, security, and personal
well-being, making it a valuable contribution to the field of artificial intelligence and behavioural
analysis.
4.SYSTEM DESIGN
• After login, users are presented with a main menu with the following options:
• Emotion Insights: Get forensic insights and tips based on detected emotions.
• Feature extraction techniques (stroke thickness, slant angle, pressure, spacing, etc.).
• The extracted handwriting features are processed using a deep learning model (CNN
integrated with feature-based classification).
• Happy
• Calm
• Angry
• Stressed
• The detected emotion is displayed to the user along with forensic insights.
• Built using HTML, CSS, and JavaScript for a user-friendly web interface.
• Features include:
project_folder/
├── static/
│ ├── index.html
│ ├── dashboard.html
│ └── emotion/
│ ├── emotion_detection.html
│ ├── history.html
├── app.py
├── model/
│ ├── emotion_model.h5
│ ├── class_indices.json
├── dataset/
│ ├── handwriting_samples
│ ├── augmented_images
└── requirements.txt
1. Static/ Folder:
• Contains all the HTML files used for the front-end of the project.
• The emotion/ sub-folder contains pages for emotion detection and history viewing.
2. HTML Files:
• index.html:
• dashboard.html:
• emotion/emotion_detection.html:
• emotion/history.html:
3. app.py:
• The Flask application file that serves as the backend for the project.
• Includes logic for processing uploaded handwriting images, extracting features, and
interacting with the trained deep learning model.
4. model/
• class_indices.json: A JSON file storing class labels mapped to emotion categories (e.g.,
Happy, Angry, Calm, Stressed).
5. dataset/
1. Login:
2. Main Menu:
3. Functional Pages:
• emotion_detection.html:
• Processes the image and displays the detected emotion with forensic insights.
• history.html:
4. Backend:
• The uploaded handwriting image is preprocessed and analyzed using the deep learning
model (emotion_model.h5).
• The detected emotion is sent back and displayed on the respective page.
5.Implementation
import random
import cv2
import pandas as pd
import numpy as np
import tensorflow as tf
def extract_handwriting_features(image_path):
if not os.path.exists(image_path):
if img is None:
angles = []
if len(bounding_boxes) > 1:
spacing = np.mean([
for i in range(len(bounding_boxes) - 1)
])
else:
spacing = np.nan
stroke_count = len(contours)
feature_vector = np.array([
])
return feature_vector.tolist()
df = pd.read_csv('C:\\Users\\Aditya\\OneDrive\\Documents\\Mini_Project\\Handwriting.csv')
def data_augmentation(image):
angel=random.uniform(-5,5)
h,w=image.shape[:2]
M=cv2.getRotationMatrix2D((w//2,h//2),angel,1)
rotated=cv2.warpAffine(image,M,(w,h))
shearing=random.uniform(-0.1,0.1)
M_shear=np.float32([[1,shearing,0],[0,1,0]])
shear=cv2.warpAffine(rotated,M_shear,(w,h))
scale_factor=random.uniform(0.9,1.1)
scaled=cv2.resize(shear,None,fx=scale_factor,fy=scale_factor,interpolation=cv2.INTER_CUBIC
)
noise=np.random.normal(0,0.5,scaled.shape).astype(np.uint8)
noise=cv2.add(scaled,noise)
alpha=random.uniform(0.8,1)
beta=random.randint(-5,5)
adjusted=cv2.convertScaleAbs(noise,alpha=alpha,beta=beta)
return adjusted
output_folder='C:\\Users\\Aditya\\OneDrive\\Documents\\Mini_Project\\aug_images'
Dept of AIML 2024-25 19 | P a g e
Handwriting-Based Emotion Detection Using Deep Learning and Image Processing
os.makedirs(output_folder,exist_ok=True)
augmented_data=[]
image_path=row['Image Path']
emotion = row['Emotion']
image=cv2.imread(image_path)
filename=os.path.basename(image_path).split('.')[0]
os.makedirs(emotion_folder, exist_ok=True)
for i in range(6):
augmented_image=data_augmentation(image)
output_path=os.path.join(emotion_folder,f"{filename}aug{i}.png")
cv2.imwrite(output_path,augmented_image)
augmented_data.append([output_path,emotion,sentence])
augmented_df=pd.DataFrame(augmented_data,columns=['Image Path','Emotion','Sentence'])
all_emotions=df['Emotion'].tolist()+augmented_df['Emotion'].tolist()
augmented_df=pd.concat([df,augmented_df],ignore_index=True)
features=[]
features.append(extract_handwriting_features(image_path))
augmented_df=pd.concat([augmented_df,features_df],axis=1)
augmented_df.to_csv('C:\\Users\\Aditya\\OneDrive\\Documents\\Mini_Project\\Augmented_Han
dwriting.csv')
original_images_folder = 'C:\\Users\\Aditya\\OneDrive\\Documents\\Mini_Project\\Images'
augmented_images_folder =
'C:\\Users\\Aditya\\OneDrive\\Documents\\Mini_Project\\aug_images'
X = np.array(features)
y = pd.get_dummies(augmented_df['Emotion']).values
train_datagen = combined_datagen.flow_from_directory(
original_images_folder,
target_size=(224, 224),
batch_size=64,
class_mode='categorical'
val_datagen = ImageDataGenerator(rescale=1.0/255)
val_generator = val_datagen.flow_from_directory(
augmented_images_folder,
target_size=(224, 224),
batch_size=64,
class_mode='categorical'
while True:
feature_batch = feature_data[:img_batch.shape[0]]
x = Flatten()(mobilenet.output)
x = Dropout(0.5)(x)
features_input = Input(shape=(X.shape[1],))
y = Dense(64, activation='relu')(features_input)
y = Dropout(0.5)(y)
z = Dense(128, activation='relu')(combined)
z = Dropout(0.5)(z)
z = Dense(64, activation='relu')(z)
history = model.fit(
epochs=1,
model.save('C:\\Users\\Aditya\\OneDrive\\Documents\\Mini_Project\\emotion_detection_model.
h5')
import json
json.dump(class_indices, f)
Explanation
1. Importing Libraries
• sklearn.model_selection: For splitting the data into training and validation sets.
• Stroke Thickness: Measures the difference in thickness between the dilated and
original images.
• Slant Angle: Measures the angle of the lines in the handwriting using Hough Line
Transform.
• After extracting these features, the function returns a normalized feature vector for each
image.
3. Data Augmentation
• Rotation
• Shearing
• Scaling
• Adding noise
• These augmented images help in improving the model's generalization ability by training
on a more diverse dataset.
• df: Loads the CSV file containing information about images, their paths, emotion labels,
and associated sentences.
• Augmenting Data: The code loops over the dataset, generates augmented versions of each
image, and stores them in an output folder, updating the dataset accordingly.
• Feature Extraction: For each image, handwriting features are extracted and stored in a
new dataframe (features_df).
• augmented_df: This dataframe now contains both original and augmented images with
associated emotion labels, sentences, and extracted handwriting features.
• train_test_split: Splits the data into training and validation sets (80% for training and 20%
for validation).
• train_datagen: Applies the combined augmentations to the images in the original folder
(original_images_folder).
• val_generator: This is used for validation images, without additional augmentations, but
rescaling the pixel values.
• Image Model:
• The last layer of MobileNetV2 is flattened and passed through a Dropout layer for
regularization.
• Feature Model:
• This model takes in the handwriting features and processes them through a Dense
layer (64 units) followed by a Dropout layer.
• Combining Models: The outputs from both the image and feature models are
concatenated and passed through additional dense layers to generate a final
output.
• Final Output Layer: A softmax layer that outputs the predicted emotion for each
input image.
• The model is compiled with the Adam optimizer and categorical cross-entropy loss (since
it’s a multi-class classification problem).
• The model is trained for 1 epoch using the combined data generator, which feeds both
image data and handwriting features during training.
• class_indices: Maps emotion labels (e.g., happy, sad, angry) to numerical indices.
• This dictionary is saved to a JSON file (class_indices.json) so that the model can later
map predictions to human-readable emotion labels.
Output
6.Results
Website view
9.Applications
1. Psychological & Mental Health Assessment
This system can be used by psychologists and therapists to assess an individual's emotional state
based on handwriting. By detecting stress, anxiety, or depression through handwriting patterns,
mental health professionals can provide early intervention and tailored therapy for individuals
struggling with emotional distress.
In academic settings, teachers and counsellors can use this technology to monitor students'
emotional well-being through their handwritten assignments. It helps identify students
experiencing stress, anxiety, or disengagement, allowing timely intervention to improve their
learning experience and mental health.
Law enforcement agencies can leverage handwriting-based emotion detection to analyze suspect
notes, threat letters, or criminal documents. This can provide insights into a person's emotional
state at the time of writing, helping forensic experts in criminal profiling and psychological
assessments of suspects.
Organizations can use this system to assess employees’ emotional well-being through their
handwritten documents, notes, or reports. By identifying workplace stress or burnout early, HR
departments can implement wellness programs to improve employee productivity and mental
health.
Companies can use handwriting emotion detection to analyse customer feedback or handwritten
surveys. By understanding customer sentiments from physical responses, businesses can refine
their products, services, and marketing strategies based on consumer emotions.
Conclusion
The handwriting-based emotion detection system leverages deep learning and computer vision to
classify emotions such as happiness, anger, calmness, and stress by analysing handwriting features
like stroke thickness, slant, pressure, and spacing. This non-intrusive approach has valuable
applications in mental health assessment, education, forensic investigations, workplace well-
being, and human-computer interaction. By automating emotion recognition, the system enhances
accuracy and efficiency, reducing the need for manual interpretation. Its integration with AI-driven
applications opens new possibilities in personalized user experiences, sentiment analysis, and
fraud detection. Future advancements, such as expanding datasets, incorporating multilingual
handwriting, and real-time analysis, can further improve its accuracy and applicability, making it
a powerful tool for behavioural analysis, security, and mental health support.
The future scope of the Emotion Detection System includes expanding the dataset with diverse
handwriting samples for improved accuracy, integrating real-time handwriting analysis using
digital tablets, and leveraging advanced deep learning models like transformers for better feature
extraction. A multimodal approach combining handwriting, facial expression, and voice tone
analysis will enhance emotion recognition. Cloud and mobile deployment will increase
accessibility, while applications in security, such as fraud detection and signature verification,
will broaden its use. Additionally, AI-powered adaptive learning will enable continuous
improvements through user feedback for more precise and personalized emotion detection
9.References
1. Deep Learning for Handwriting-Based Emotion Detection – Research papers and
studies on deep learning applications for handwriting analysis and emotion recognition.
Example: Handwriting Analysis for Emotion Recognition Using CNNs and RNNs (IEEE,
2022).
4. Machine Learning for Sentiment and Emotion Analysis – Research on using AI for
emotion recognition from textual and handwritten data.