After loading the jpg file in OpenCV, the file size increases when you export it.

Asked 2 years ago, Updated 2 years ago, 125 views

Prerequisites/Problems

Version:
Python 3.7.3
OpenCV 4.1.0

If you read the jpg file with the imread function and write the jpg file with the imwrite function without any action, the jpg file size will be larger than the jpg file size from which you read it.

Specifically, it is as follows.
Loaded from jpg: 1,209KB
Post-write jpg:1608KB

I tried several different jpgs, but all of them have similar proportions and file sizes.

Also, there was no difference between the number of pixels, image size, and number of channels between the image from which it was read and the image after writing.

As a background, I used OpenCV to put text on the image to be processed, but the file size was abnormally large, so after reading the image, I ran the image without processing it.
 

Source Code

import cv2

im=cv2.imread('target.jpg')
cv2.imwrite ('after.jpg', im)

Tried

With reference to the following, I tried all the settings when writing jpg, such as IMWRITE_JPEG_QUALITY, but the file size still gets bigger.

https://docs.opencv.org/3.4.3/d4/da8/group__imgcodecs.html

Also, when comparing the read source jpg with the post-write jpg using WinMerge and ImageMagick, we can see a big difference, but we don't know why.

I would appreciate it if you could tell me the reason above and how to write the file without changing the size of the file.
Thank you for your cooperation.

python python3 opencv

2022-09-30 21:42

1 Answers

The JPEG quality setting is higher than the original image, so I think the size is bigger.

import cv2
im=cv2.imread('image1.jpg')
cv2.imwrite('after10.jpg', im, [cv2.IMWRITE_JPEG_QUALITY, 10])
cv2.imwrite('after20.jpg',im,[cv2.IMWRITE_JPEG_QUALITY,20])
cv2.imwrite('after30.jpg',im,[cv2.IMWRITE_JPEG_QUALITY,30])
cv2.imwrite('after40.jpg',im,[cv2.IMWRITE_JPEG_QUALITY,40])
cv2.imwrite('after70.jpg',im,[cv2.IMWRITE_JPEG_QUALITY,70])
cv2.imwrite('after80.jpg',im,[cv2.IMWRITE_JPEG_QUALITY,80])
cv2.imwrite('after90.jpg',im,[cv2.IMWRITE_JPEG_QUALITY,90])
cv2.imwrite('after95.jpg',im,[cv2.IMWRITE_JPEG_QUALITY,95])

cv2.__version__
'3.4.1'

In our environment, we were able to specify the quality with the above code.
Windows 10 environment.It depends on the original image, but I have confirmed that the test image will be smaller than the original image if it is less than 60%.


2022-09-30 21:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.