30

In OpenCV it is possible to save an image to disk with a certain jpeg compression. Is there also a way to do this in memory? Or should I write a function using cv2.imsave() that loads the file and removes it again from disk? If anyone knows a better way that is also fine.

The use case is real-time data augmentation. Using something else than OpenCV would cause possibly unnecessary overhead.

Example of desired function im = cv2.imjpgcompress(90)

1 Answer 1

66

You can use imencode:

encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
result, encimg = cv2.imencode('.jpg', img, encode_param)

(The default value for IMWRITE_JPEG_QUALITY is 95.)

You can decode it back with:

decimg = cv2.imdecode(encimg, 1)

Snippet from here

2
  • The shape of the encimg is different from that of im. Why is that? Before: 340 1080 3 After: 58154 1
    – Simon
    Nov 23, 2016 at 16:11
  • import cv2 filename = 'image.png' im = cv2.imread(filename) encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 80] result, im = cv2.imencode('.jpg', im, encode_param) print result
    – Simon
    Nov 23, 2016 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.