Warning: Undefined variable $position in /home/pystyles/pystyle.info/public_html/wp/wp-content/themes/lionblog/functions.php on line 4897

OpenCV – ndarray 形式の画像を Notebook 上にインライン表示する方法について

OpenCV – ndarray 形式の画像を Notebook 上にインライン表示する方法について

概要

Jupyter Notebook では、Pillow の PIL Image 形式の画像は自動でインライン表示されますが、OpenCV で扱う ndarray 形式の画像は、配列の値がそのまま表示され、画像として表示できません。本記事では、Jupyter Notebook 上で ndarray 形式の画像をインラインで表示する方法について紹介します。

Advertisement

方法

  1. cv2.imencode() で、ndarray 形式の画像をエンコードされたバイト列に変換する。この関数は、変換が成功したかどうかの bool 値とエンコードされたバイト列を tuple で返す。
  2. バイト列を IPython.display.Image オブジェクトに変換する
  3. IPython.display.Image オブジェクトを IPython.display.display() で表示する
In [1]:
import cv2
from IPython import display


def imshow(img, format=".jpg", **kwargs):
    """ndarray 配列をインラインで Notebook 上に表示する。
    """
    img = cv2.imencode(format, img)[1]
    img = display.Image(img, **kwargs)
    display.display(img)


img = cv2.imread("sample.jpg")
imshow(img)

IPython.display.Image オブジェクトを作成する際に width または height を指定すると、画像は (width, height) に収まるようにリサイズして表示されます。大きい画像を表示したい場合に指定するとよいでしょう。

In [2]:
imshow(img, width=400)