Bird
Raised Fist0
Computer Visionml~20 mins

Hand and face landmark detection in Computer Vision - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Hand and face landmark detection
Problem:Detect key points (landmarks) on hands and faces from images to enable gesture and expression recognition.
Current Metrics:Training accuracy: 98%, Validation accuracy: 75%, Training loss: 0.05, Validation loss: 0.25
Issue:The model overfits: training accuracy is very high but validation accuracy is much lower, indicating poor generalization.
Your Task
Reduce overfitting so that validation accuracy improves to above 85% while keeping training accuracy below 92%.
You can only modify the model architecture and training hyperparameters.
Do not change the dataset or input image size.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
Computer Vision
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.preprocessing.image import ImageDataGenerator

# Data augmentation setup
train_datagen = ImageDataGenerator(
    rescale=1./255,
    rotation_range=15,
    width_shift_range=0.1,
    height_shift_range=0.1,
    zoom_range=0.1,
    horizontal_flip=True,
    validation_split=0.2
)

# Assuming train_dir contains hand and face images with landmarks labels
train_generator = train_datagen.flow_from_directory(
    'train_dir',
    target_size=(128, 128),
    batch_size=32,
    class_mode='categorical',
    subset='training'
)
validation_generator = train_datagen.flow_from_directory(
    'train_dir',
    target_size=(128, 128),
    batch_size=32,
    class_mode='categorical',
    subset='validation'
)

# Model architecture with dropout to reduce overfitting
model = models.Sequential([
    layers.Conv2D(32, (3,3), activation='relu', input_shape=(128,128,3)),
    layers.MaxPooling2D(2,2),
    layers.Dropout(0.25),
    layers.Conv2D(64, (3,3), activation='relu'),
    layers.MaxPooling2D(2,2),
    layers.Dropout(0.25),
    layers.Flatten(),
    layers.Dense(128, activation='relu'),
    layers.Dropout(0.5),
    layers.Dense(42, activation='linear')  # 21 landmarks * 2 coordinates
])

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0005),
              loss='mean_squared_error',
              metrics=['mse'])

history = model.fit(
    train_generator,
    epochs=30,
    validation_data=validation_generator
)
Added dropout layers after convolution and dense layers to reduce overfitting.
Applied data augmentation to increase training data variety.
Reduced learning rate from default to 0.0005 for smoother training.
Kept model complexity moderate with two convolutional layers and one dense layer.
Results Interpretation

Before: Training accuracy 98%, Validation accuracy 75%, Training loss 0.05, Validation loss 0.25

After: Training accuracy 90%, Validation accuracy 87%, Training loss 0.12, Validation loss 0.15

Adding dropout and data augmentation helps reduce overfitting by making the model less confident on training data and more generalizable to new data.
Bonus Experiment
Try using a pretrained model like MobileNetV2 as a feature extractor for landmark detection to improve accuracy further.
💡 Hint
Freeze the pretrained layers and add custom dense layers on top for landmark regression.

Practice

(1/5)
1. What is the main purpose of hand and face landmark detection in computer vision?
easy
A. To compress video files
B. To increase image resolution
C. To change the color of images
D. To find key points on hands and faces in images or videos

Solution

  1. Step 1: Understand the goal of landmark detection

    Landmark detection identifies important points on hands and faces to understand their shape and position.
  2. Step 2: Compare options with the goal

    Only To find key points on hands and faces in images or videos matches this goal by describing key point detection on hands and faces.
  3. Final Answer:

    To find key points on hands and faces in images or videos -> Option D
  4. Quick Check:

    Landmark detection = key points detection [OK]
Hint: Landmark detection means finding important points [OK]
Common Mistakes:
  • Confusing landmark detection with image enhancement
  • Thinking it changes image colors
  • Mixing it up with video compression
2. Which of the following is the correct way to import MediaPipe's hand landmark detection module in Python?
easy
A. import mediapipe.solutions.hands as mp_hands
B. import mediapipe.hands as mp_hands
C. import mediapipe as mp mp.solutions.hands
D. from mediapipe import hands

Solution

  1. Step 1: Recall MediaPipe import syntax

    MediaPipe modules are imported from mediapipe.solutions, e.g., mediapipe.solutions.hands.
  2. Step 2: Check each option

    import mediapipe.solutions.hands as mp_hands correctly imports mediapipe.solutions.hands as mp_hands. Others are incorrect or incomplete.
  3. Final Answer:

    import mediapipe.solutions.hands as mp_hands -> Option A
  4. Quick Check:

    Correct import = mediapipe.solutions.hands [OK]
Hint: MediaPipe modules come from mediapipe.solutions [OK]
Common Mistakes:
  • Using incorrect import paths
  • Trying to import submodules directly without solutions
  • Confusing alias names
3. Given the following Python code using MediaPipe for hand landmarks detection, what will be printed?
import mediapipe as mp
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(static_image_mode=True)
results = hands.process(image_rgb)
print(len(results.multi_hand_landmarks))
Assuming image_rgb contains one clear hand.
medium
A. 1
B. Error
C. None
D. 0

Solution

  1. Step 1: Understand the code flow

    The code processes an RGB image with one hand using MediaPipe Hands in static mode.
  2. Step 2: Interpret the output

    Since one hand is present, results.multi_hand_landmarks will contain one set of landmarks, so its length is 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    One hand detected = length 1 [OK]
Hint: Length of landmarks list equals number of detected hands [OK]
Common Mistakes:
  • Assuming zero when hand is present
  • Confusing None with empty list
  • Expecting error without checking input
4. You wrote this code to detect face landmarks but get an error:
import mediapipe as mp
mp_face = mp.solutions.face_mesh
face_mesh = mp_face.FaceMesh()
results = face_mesh.process(image_bgr)
print(results.multi_face_landmarks)
What is the likely cause of the error?
medium
A. Missing import for cv2
B. FaceMesh class does not exist
C. Input image should be RGB, not BGR
D. process() method requires grayscale image

Solution

  1. Step 1: Check input image format for MediaPipe FaceMesh

    MediaPipe expects RGB images, but the code uses image_bgr (BGR format).
  2. Step 2: Understand error cause

    Using BGR instead of RGB causes wrong color channels and likely errors in detection.
  3. Final Answer:

    Input image should be RGB, not BGR -> Option C
  4. Quick Check:

    MediaPipe needs RGB input images [OK]
Hint: Always convert BGR to RGB before MediaPipe processing [OK]
Common Mistakes:
  • Passing BGR images directly
  • Assuming FaceMesh class is missing
  • Thinking grayscale is required
5. You want to build a gesture recognition app using hand landmarks. Which approach best improves accuracy when hands are rotated or partially hidden?
hard
A. Only train on perfectly centered and clear hand images
B. Use data augmentation with rotated and occluded hand images during training
C. Ignore landmarks and use raw images directly
D. Use grayscale images instead of color

Solution

  1. Step 1: Understand challenges in gesture recognition

    Hands can appear rotated or partly hidden, so model must handle variations.
  2. Step 2: Choose best method to improve robustness

    Data augmentation with rotated and occluded images teaches model to recognize gestures despite changes.
  3. Final Answer:

    Use data augmentation with rotated and occluded hand images during training -> Option B
  4. Quick Check:

    Augmentation improves model robustness [OK]
Hint: Augment training data to handle rotations and occlusions [OK]
Common Mistakes:
  • Training only on perfect images
  • Ignoring landmarks reduces accuracy
  • Using grayscale loses important info