Created
June 5, 2024 19:58
-
-
Save greg-randall/388e4e36cdb6548ef4a0c96a5132b467 to your computer and use it in GitHub Desktop.
Crops a folder of headshots to the face that it finds in the image.
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 matplotlib.pyplot as plt | |
from PIL import Image | |
# adjust these variables as necessary | |
dirname = "pix-for-crop" | |
put_dirname = "cropped" | |
simple_crop = False | |
# Check if the output directory exists, create it if it doesn't | |
if not os.path.exists(put_dirname): | |
os.mkdir(put_dirname) | |
# Load the cascade | |
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') | |
file_types = ('.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG') | |
files = [file_i | |
for file_i in os.listdir(dirname) | |
if file_i.endswith(file_types)] | |
filenames = [os.path.join(dirname, fname) | |
for fname in files] | |
print('found %d files' % len(filenames)) | |
filename_inc = 100 | |
filecount = 1 | |
for file in filenames: | |
img = cv2.imread(file) | |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
detected_faces = face_cascade.detectMultiScale(gray, 1.1, 4) | |
print("[%d of %d] %d detected faces in %s" % (filecount, len(filenames), len(detected_faces), file)) | |
for (x, y, w, h) in detected_faces: | |
crop_width = min(w, h) | |
if w >= crop_width and h >= crop_width: | |
image_to_crop = Image.open(file) | |
if simple_crop: | |
crop_area = (x, y, x+w, y+h) | |
else: | |
size_array = [] | |
size_array.append(y) | |
size_array.append(image_to_crop.height - (y+h)) | |
size_array.append(x) | |
size_array.append(image_to_crop.width - (x+w)) | |
size_array.sort() | |
short_side = size_array[0] | |
crop_area = (x - size_array[0] , y - size_array[0], x+w + size_array[0], y+h + size_array[0]) | |
cropped_image = image_to_crop.crop(crop_area) | |
filename = os.path.basename(file) | |
cropped_image.save(put_dirname + "/" + filename, "JPEG") | |
filename_inc += 1 | |
filecount += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment