This is a Python program I wrote for fun to apply linear algebra theory I learned in Monash uni. The code uses singular value expansion method to reduce the size of an image. Here are compression examples, featuring my cat Marmite.
First, install Python. Next, install dependencies:
pip install numpy
pip install imageio
Finally, download the code of the image compressor (requires git):
git clone https://github.com/evgenyneu/image_compressor_python.git
cd image_compressor_python
Compress an image file marmite.jpg using ten terms of the singular value expansion:
python src/compress.py marmite.jpg --terms=10
It creates an image named marmite_10_terms_25.0x_compression.jpg
that looks like this:
You can experiment with the --terms
option and see how it affects the image quality and compression ratio.
-h, --help show this help message and exit
--output OUTPUT path to the compressed image that will be created
--terms TERMS number of terms in the singular value expansion
--iterations ITERATIONS
number of iterations of the power method
--notext do not put text on the image
This following program allows to compress many images with different quality all at once. This can be useful for comparing many different outcomes and see how the terms
setting affects image quality:
$ python src/process_samples.py INPUT_DIR OUTPUT_DIR
Replace INPUT_DIR
with the name of directory that contains images you want to compress, in JPG, PNG or BMP format. All images in the directory will be compressed.
Replace OUTPUT_DIR
with a name of the directory where you want compressed images to be placed.
This example uses the images from images/for_compression
directory:
$ python src/process_samples.py images/for_compression images/compressed/
Creating images:
images/compressed/100x100/marmite_100x100_1_terms_49.8x_compression.jpg
images/compressed/100x100/marmite_100x100_2_terms_24.9x_compression.jpg
images/compressed/100x100/marmite_100x100_5_terms_10.0x_compression.jpg
images/compressed/100x100/marmite_100x100_10_terms_5.0x_compression.jpg
images/compressed/100x100/marmite_100x100_20_terms_2.5x_compression.jpg
The program produced the following compressed images featuring my cat Marmite. The image are 1000 by 1000 pixels. The compression results for images of different sizes are located here.
Install pytest
pip install pytest
and run the unit tests:
pytest
This work is in public domain.