JupyterでOpenCVの画像をインライン表示

JupyterでOpenCVの画像をインライン表示

OpenCVで読み込んだ画像の明るさ調整等の処理を行った結果を、Jupyterですばやく確認したかったので、やってみた。

画像読み込み

OpenCVで画像を読み込む。
ここはいたって普通の読み込み方法。

import cv2
image = cv2.imread('/path/to/image.png')

Jupyterで表示

Jupyter(IPython)のライブラリを利用する。
画像データを表す、IPython.display.Imageと、Jupyter上で表示するIPython.display.display()関数で表示できる。

エンコードした画像データをbytes型で持つので、ファイルフォーマットを指定する。 普段の画像保存と同じように、自然画像のような場合には.jpgとかにしたほうがメモリに優しい。

from IPython.display import display, Image

def display_cv_image(image, format='.png'):
    decoded_bytes = cv2.imencode(format, image)[1].tobytes()
    display(Image(data=decoded_bytes))

display_cv_image(image, '.png')

f:id:uphy:20161211110607p:plain