Life2Coding
Save OpenCV Images in JPEG with Quality and PNG with Compression

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3

Goals:

In this tutorial, I will show you how to save OpenCV images in different image formats. We will also see how to use image quality for JPEG images and compression ratio for PNG images.

Documentation:

Python: cv2.imwrite(filename, img[, params]) → retval

Saves an image to a specified file.

Parameters: 

  • filename – Name of the file.
  • image – Image to be saved.
  • params
    • Format-specific save parameters encoded as pairs paramId_1, paramValue_1, paramId_2, paramValue_2, …. The following parameters are currently supported:
      • For JPEG, it can be a quality (CV_IMWRITE_JPEG_QUALITY) from 0 to 100 (the higher is the better). Default value is 95.
      • For PNG, it can be the compression level (CV_IMWRITE_PNG_COMPRESSION) from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3.
      • For PPM, PGM, or PBM, it can be a binary format flag (CV_IMWRITE_PXM_BINARY), 0 or 1. Default value is 1.

 Steps:

  • Load Image using cv2.imread()
  • Display Image using cv2.imshow()
  • We will define the image extension and also quality and compression ratio
  • Save the output in an image file using cv2.imwrite()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

Output:

Capture-e1517744118746 Save OpenCV Images in JPEG with Quality and PNG with Compression

life2coding_icon [] Save OpenCV Images in JPEG with Quality and PNG with Compression

Life2Coding

Technology Related Blog at Life2Coding
Feel free to contact us for your any kind of technical problems. We are here to help you.
life2coding_icon [] Save OpenCV Images in JPEG with Quality and PNG with Compression

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.