MTCNN Python Code to Collect Images from sub directories, Detect Face, Resize Images, Display a Sample Image
# Import necessary libraries
from mtcnn.mtcnn import MTCNN
import cv2
import os
# Initialize MTCNN detector
detector = MTCNN()
# Set the path to the directory containing the images on Your Computer. In Below example images are located at pycham prohect directory (Indian-celebrities/train) folder.
#Note: This folder contain sub folders, which actually contain images
image_dir = 'Indian-celebrities/train'
# Create an empty list to store the images
images = []
# Iterate through the subdirectories in the image directory
for subdir in os.listdir(image_dir):
subdir_path = os.path.join(image_dir, subdir)
# Iterate through the images in each subdirectory
for image_path in os.listdir(subdir_path):
# Load the image
image = cv2.imread(os.path.join(subdir_path, image_path))
# Detect the face in the image using MTCNN
result = detector.detect_faces(image)
# Extract the bounding box for the face
x1, y1, width, height = result[0]['box']
# Crop the image to only include the face
face_image = image[y1:y1 + height, x1:x1 + width]
# Resize the image to a fixed size
face_image = cv2.resize(face_image, (160, 160))
# Add the image to the list
images.append(face_image)
# Display a sample image
# Note: In below code, 32 is number of image which you want to display, you can chnage this no
sample_image = images[32]
cv2.imshow('Sample Image', sample_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Send Query