10

I have generated some depth maps using blender and have saved z-buffer values(32 bits) in OpenEXR format. Is there any way to access values from a .exr file (pixel by pixel depth info) using OpenCV 2.4.13 and python 2.7? There is no example anywhere to be found. All I can see in documentation that this file format is supported. But trying to read such a file results in error.

new=cv2.imread("D:\\Test1\\0001.exr")
cv2.imshow('exr',new)
print new[0,0]

Error:

print new[0,0]
TypeError: 'NoneType' object has no attribute '__getitem__'

and

cv2.imshow('exr',new)
cv2.error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow

Closest I found is this link and this link.

gaya
  • 463
  • 2
  • 6
  • 22
  • 1
    You might want to look at [this](https://stackoverflow.com/questions/25413604/how-to-load-a-many-channel-exr-in-android) – Rick M. Jun 20 '17 at 08:37
  • I also found this http://excamera.com/articles/26/doc/index.html just now. (: – gaya Jun 20 '17 at 09:00

3 Answers3

11

I might be a little late to the party but; Yes you can definitely use OpenCV for that.

cv2.imread(PATH_TO_EXR_FILE,  cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)  

should get you what you need

lwohlhart
  • 1,829
  • 12
  • 20
3

Full solution

@Iwohlhart's solution threw an error for me and following fixed it,

# first import os and enable the necessary flags to avoid cv2 errors

import os
os.environ["OPENCV_IO_ENABLE_OPENEXR"]="1"
import cv2

# then just type in following

img = cv2.imread(PATH2EXR, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)
'''
you might have to disable following flags, if you are reading a semantic map/label then because it will convert it into binary map so check both lines and see what you need
''' 
# img = cv2.imread(PATH2EXR) 
 
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
2

You can use OpenEXR package

pip --no-cache-dir install OpenEXR

If the above fails, install the OpenEXR dev library and then install the python package as above

sudo apt-get install openexr
sudo apt-get install libopenexr-dev

If gcc is not installed

sudo apt-get install gcc
sudo apt-get install g++

To read exr file

def read_depth_exr_file(filepath: Path):
    exrfile = exr.InputFile(filepath.as_posix())
    raw_bytes = exrfile.channel('B', Imath.PixelType(Imath.PixelType.FLOAT))
    depth_vector = numpy.frombuffer(raw_bytes, dtype=numpy.float32)
    height = exrfile.header()['displayWindow'].max.y + 1 - exrfile.header()['displayWindow'].min.y
    width = exrfile.header()['displayWindow'].max.x + 1 - exrfile.header()['displayWindow'].min.x
    depth_map = numpy.reshape(depth_vector, (height, width))
    return depth_map
Nagabhushan S N
  • 6,407
  • 8
  • 44
  • 87