文系プログラマによるTIPSブログ

文系プログラマ脳の私が開発現場で学んだ事やプログラミングのTIPSをまとめています。

s3への画像配置でAWS LambdaのPython3.6+Pillow-SIMDで複数サムネイル生成する

前回からちょっとだけ進化します〜


f:id:treeapps:20171029033317p:plain

www.bunkei-programmer.net

前回は、Python Pillowでサムネイルを作成しましたね。

しかしですね、実はPillowより更に一歩進んだPillow-SIMDというものが存在するのです。

Pithon Pillow-SIMD

github.com

Pillowと100%互換がある

Pillow-SIMD is "following" Pillow. Pillow-SIMD versions are 100% compatible drop-in replacements for Pillow of the same version.

このように、Pillow-SIMDは、Pillowと100%互換を持ちます。

超高速

The results show that for resizing Pillow is always faster than ImageMagick, Pillow-SIMD, in turn, is even faster than the original Pillow by the factor of 4-6. In general, Pillow-SIMD with AVX2 is always 16 to 40 times faster than ImageMagick and outperforms Skia, the high-speed graphics library used in Chromium.

更に、Pillowと比較して大体4〜6倍高速、ImageMagickと比較して大体16〜40倍、高速のようです。

Pillow-SIMD project is production-ready. The project is supported by Uploadcare, a SAAS for cloud-based image storing and processing.

そして、production-readyという事で、production環境でもイケるようです。

合計ファイルサイズ

Pillowの合計ファイルサイズ
$ du -ms ./Pillow
19	./Pillow
Pillow-SIMDの合計ファイルサイズ
$ du -ms Pillow-SIMD
4	Pillow-SIMD

Pillowが19MByteに対して、Pillo-SIMDはなんと4MByteです。

AWS Lambda + Pillow-SIMDで画像変換

まず、前回はPillowで画像変換を行いました。

これを、Pillow-SIMDに置き換えます。正直凄く簡単に置き換えられます。

https://github.com/uploadcare/pillow-simd#installation

pip uninstall pillow
CC="cc -mavx2" pip install -U --force-reinstall pillow-simd

1行目は、既にPillowがインストールされている場合はアンインストールしてね、という事ですが、AWS Lambdaで使用する場合はpipにインストールしないので、これは飛ばして大丈夫です。

↑はこれはpipにインストールする形式なので、Lambdaにアップロードできるようにローカルにモジュールをインストールさせます。

CC="cc -mavx2" pip install -U --force-reinstall pillow-simd -t .

これだけです。「-t .」を追加しただけです。後はPillowと全く同じ手順でlambdaにアップロードすれば、Pillowと全く同じように使用できます。

一応手順を書いておくと、以下になります。

setup.cfg

AWS LambdaにPillow-SIMDを反映するため、以下を用意します。

[install]
install-purelib=$base/lib64/python

docs.aws.amazon.com

Pillow-SIMDをインストール

CC="cc -mavx2" pip install -U --force-reinstall pillow-simd -t .

後は、前回同様にzip圧縮してlambdaにアップロードするだけです。

画像変換ソースコード

PillowとAPIが同一なので、Pillowで動くコードは、Pillow-SIMDでも動きます。私が検証した感じだと、1行も変えずに動きました。

なので、前回の記事の以下のコードがそのまま使えます。
www.bunkei-programmer.net

雑感

ImageMagickはそろそろ嫌だなー、という事でPillowを始め、そして更にPillow-SIMDをやってみました。

Pillowと比較してPillow-SIMDは4〜6倍速い(自称)そうですが、そこまで体感はできませんね。こればかりはちゃんと計測してみないと解りませんが、少なくともImageMagickよりはかなり速いように思えます。画質も申し分無く、機能も中々多いです。

もしPythonが嫌いでなければ、Pillow-SIMDで画像変換を行うと、幸せになれるかもしれません。