🤳 AI Group Photo Generator

Core Source Code & Implementation Logic

Python Streamlit Computer Vision AI Processing

🔍 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:

📄 subject_extractor.py
import cv2 import numpy as np from rembg import remove from PIL import Image class SubjectExtractor: def __init__(self): # Initialize face detection cascade for precise subject identification 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) """ # Load and preprocess the image original_image = Image.open(image_path) # Use AI model to remove background - this is the key innovation # The model understands human forms and preserves natural edges subject_with_transparency = remove(original_image) # Convert to OpenCV format for face detection cv_image = cv2.cvtColor(np.array(original_image), cv2.COLOR_RGB2BGR) gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY) # Detect faces to determine optimal positioning in group composition faces = self.face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5) # Calculate subject bounds for intelligent scaling and positioning 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""" # Convert to numpy array and find non-transparent pixels img_array = np.array(subject_image) alpha_channel = img_array[:, :, 3] # Find the bounds of the actual subject (non-transparent areas) 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:

📄 composition_engine.py
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. """ # Create blank canvas with professional background canvas = Image.new('RGBA', canvas_size, (240, 240, 240, 255)) # Calculate optimal positions using golden ratio and visual weight positions = self._calculate_optimal_positions(subjects, canvas_size) for subject, position in zip(subjects, positions): # Scale subject based on distance from camera (depth simulation) scaled_subject = self._apply_depth_scaling(subject, position) # Blend with natural lighting and shadow effects final_subject = self._apply_lighting_effects(scaled_subject, position) # Composite onto canvas with edge blending for realism 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 = [] # Use rule of thirds and golden ratio for natural arrangement golden_ratio = 1.618 num_subjects = len(subjects) if num_subjects == 2: # Two subjects: use golden ratio positioning 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: # Three subjects: triangular composition for visual harmony center_x = width // 2 positions = [ (center_x, height * 0.25), # Center front (center_x - width * 0.2, height * 0.4), # Left back (center_x + width * 0.2, height * 0.4) # Right back ] return positions

⚙️ Technical Implementation Notes

Key Algorithms & Innovations

Why This Approach Works