🔍 About This Code Showcase
This curated code snippet demonstrates how the AI Group Photo Generator performs intelligent subject extraction and composition blending to create professional group photographs.
Full deployment scripts, API integrations, and proprietary details are omitted for clarity and security. This showcase highlights the core algorithmic approach and key technical implementation.
🧠 Core Algorithm: Subject Detection & Extraction
The heart of the AI Group Photo Generator lies in its ability to intelligently detect and extract subjects from individual photos. Here's the core implementation:
import cv2
import numpy as np
from rembg import remove
from PIL import Image
class SubjectExtractor:
def __init__(self):
self.face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
def extract_subject(self, image_path):
"""
Extract the main subject from an image using AI-powered background removal
and intelligent face detection for optimal composition placement.
Args:
image_path (str): Path to the input image
Returns:
tuple: (subject_image, face_coordinates, subject_mask)
"""
original_image = Image.open(image_path)
subject_with_transparency = remove(original_image)
cv_image = cv2.cvtColor(np.array(original_image), cv2.COLOR_RGB2BGR)
gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
faces = self.face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
subject_bounds = self._calculate_subject_bounds(subject_with_transparency)
return subject_with_transparency, faces, subject_bounds
def _calculate_subject_bounds(self, subject_image):
"""Calculate the bounding box of the extracted subject for precise positioning"""
img_array = np.array(subject_image)
alpha_channel = img_array[:, :, 3]
rows = np.any(alpha_channel > 0, axis=1)
cols = np.any(alpha_channel > 0, axis=0)
y_min, y_max = np.where(rows)[0][[0, -1]]
x_min, x_max = np.where(cols)[0][[0, -1]]
return (x_min, y_min, x_max - x_min, y_max - y_min)
🎨 Intelligent Composition Engine
Once subjects are extracted, the composition engine arranges them naturally using advanced positioning algorithms:
class CompositionEngine:
def create_group_composition(self, subjects, canvas_size=(1920, 1080)):
"""
Intelligently arrange multiple subjects into a natural group photo composition.
Uses golden ratio and visual balance principles for professional results.
"""
canvas = Image.new('RGBA', canvas_size, (240, 240, 240, 255))
positions = self._calculate_optimal_positions(subjects, canvas_size)
for subject, position in zip(subjects, positions):
scaled_subject = self._apply_depth_scaling(subject, position)
final_subject = self._apply_lighting_effects(scaled_subject, position)
canvas = self._blend_subject(canvas, final_subject, position)
return canvas
def _calculate_optimal_positions(self, subjects, canvas_size):
"""Calculate positions using compositional rules and visual balance"""
width, height = canvas_size
positions = []
golden_ratio = 1.618
num_subjects = len(subjects)
if num_subjects == 2:
pos1_x = width // golden_ratio
pos2_x = width - (width // golden_ratio)
positions = [(pos1_x, height * 0.3), (pos2_x, height * 0.3)]
elif num_subjects == 3:
center_x = width // 2
positions = [
(center_x, height * 0.25),
(center_x - width * 0.2, height * 0.4),
(center_x + width * 0.2, height * 0.4)
]
return positions