Permalink
Cannot retrieve contributors at this time
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?
minichall_abolande/crop_and_save_images_test.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
58 lines (46 sloc)
2.16 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = 'rgb_test' | |
path_to_cr_data = 'rgb_test_crop' | |
# 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) | |
else: | |
# If no face with at least one eye detected, copy the original image | |
shutil.copyfile(img_path, os.path.join(path_to_cr_data, rel_path, file)) | |
# Process images in the 'train_classified' directory | |
process_images_in_directory(path_to_data) | |
print("Images have been cropped and saved in the 'train_cropped' directory.") | |
# 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.") |