Python OpenEXR.InputFile() Examples

The following are 16 code examples of OpenEXR.InputFile(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module OpenEXR , or try the search function .
Example #1
Source File: utils.py    From noise2noise-pytorch with MIT License 7 votes vote down vote up
def load_hdr_as_tensor(img_path):
    """Converts OpenEXR image to torch float tensor."""

    # Read OpenEXR file
    if not OpenEXR.isOpenExrFile(img_path):
        raise ValueError(f'Image {img_path} is not a valid OpenEXR file')
    src = OpenEXR.InputFile(img_path)
    pixel_type = Imath.PixelType(Imath.PixelType.FLOAT)
    dw = src.header()['dataWindow']
    size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
    
    # Read into tensor
    tensor = torch.zeros((3, size[1], size[0]))
    for i, c in enumerate('RGB'):
        rgb32f = np.fromstring(src.channel(c, pixel_type), dtype=np.float32)
        tensor[i, :, :] = torch.from_numpy(rgb32f.reshape(size[1], size[0]))
        
    return tensor 
Example #2
Source File: render_utils.py    From pvnet-rendering with Apache License 2.0 7 votes vote down vote up
def exr_to_png(exr_path):
        depth_path = exr_path.replace('.png0001.exr', '.png')
        exr_image = OpenEXR.InputFile(exr_path)
        dw = exr_image.header()['dataWindow']
        (width, height) = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)

        def read_exr(s, width, height):
            mat = np.fromstring(s, dtype=np.float32)
            mat = mat.reshape(height, width)
            return mat

        dmap, _, _ = [read_exr(s, width, height) for s in exr_image.channels('BGR', Imath.PixelType(Imath.PixelType.FLOAT))]
        dmap = Image.fromarray((dmap != 1).astype(np.int32))
        dmap.save(depth_path)
        exr_image.close()
        os.system('rm {}'.format(exr_path)) 
Example #3
Source File: dataset_utils.py    From rpg_davis_simulator with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, frame_id, exr_path, use_log=True, blur_size=0, use_scharr=True):
        self.frame_id = frame_id
        self.exr_img = OpenEXR.InputFile(exr_path)
        self.img_raw = extract_grayscale(self.exr_img)
        
        # self.img is actually log(eps+img), blurred
        self.img = Frame.preprocess_image(self.img_raw.copy(), use_log=True, blur_size=blur_size)
        
        # self.img_raw is the non-logified image, blurred        
        self.img_raw = Frame.preprocess_image(self.img_raw, use_log=False, blur_size=blur_size)
        
        # compute the gradient using
        # nabla(log(eps+I)) = nabla(I) / (eps+I) (chain rule)
        # (hopefully better precision than directly
        # computing the numeric gradient of the log img)
        eps = 0.001
        self.gradient = compute_gradient(self.img_raw, use_scharr)
        self.gradient[:,:,0] = self.gradient[:,:,0] / (eps+self.img_raw)
        self.gradient[:,:,1] = self.gradient[:,:,1] / (eps+self.img_raw)
        self.z = extract_depth(self.exr_img) 
Example #4
Source File: dataset_utils.py    From EVDodgeNet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, frame_id, exr_path, use_log=True, blur_size=0, use_scharr=True):
        self.frame_id = frame_id
        self.exr_img = OpenEXR.InputFile(exr_path)
        self.img_raw = extract_grayscale(self.exr_img)
        
        # self.img is actually log(eps+img), blurred
        self.img = Frame.preprocess_image(self.img_raw.copy(), use_log=True, blur_size=blur_size)
        
        # self.img_raw is the non-logified image, blurred        
        self.img_raw = Frame.preprocess_image(self.img_raw, use_log=False, blur_size=blur_size)
        
        # compute the gradient using
        # nabla(log(eps+I)) = nabla(I) / (eps+I) (chain rule)
        # (hopefully better precision than directly
        # computing the numeric gradient of the log img)
        eps = 0.001
        self.gradient = compute_gradient(self.img_raw, use_scharr)
        self.gradient[:,:,0] = self.gradient[:,:,0] / (eps+self.img_raw)
        self.gradient[:,:,1] = self.gradient[:,:,1] / (eps+self.img_raw)
        self.z = extract_depth(self.exr_img) 
