This project demonstrates the fundamentals of Digital Image Processing (23DSDE12) through mask-based foreground extraction and image compositing. Using a transparent image of a character (Tom/Jerry), the script dynamically generates a binary mask and blends the foreground onto a new cartoon background scene.
The repository provides two parallel implementations:
- MATLAB (
experiment1.m): The primary academic implementation. - Python/OpenCV (
experiment1.py): A production-grade implementation mirroring the exact MATLAB logic.
- Automatic Mask Generation: Automatically detects and extracts the alpha channel of transparent images (
.png) to create flawless binary masks without manual thresholding. - Robust Path Resolution: Compatible with both local VS Code execution and MATLAB Online's virtual file system.
- Cross-Language Validation: Verifies results by implementing the exact mathematical operations in both MATLAB and Python.
- Automated Directory Management: Automatically generates the
output/directory and saves processed step-by-step images.
📦 Foreground-Extraction
┣ 📂 input
┃ ┣ 📜 tom.png # Foreground object (with alpha channel)
┃ ┣ 📜 jerry.png # Alternate foreground object
┃ ┗ 📜 background.jpg # Background scene
┣ 📂 output
┃ ┣ 📜 composite.png # Final blended image
┃ ┣ 📜 mask.png # Extracted binary mask
┃ ┣ 📜 extracted_fg.png # Foreground cut-out
┃ ┣ 📜 masked_bg.png # Background with hole punched
┃ ┗ 📜 Experiment1_Results.png # 2x3 Subplot showing all steps
┣ 📜 experiment1.m # MATLAB implementation
┣ 📜 experiment1.py # Python/OpenCV implementation
┗ 📜 README.md
- Open MATLAB Desktop or MATLAB Online.
- Navigate to this repository's directory.
- Open
experiment1.mand click Run. - The output subplot will render, and files will be saved in
output/.
# Install dependencies
pip install opencv-python numpy matplotlib
# Run the pipeline
python experiment1.py- Read & Preprocess: Loads images and extracts the alpha transparency channel to use as a master mask.
- Resize: Rescales the background matrix and the mask matrix to perfectly match the foreground object dimensions using bicubic interpolation.
- Binarization & Precision: Normalizes all image matrices to double-precision
[0, 1]to ensure pixel-perfect array multiplication. - Compositing:
Extracted Foreground = fg .* maskMasked Background = bg .* (1 - mask)Final Output = Extracted Foreground + Masked Background
Sanyog Kumar Singh
USN: 23BTRDC034
Subject: Digital Image Processing (23DSDE12)