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 decoding
cv2.imwrite('../data/Lena_compressed.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 0])

# check that image saved and loaded again image is the same as original one
saved_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 size
cv2.imwrite('../data/Lena_compressed.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 0])