Reading .JPG image and saving it without resizing file

I want to write Python code that reads a .jpg image, resizes some of its RBG components, and saves it again without resizing the image.

I tried to load the image using OpenCV and PyGame, however, when I tried the simple Load / Save code using three different functions, the resulting images are larger than the original 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 result was 75.5K, 75.5K, 49.9K.

So, I'm not sure if I am missing something that makes the original image resize, even though I did only Load / Save or not?

And is there a more efficient library than OpenCV or PyGame ?!

+4
source share
2 answers

JPEG is a lossy image format. When you open and save one, you encode the whole image again. You can adjust the quality settings to get closer to the size of the original file, but you will lose some image quality independently. There is no general way to find out what the initial quality setting is, but if the file size is important, you can guess until you get it.

+7
source

The size of the output JPEG file depends on 3 things:

  • Sizes of the source image. In your case, they are the same for all three examples.
  • Color complexity of the image. An image with more details will be more than completely blank.
  • Quality setting used in the encoder. In your case, you used the default values, which are apparently higher for OpenCV and PyGame. A better setting will lead to the creation of a file that will be closer to the original (less loss), but more.

Due to the loss of JPEG character, some of this is a bit unpredictable. You can save the image with a specific quality setting, open this new image and save it again with the exact same quality setting, and it will probably be slightly different in size due to the changes that were made when you saved it for the first time .

+3
source

Source: https://habr.com/ru/post/1433013/


All Articles