Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a .JPG Image and Saving it without file size change

I want to write a python code that reads a .jpg picture, alter some of its RBG components and save it again, without changing the picture size.

I tried to load the picture using OpenCV and PyGame, however, when I tried a simple Load/Save code, using three different functions, the resulting images is greater in size than the initial image. This is the code I used.

>>> import cv, pygame # Importing OpenCV & PyGame libraries.
>>> image_opencv = cv.LoadImage('lena.jpg')
>>> image_opencv_matrix = cv.LoadImageM('lena.jpg')
>>> image_pygame = pygame.image.load('lena.jpg')
>>> cv.SaveImage('lena_opencv.jpg', image_opencv)
>>> cv.SaveImage('lena_opencv_matrix.jpg', image_opencv_matrix)
>>> pygame.image.save(image_pygame, 'lena_pygame.jpg')

The original size was 48.3K, and the resulting are 75.5K, 75.5K, 49.9K.

So, I'm not sure I'm missing something that makes the picture original size changes, although I only made a Load/Save, or not?

And is there a better library to use rather than OpenCV or PyGame ?!

like image 731
Mahmoud Aladdin Avatar asked Dec 27 '22 18:12

Mahmoud Aladdin


2 Answers

JPEG is a lossy image format. When you open and save one, you’re encoding the entire image again. You can adjust the quality settings to approximate the original file size, but you’re going to lose some image quality regardless. There’s no general way to know what the original quality setting was, but if the file size is important, you could guess until you get it close.

like image 112
Josh Lee Avatar answered Dec 29 '22 07:12

Josh Lee


The size of a JPEG output depends on 3 things:

  1. The dimensions of the original image. In your case these are the same for all 3 examples.
  2. The color complexity within the image. An image with a lot of detail will be bigger than one that is totally blank.
  3. The quality setting used in the encoder. In your case you used the defaults, which appear to be higher for OpenCV vs. PyGame. A better quality setting will generate a file that's closer to the original (less lossy) but larger.

Because of the lossy nature of JPEG some of this is slightly unpredictable. You can save an image with a particular quality setting, open that new image and save it again at the exact same quality setting, and it will probably be slightly different in size because of the changes introduced when you saved it the first time.

like image 33
Mark Ransom Avatar answered Dec 29 '22 09:12

Mark Ransom