PILを用いた画像圧縮(jpeg, jpeg2000)

pythonのライブラリPIL(Python Imaging Library)を用いてjpegjpeg2000による圧縮を行う方法を示す。

 

from PIL import Image

Image.open('org_img.png').save('new_img.jpg', format='jpeg', quality=50,  optimize=True)

 

qualityの値を変化させることで精度を調整できる。

(おそらく1から100)

 

同様にJPEG2000で圧縮するには

Image.open('org_img.png').save('new_img.j2k', 'JPEG2000', quality_mode='dB',  quality_layers=[35])

 

35となっている部分を変化させることによって精度を調整できる。

 

JPEG2000の圧縮の際に

AttributeError: module 'PIL._imaging' has no attribute 'jpeg2k_encoder'

OSError: encoder jpeg2k not available

 

などといったエラーが出た場合には、OpenJPEGをインストールし、PILをビルドする必要があるらしい。

詳しくは

Image file formats — Pillow (PIL Fork) 7.0.0 documentation

JPEG2000のNoteを確認すると良い。