Compress images using Singular Value Decomposition (SVD)
Project description
Shrinkme - SVD-Based Image Compression
Compress images intelligently using Singular Value Decomposition (SVD), a mathematical technique that reduces file size while maintaining visual quality. Perfect for batch processing, thumbnail generation, or optimizing image storage.
🚀 Features
- SVD-Based Compression: Uses mathematical decomposition to analyze and compress images
- Flexible Resizing: Resize images before or after compression to fit your needs
- Dual Interface: Use as a Python library or command-line tool
- Detailed Metrics: Get compression ratios, storage savings, and file size statistics
- Visual Comparison: Preview original vs. compressed images side-by-side
- Batch Processing: Easily compress multiple images programmatically
- Cross-Platform: Works on Windows, macOS, and Linux
📦 Installation
Via pip (Recommended)
pip install shrinkme
From source
git clone https://github.com/PriyankaGayale/shrinkme.git
cd shrinkme
pip install -e .
🎯 Quick Start
Command Line
# Basic compression
shrinkme compress --input image.jpg --k 50
# Compress with resizing
shrinkme compress --input image.jpg --k 50 --resize 800x600
# Compress and visualize
shrinkme compress --input image.jpg --k 50 --visualize
# Save to custom output path
shrinkme compress --input image.jpg --k 50 --output result.jpg
Python Library
from shrinkme import load_image, compress_image, save_compressed_image
# Load image
img = load_image("image.jpg")
# Compress with k=50 singular values
compressed = compress_image(img, k=50)
# Save result
save_compressed_image(compressed, "output.jpg")
📚 Usage Examples
Basic Compression
from shrinkme import load_image, compress_image, save_compressed_image, print_metrics, calculate_compression_metrics
img = load_image("sample.jpg")
compressed = compress_image(img, k=50)
metrics = calculate_compression_metrics("sample.jpg", img, k=50)
print_metrics(metrics, k=50)
save_compressed_image(compressed, "compressed.jpg")
Compression with Resizing
from shrinkme import resize_image, compress_image, resize_output, save_compressed_image
# Resize before compression
img = resize_image("sample.jpg", width=800, height=600)
compressed = compress_image(img, k=40)
save_compressed_image(compressed, "result.jpg")
# Or resize after compression
img = load_image("sample.jpg")
compressed = compress_image(img, k=50)
resized = resize_output(compressed, width=1024, height=768)
save_compressed_image(resized, "result.jpg")
Batch Processing
from pathlib import Path
from shrinkme import load_image, compress_image, save_compressed_image
image_dir = Path("images/")
for img_path in image_dir.glob("*.jpg"):
img = load_image(str(img_path))
compressed = compress_image(img, k=50)
output_path = f"compressed/{img_path.name}"
save_compressed_image(compressed, output_path)
print(f"✓ Processed {img_path.name}")
Finding Optimal K Value
from shrinkme import load_image, compress_image, calculate_compression_metrics
img = load_image("image.jpg")
for k in [20, 40, 60, 80, 100]:
compressed = compress_image(img, k)
metrics = calculate_compression_metrics("image.jpg", img, k)
ratio = metrics["compression_ratio"]
saved = metrics["space_saved"] * 100
print(f"k={k}: {ratio:.2f}x compression, {saved:.1f}% space saved")
🔧 API Reference
See docs/API.md for complete function documentation.
Core Functions
load_image(path)- Load image and convert to grayscale matrixcompress_image(img_matrix, k)- Compress using SVD with k singular valuescalculate_compression_metrics(path, img_matrix, k)- Get compression statisticssave_compressed_image(matrix, output_path)- Save compressed image to fileshow_images(original, compressed)- Display before/after comparison
Utility Functions
resize_image(path, width, height)- Resize image before compressionresize_output(matrix, width, height)- Resize after compressionparse_dimension_string(dim_str)- Parse "WIDTHxHEIGHT" formatpreserve_aspect_ratio(...)- Calculate dimensions preserving aspect ratio
📖 How It Works
Mathematical Background
Shrinkme uses Singular Value Decomposition (SVD) to compress images:
- Convert image to matrix: Each pixel is a value (0-255)
- Decompose matrix: A = U × Σ × V^T
- Keep top k singular values: Only use most significant components
- Reconstruct image: A_k ≈ U_k × Σ_k × V_k^T
Storage Savings:
- Original:
m × nvalues - Compressed:
k(m + n + 1)values
Example: A 512×512 image with k=50:
- Original: 262,144 values
- Compressed: 51,250 values
- Compression ratio: 5.1x
- Space saved: 80.4%
Why SVD for Images?
Natural images contain redundant information (similar colors in large areas). SVD exploits this by keeping only the most important information (highest singular values) and discarding the rest.
🎮 CLI Commands
shrinkme compress --help
Options:
--input, -i(required): Path to input image--k, -k(required): Number of singular values to keep--output, -o: Save path (default: compressed_output.jpg)--resize, -r: Resize input to WIDTHxHEIGHT before compression--resize-output: Resize output to WIDTHxHEIGHT after compression--visualize, -v: Show before/after comparison--metrics, -m: Display compression statistics (default: true)
📋 Requirements
- Python 3.8 or higher
- numpy >= 1.21.0
- Pillow >= 8.0.0
- matplotlib >= 3.3.0 (for visualization)
🧪 Testing
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run with coverage
pytest --cov=shrinkme
🚧 Development
Setup Development Environment
git clone https://github.com/PriyankaGayale/shrinkme.git
cd shrinkme
pip install -e ".[dev]"
Code Style
# Format code
black shrinkme/
# Check style
flake8 shrinkme/
# Sort imports
isort shrinkme/
Building Distribution Package
pip install build twine
# Build
python -m build
# Test upload
twine upload --repository testpypi dist/*
# Upload to PyPI
twine upload dist/*
See CONTRIBUTING.md for detailed contribution guidelines.
📄 License
This project is licensed under the MIT License - see LICENSE file for details.
🙏 Acknowledgments
- Built with NumPy for efficient matrix operations
- Image processing with Pillow
- Visualization using Matplotlib
📞 Support & Feedback
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Security: See SECURITY.md for vulnerability reporting
💡 Tips & Tricks
Choosing the Right K Value
| K Value | Use Case |
|---|---|
| 10-20 | Aggressive compression, thumbnails |
| 30-50 | Balanced quality/compression |
| 60-100 | High quality, web images |
| 100+ | Minimal compression, archival |
Performance Tips
- Resize first: Smaller images compress faster
- Batch process: Use loops for efficiency
- Experiment: Test different k values to find sweet spot
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file shrinkme-0.1.0.tar.gz.
File metadata
- Download URL: shrinkme-0.1.0.tar.gz
- Upload date:
- Size: 125.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6ad493ae1e379dc578fc6524feee7ec4630891e2128e796ccb810ea14747f6db
|
|
| MD5 |
062d9ec9847ce613fcd04f88d82a4f5f
|
|
| BLAKE2b-256 |
6143c2859990407088a380f088674326ca704c9752cd27adc129406cd4bf5cb5
|
File details
Details for the file shrinkme-0.1.0-py3-none-any.whl.
File metadata
- Download URL: shrinkme-0.1.0-py3-none-any.whl
- Upload date:
- Size: 12.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e84633c5aa1ac26751847597486275ccc104bfd9af2dea8e08bf0700b717943c
|
|
| MD5 |
7db424f5f984e0ed586798fd8acbbf1a
|
|
| BLAKE2b-256 |
54399ba9710136b0bca5010b3d0c399bfa932a9e385ce1ee0828b527e0129cce
|