Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import os
import cv2
import shutil
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
def get_cropped_image_if_2_eyes(image_path):
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
if len(eyes) >= 1:
return roi_color
def resize_image(image, width=224, height=224):
return cv2.resize(image, (width, height))
path_to_data = 'train_classified'
path_to_cr_data = 'train_cropped'
# Create cropped directory if not exist
if not os.path.exists(path_to_cr_data):
os.makedirs(path_to_cr_data)
# Function to process images in a directory
def process_images_in_directory(directory):
for subdir, _, files in os.walk(directory):
for file in files:
img_path = os.path.join(subdir, file)
cropped_image = get_cropped_image_if_2_eyes(img_path)
if cropped_image is not None:
# Resize to 224x224
resized_image = resize_image(cropped_image)
rel_path = os.path.relpath(subdir, path_to_data)
target_dir = os.path.join(path_to_cr_data, rel_path)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
cv2.imwrite(os.path.join(target_dir, file), resized_image)
# Process images in the 'train_small' directory
process_images_in_directory(path_to_data)
print("Images have been cropped, resized to 224x224, and saved in the 'cropped' directory.")