How to do it...

Here are the steps for this recipe:

  1. First, read the image:
img = cv2.imread('../data/Lena.png')
  1. Save the image in PNG format without losing quality, then read it again to check whether all the information has been preserved during writing onto the disk:
# save image with lower compression—bigger file size but faster decodingcv2.imwrite('../data/Lena_compressed.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 0])# check that image saved and loaded again image is the same as original onesaved_img = cv2.imread(params.out_png)assert saved_img.all() == img.all()
  1. Save the image in the JPEG format:
# save image with lower quality—smaller file sizecv2.imwrite('../data/Lena_compressed.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 0])

Get OpenCV 3 Computer Vision with Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.