LoginSignup
7
5

More than 3 years have passed since last update.

OpenEXR画像ファイルをpythonで読みこむ

Last updated at Posted at 2019-06-16

仕事で扱うことになった画像データが見慣れない拡張子「.exr」のファイルだったのでなんだろうと思ったらHDR用の画像フォーマットであるopenEXR形式でした。openCVのcv2.imread()で読んでみたところfloatの値が整数で取得されちゃって上手くいきませんでしたので、OpenEXRパッケージを使って読み込みました。なお、以下のOpenEXRのドキュメントにあったコードをベースにやってます。

OpenEXR packageのドキュメント
https://excamera.com/articles/26/doc/intro.html

試行環境

Windows10
python 3.6

読み込み手順

まず、OpenEXRをインストールします。pipで簡単に入ります。

terminal
pip install OpenEXR

Windows環境の人はpipで入らなかったりするので、その時は私的ビルドバイナリを使うと入るかも
https://www.lfd.uci.edu/~gohlke/pythonlibs/#openexr

画像を読んできて表示します。

python
import numpy as np
import matplotlib.pyplot as plt
import OpenEXR, Imath, array

filePath = 'hoge.exr'

# ファイルを読み込む
pt = Imath.PixelType(Imath.PixelType.FLOAT)
img_exr = OpenEXR.InputFile(filePath)

# 読んだEXRファイルからRGBの値を取り出し
r_str, g_str, b_str = img_exr.channels('RGB', pt)
red = np.array(array.array('f', r_str))
green = np.array(array.array('f', g_str))
blue = np.array(array.array('f', b_str))

# 画像サイズを取得
dw = img_exr.header()['dataWindow']
size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
print(size)

# openCVで使えるように並べ替え
img = np.array([[r, g, b] for r, g, b in zip(red, green, blue)])
img = img.reshape(size[1], size[0], 3)

# 画像を表示
plt.figure(dpi=300)
plt.imshow(img)
plt.show()

なんだか回りくどい読み方だなと思うんですが、ほぼ公式のサンプルコードそのままなのでこれで良いようです。僕の用途もそれほどスピードを求められないのでこれで問題ない筈ですが、速さを求められる用途だとarrayで一旦変換するなんてのは無駄に思えちゃいますよね。
https://excamera.com/articles/26/doc/openexr.html

えんじょい

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5