Reputation: 465
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.
Upvotes: 10
Views: 29710
Reputation: 106
A convenient way to read an OpenEXR (.exr) is the library openexr-numpy
from openexr_numpy import imread, imwrite
import numpy as np
img = imread(IMAGE_PATH_EXR)
Another high-level options would be ImageIO and OpenCV or you can use OpenEXR to read each pixel.
Upvotes: 0
Reputation: 7277
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
Upvotes: 3
Reputation: 151
@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)
Upvotes: 6
Reputation: 1942
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
Upvotes: 13