Hello! 😃 I recently needed to compress images for work, but most free image compressors have a file size requirement, so I decided to create my own using python and opencv.
In this post I will show how I did it and I hope it helps anyone with the same problem
First we need to create and activating the virtual environment, this can be done with the following command:
python3 -m venv env source env/bin/activate
Done 😎 next we can get to writing the code.
Next open up a file called "requirements.txt" and insert the following:
To install the requirements use the following command:
pip install -r requirements.txt
Next open up a file called "main.py", first we will require some packages so write the following:
import cv2 import os import argparse
Next we will create a simple function to display the file size of a file in MB:
def show_file_size(file): file_size = os.path.getsize(file) file_size_mb = round(file_size / 1024, 2) print("File size is now " + str(file_size_mb) + "MB")
Nothing too complicated just a couple of lines to display the file size of a file.
Finally we need to create a main function:
if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to input file") ap.add_argument("-c", "--compression", required = True, help = "Compression level") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imwrite("compressed_image.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, args["compression"]]) print("Image Compressed Successfully") show_file_size("compressed_image.jpg")
Here we use ArgumentParser to parse the user's "image" and "compression" arguments we then read the image file using opencv, and then use the imwrite function to output the compressed file. Finally we then display the new file size to the user.
Done! 😆 Image compression in just a few lines of code.
Here I have shown how to implrement simple image compression using opencv and python, I hope this article has been of some use to you.
As always you can find the source code on my GitHub: https://github.com/ethand91/python-image-compression
Feel free to play around with different compressions 👀
Like me work? I post about a variety of topics, if you would like to see more please like and follow me. Also I love coffee.
If you are looking to learn Algorithm Patterns to ace the coding interview I recommend the following course
Original link to post: https://ethan-dev.com/post/image-compression-with-opencv-python