Example #5
Source File: util.py    From nuke-ML-server with Apache License 2.0 6 votes vote down vote up
def check_exr(exr_files, channel_names=['R', 'G', 'B']):
    """Check that exr_files (a list of EXR file(s)) have the requested channels
    and have the same data window size. Return image width and height.
    """
    if not list(channel_names):
        raise ValueError("channel_names is empty")
    if isinstance(exr_files, OpenEXR.InputFile):    # single exr file
        exr_files = [exr_files]
    elif not isinstance(exr_files, list):
        raise TypeError("type(exr_files): {}, should be str or list".format(type(exr_files)))
    # Check data window size
    data_windows = [str(exr.header()['dataWindow']) for exr in exr_files]
    if any(dw != data_windows[0] for dw in data_windows):
        raise ValueError("input and groundtruth .exr images have different size")
    # Check channel to read are present in given exr file(s)
    channels_headers = [exr.header()['channels'] for exr in exr_files]
    for channels in channels_headers:
        if any(c not in list(channels.keys()) for c in channel_names):
            raise ValueError("Try to read channels {} of an exr image with channels {}"
                .format(channel_names, list(channels.keys())))
    # Compute the size
    dw = exr_files[0].header()['dataWindow']
    width = dw.max.x - dw.min.x + 1
    height = dw.max.y - dw.min.y + 1
    return width, height 
Example #6
Source File: util.py    From nuke-ML-server with Apache License 2.0 6 votes vote down vote up
def read_crop_exr_pair(exr_path_in, exr_path_gt, crop_size=256, channel_names=['R', 'G', 'B']):
    """Read requested channels of input and groundtruth .exr image paths
    and return the same random crop of both
    """
    # Open the input file
    exr_file_in = OpenEXR.InputFile(exr_path_in)
    exr_file_gt = OpenEXR.InputFile(exr_path_gt)
    width, height = check_exr([exr_file_in, exr_file_gt], channel_names)
    # Check exr image width and height >= crop_size
    if height < crop_size or width < crop_size:
        raise ValueError("Input images size should be superior or equal to crop_size: {} < ({},{})"
            .format((width, height), crop_size, crop_size))
    # Get random crop value
    randw = np.random.randint(0, width-crop_size) if width-crop_size > 0 else 0
    randh = np.random.randint(0, height-crop_size) if height-crop_size > 0 else 0 
    # Get the crop of input and groundtruth .exr images
    exr_crop_in = read_crop_exr(exr_file_in, (width, height), randw, randh, crop_size, channel_names)
    exr_crop_gt = read_crop_exr(exr_file_gt, (width, height), randw, randh, crop_size, channel_names)
    return [exr_crop_in, exr_crop_gt] 
Example #7
Source File: exr_test.py    From graphics with Apache License 2.0 5 votes vote down vote up
def test_reading_unknown_exr_type_fails(self):
    image, channels = _MakeTestImage(3, np.float16)
    with tempfile.NamedTemporaryFile() as temp:
      exr.write_exr(temp.name, image, channels)
      exr_file = OpenEXR.InputFile(temp.name)
      # Deliberately break the R channel header info. A mock InputFile is
      # required to override the header() method.
      header_dict = exr_file.header()
      header_dict['channels']['R'].type.v = -1  # Any bad value will do.
      make_mock_exr = collections.namedtuple('MockExr', ['header', 'channel'])
      mock_broken_exr = make_mock_exr(lambda: header_dict, exr_file.channel)
      with self.assertRaisesRegexp(RuntimeError, 'Unknown EXR channel type'):
        _ = exr.channels_to_ndarray(mock_broken_exr, ['R', 'G', 'B']) 
Example #8
Source File: exr.py    From graphics with Apache License 2.0 5 votes vote down vote up
def channels_to_ndarray(exr, channel_names):
  """Copies channels from an OpenEXR.InputFile into a numpy array.

  If the EXR image is of size (width, height), the result will be a numpy array
  of shape (height, width, len(channel_names)), where the last dimension holds
  the channels in the order they were specified in channel_names. The requested
  channels must all have the same datatype.

  Args:
    exr: An OpenEXR.InputFile that is already open.
    channel_names: A list of strings naming the channels to read.

  Returns:
    A numpy ndarray.

  Raises:
    ValueError: If the channels have different datatypes.
    RuntimeError: If a channel has an unknown type.
  """
  channels_header = exr.header()['channels']
  window = exr.header()['dataWindow']
  width = window.max.x - window.min.x + 1
  height = window.max.y - window.min.y + 1

  def read_channel(channel):
    """Reads a single channel from the EXR."""
    channel_type = channels_header[channel].type
    try:
      numpy_type = _exr_to_np[channel_type.v]
    except KeyError:
      raise RuntimeError('Unknown EXR channel type: %s' % str(channel_type))
    flat_buffer = np.frombuffer(exr.channel(channel), numpy_type)
    return np.reshape(flat_buffer, [height, width])

  channels = [read_channel(c) for c in channel_names]
  if any([channels[0].dtype != c.dtype for c in channels[1:]]):
    raise ValueError('Channels have mixed datatypes: %s' %
                     ', '.join([str(c.dtype) for c in channels]))
  # Stack the arrays so that the channels dimension is the last (fastest
  # changing) dimension.
  return np.stack(channels, axis=-1) 
Example #9
Source File: convertEXR.py    From 3D-point-cloud-generation with MIT License 5 votes vote down vote up
def readEXR(fname,RESOLUTION):
	channel_list = ["B","G","R"]
	file = OpenEXR.InputFile(fname)
	dw = file.header()["dataWindow"]
	height,width = RESOLUTION,RESOLUTION
	FLOAT = Imath.PixelType(Imath.PixelType.FLOAT)
	vectors = [np.array(array.array("f",file.channel(c,FLOAT))) for c in channel_list]
	depth = vectors[0].reshape([height,width])
	return depth 
Example #10
Source File: exr.py    From pyexr with MIT License 5 votes vote down vote up
def open(filename):
  # Check if the file is an EXR file
  if not OpenEXR.isOpenExrFile(filename):
    raise Exception("File '%s' is not an EXR file." % filename)
  # Return an `InputFile`
  return InputFile(OpenEXR.InputFile(filename), filename) 
Example #11
Source File: exr_image_parser.py    From bpycv with MIT License 5 votes vote down vote up
def parser_exr(exr_path):
    file = OpenEXR.InputFile(exr_path)
    header = file.header()

    h, w = header["displayWindow"].max.y + 1, header["displayWindow"].max.x + 1
    exr = ExrDict()
    for key in header["channels"]:
        assert header["channels"][key].type.__str__() == "FLOAT"
        exr[key] = np.fromstring(file.channel(key), dtype=np.float32).reshape(h, w)
    file.close()
    return exr 
Example #12
Source File: process_exr.py    From pcn with MIT License 5 votes vote down vote up
def read_exr(exr_path, height, width):
    file = OpenEXR.InputFile(exr_path)
    depth_arr = array.array('f', file.channel('R', Imath.PixelType(Imath.PixelType.FLOAT)))
    depth = np.array(depth_arr).reshape((height, width))
    depth[depth < 0] = 0
    depth[np.isinf(depth)] = 0
    return depth 
Example #13
Source File: util.py    From nuke-ML-server with Apache License 2.0 5 votes vote down vote up
def read_exr(exr_path, channel_names=['R', 'G', 'B']):
    """Read requested channels of an exr and return them in a numpy array
    """
    # Open and check the input file
    exr_file = OpenEXR.InputFile(exr_path)
    width, height = check_exr(exr_file, channel_names)
    # Copy channels from an exr file into a numpy array
    exr_numpy = [np.frombuffer(exr_file.channel(c, EXR_PIX_TYPE), dtype=EXR_NP_TYPE)
        .reshape(height, width) for c in channel_names]
    exr_numpy = np.stack(exr_numpy, axis=-1)
    return exr_numpy 
Example #14
Source File: exr.py    From graphics with Apache License 2.0 4 votes vote down vote up
def read_exr(filename, channel_names=None):
  """Opens an EXR file and copies the requested channels into an ndarray.

  The Python OpenEXR wrapper uses a dictionary for the channel header, so the
  ordering of the channels in the underlying file is lost. If channel_names is
  not passed, this function orders the output channels with any present RGBA
  channels first, followed by the remaining channels in alphabetical order.
  By convention, RGBA channels are named 'R', 'G', 'B', 'A', so this function
  looks for those strings.

  Args:
    filename: The name of the EXR file.
    channel_names: A list of strings naming the channels to read. If None, all
      channels will be read.

  Returns:
    A numpy array containing the image data, and a list of the corresponding
      channel names.
  """
  exr = OpenEXR.InputFile(filename)
  if channel_names is None:
    remaining_channel_names = list(exr.header()['channels'].keys())
    conventional_rgba_names = ['R', 'G', 'B', 'A']
    present_rgba_names = []
    # Pulls out any present RGBA names in RGBA order.
    for name in conventional_rgba_names:
      if name in remaining_channel_names:
        present_rgba_names.append(name)
        remaining_channel_names.remove(name)
    channel_names = present_rgba_names + sorted(remaining_channel_names)

  return channels_to_ndarray(exr, channel_names), channel_names 
Example #15
Source File: synthetic.py    From opensurfaces with MIT License 4 votes vote down vote up
def open_multilayer_exr_layers(inputfile, layers):
    """
    Load a list of images, each corresponding to a layer of an OpenEXR file.

    Note that "layer" does not correspond to a single color channel, like "R",
    but rather, a group of 3 color channels.

    :param inputfile: string filename
    :param layers: list of string layer names
    """
    f = OpenEXR.InputFile(inputfile)
    header = f.header()
    dw = header['dataWindow']
    cols, rows = dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1

    # load channels
    FLOAT = Imath.PixelType(Imath.PixelType.FLOAT)
    images = []
    for layer in layers:
        channels = LAYER_CHANNELS[layer]
        image = np.empty((rows, cols, 3), dtype=np.float32)
        for (i, c) in enumerate(channels):
            data = f.channel(c, FLOAT)
            image[:, :, i] = np.fromstring(data, dtype=np.float32) \
                .reshape((rows, cols))
        images.append(image)

    return images


#def denoise_indirect_image(img):
    #denoised = np.empty_like(img)
    #for c in xrange(3):
        #denoised[:, :, c] = median_filter(
            #img[:, :, c],
            #mode='reflect',
            #footprint=[
                #[0, 1, 0],
                #[1, 1, 1],
                #[0, 1, 0],
            #]
        #)
    #return denoised 
Example #16
Source File: flow.py    From EVDodgeNet with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def rigid_flow(self):

    	V, Omega, dt = self.compute_velocity_from_msg(self.pose_data[200,:], self.pose_data[204,:])

    	# print(self.depth_data[1][1])

    	depth_image0 = OpenEXR.InputFile(self.depth_data[200][1])
    	dw0 = depth_image0.header()['dataWindow']
    	size0 = (dw0.max.x - dw0.min.x + 1, dw0.max.y - dw0.min.y + 1)
    	pt0 = Imath.PixelType(Imath.PixelType.FLOAT)
    	depth0 = np.fromstring(depth_image0.channel("Z"), dtype=np.float32)
        depth0.shape = (size0[1], size0[0])  # Numpy arrays are (row, col)

        depth_image1 = OpenEXR.InputFile(self.depth_data[204][1])
        dw1 = depth_image1.header()['dataWindow']
        size1 = (dw1.max.x - dw1.min.x + 1, dw1.max.y - dw1.min.y + 1)
        pt1 = Imath.PixelType(Imath.PixelType.FLOAT)
        depth1 = np.fromstring(depth_image1.channel("Z"), dtype=np.float32)
        depth1.shape = (size1[1], size1[0])  # Numpy arrays are (row, col)

        depth = (depth0+depth1)/2

    	flow_x_dist, flow_y_dist = self.compute_flow_single_frame(V,
                                                                  Omega,
                                                                  depth,
                                                                  dt)
    	print(flow_x_dist, flow_y_dist)

    	flow = np.dstack((flow_x_dist, flow_y_dist))
        flow = np.float32(flow)
    	# verfication 
    	img1 = cv2.imread(self.image_data[200][1],1)
        # img1 = np.float32(img1)
        print(img1.shape)
    	img2 = cv2.imread(self.image_data[204][1], 1)
        # img2 = np.float32(img2)
        print(img1.shape, flow.dtype)

    	warpped_img1 = self.warp_image(img2, flow)
        # warpped_img1 = self.warp_flow(img2, flow)

        cv2.imshow('warpped_img1', cv2.subtract(img1, warpped_img1))


        first_img = self.colorize_image(flow_x_dist, flow_y_dist)
        cv2.imshow('image',first_img)
        cv2.waitKey(0)