Simple Image Compression Using OpenCV And Python


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

Creating the environment

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.

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 "", 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")

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:

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.

โ€œBuy Me A Coffeeโ€

If you are looking to learn Algorithm Patterns to ace the coding interview I recommend the following course

Original link to post: