批量识别人脸图片并裁切

简单水一篇

import os
import cv2

# Load Haar Cascade classifier for face detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# 需要裁切图片的文件夹
dir_path = './test1/'

# 保存之后的图片
os.makedirs('./res/', exist_ok=True)

# Loop over all images in directory
for filename in os.listdir(dir_path):
    if not filename.endswith('.jpg'):
        continue
    
    # Load image
    img = cv2.imread(os.path.join(dir_path, filename))
    
    # Convert image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # Detect faces
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
    
    # Loop over all detected faces
    for i, (x, y, w, h) in enumerate(faces):
        # Crop face from image
        face_img = img[y:y+h, x:x+w]
        
        # 保存图片
        cv2.imwrite(os.path.join('./res/', f'{filename}_{i}.jpg'), face_img)

你可能感兴趣的:(opencv,计算机视觉,python)