Exemplo n.º 1
0
    def write(self,fileOut,channels=None,displayWindow=None,dataWindow=None,half_float=True):
        
        new_channels = {}
        
        new_header = dict(self.header)
        new_header['channels'] = {}
        
        
        if dataWindow:
            roi = box_check(dataWindow)
        else:
            roi = box_check(self.data_window)
            
        if not channels:
            channels = self.channels.keys()
        
        for name in channels:
            chan = self.channels[name]
            
            new_channels[name] = chan.pixelBox(roi).tostring()
            
            new_header['channels'][name] = Imath.Channel(Imath.PixelType(OpenEXR.FLOAT))
            
            
        new_header['dataWindow'] = Imath.Box2i(Imath.point(roi.min.x,roi.min.y), Imath.point(roi.max.x,roi.max.y))
        
        
        o = fileOut
        if half_float:
            o = StringIO()
        
        out = OpenEXR.OutputFile(o,new_header)
        
        out.writePixels(new_channels)
        
        out.close()
        
        if half_float:
            o.seek(0)

            f = OpenEXR.InputFile(o)
    
            h = f.header()
            channels = h['channels'].keys()
            pt = Imath.PixelType(Imath.PixelType.HALF)
            
            data = f.channels(channels,pt)
            data_dict ={}
            for i,name in enumerate(channels):
                h['channels'][name] = Imath.Channel(Imath.PixelType(OpenEXR.HALF))
                data_dict[name] = data[i]

            out =  OpenEXR.OutputFile(fileOut,h)
    
            out.writePixels(data_dict)
            out.close()
Exemplo n.º 2
0
    def test_conversion(self):
        """ Write an image as UINT, read as FLOAT.  And the reverse. """
        codemap = {'f': self.FLOAT, 'I': self.UINT}
        original = [0, 1, 33, 79218]
        for frm_code, to_code in [('f', 'I'), ('I', 'f')]:
            hdr = OpenEXR.Header(len(original), 1)
            hdr['channels'] = {'L': Imath.Channel(codemap[frm_code])}
            x = OpenEXR.OutputFile("out.exr", hdr)
            x.writePixels({'L': array(frm_code, original).tobytes()})
            x.close()

            xin = OpenEXR.InputFile("out.exr")
            self.assertEqual(
                array(to_code, xin.channel('L', codemap[to_code])).tolist(),
                original)
def read_exr(image_fpath):
    import OpenEXR
    import Imath
    """ Reads an openEXR file into an RGB matrix with floats """
    f = OpenEXR.InputFile(image_fpath)
    dw = f.header()['dataWindow']
    w, h = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
    im = np.empty((h, w, 3))

    # Read in the EXR
    FLOAT = Imath.PixelType(Imath.PixelType.FLOAT)
    channels = f.channels(["R", "G", "B"], FLOAT)
    for i, channel in enumerate(channels):
        im[:, :, i] = np.reshape(array.array('f', channel), (h, w))
    return im
Exemplo n.º 4
0
def loadEXRImage(inputFilePath):
    img = oe.InputFile(inputFilePath)
    dw = img.header()['dataWindow']

    size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
    (rc, gc, bc) = img.channels("RGB", Imath.PixelType(Imath.PixelType.FLOAT))
    channelType = numpy.float32

    r = numpy.fromstring(rc, dtype=channelType)
    g = numpy.fromstring(gc, dtype=channelType)
    b = numpy.fromstring(bc, dtype=channelType)

    size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)

    return [r, g, b, size]
Exemplo n.º 5
0
def minMaxEXR(filename='', output='both'):
    file = OpenEXR.InputFile(filename)
    pt = Imath.PixelType(Imath.PixelType.FLOAT)
    dw = file.header()['dataWindow']
    size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)

    rgbf = Image.frombytes("F", size, file.channel("R", pt))

    extrema = rgbf.getextrema()
    if output == 'min':
        return extrema[0]
    elif output == 'max':
        return extrema[1]
    else:
        return extrema
Exemplo n.º 6
0
def read_exr(exr_filename):
    # Open the input file
    exr_file = OpenEXR.InputFile(exr_filename)
    # Compute the size
    dw = exr_file.header()['dataWindow']
    size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
    # Read the three colour channels as 32-bit floats
    # Imath.PixelType can have UINT unint32, HALF float16, FLOAT float32
    FLOAT = Imath.PixelType(Imath.PixelType.FLOAT)
    (R, G, B) = exr_file.channels("RGB", FLOAT)
    I = np.zeros([size[1], size[0], 3], dtype=np.float32)
    I[:, :, 0] = np.frombuffer(R, dtype=np.float32).reshape(size[1], size[0])
    I[:, :, 1] = np.frombuffer(G, dtype=np.float32).reshape(size[1], size[0])
    I[:, :, 2] = np.frombuffer(B, dtype=np.float32).reshape(size[1], size[0])
    return I
Exemplo n.º 7
0
def saveExr(data, filename):
    res = data.shape[0:2]
    assert res[0] == res[1], "Only square images supported so far."
    if len(data.shape) == 2:
        data = np.reshape(data, (res[0], res[1], 1))
    channels = data.shape[-1]
    assert (channels <= 3), "More than 3 channels not supported for EXR output"
    pixelsG = np.zeros_like(data[..., 0], dtype=np.float32).tostring()
    pixelsB = np.zeros_like(data[..., 0], dtype=np.float32).tostring()
    if channels >= 1:
        pixelsR = data[..., 0].astype(np.float32).tostring()
    if channels == 1:
        pixelsG = pixelsR
        pixelsB = pixelsR
    if channels >= 2:
        pixelsG = data[..., 1:2].astype(np.float32).tostring()
    if channels == 3:
        pixelsB = data[..., 2:3].astype(np.float32).tostring()
    header = OpenEXR.Header(res[0], res[1])
    half_chan = Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT))
    header['channels'] = dict([(c, half_chan) for c in "RGB"])
    exr = OpenEXR.OutputFile(filename, header)
    exr.writePixels({'R': pixelsR, 'G': pixelsG, 'B': pixelsB})
    exr.close()
Exemplo n.º 8
0
def read_texture(filename):
    image_data = 0
    is_hdr = False
    size = ()

    if OpenEXR.isOpenExrFile(filename):
        is_hdr = True
        img = OpenEXR.InputFile(filename)
        FLOAT = Imath.PixelType(Imath.PixelType.FLOAT)
        (r, g, b) = ( img.channel(chan, FLOAT) for chan in ('R', 'G', 'B'))
        dw = img.header()['dataWindow']
        size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)

        r_data = np.fromstring(r, dtype=np.float32)
        g_data = np.fromstring(g, dtype=np.float32)
        b_data = np.fromstring(b, dtype=np.float32)

        image_data = np.dstack((r_data, g_data, b_data))
        img.close()

    else:
        try:
            image = Image.open(filename)
        except IOError as ex:
            print('IOError: failed to open texture file %s' % filename)
            return -1
        print('opened file: size=', image.size, 'format=', image.format)
        image_data = np.array(list(image.getdata()), np.uint8)
        size = image.size
        image.close()


    texture_id= glGenTextures(1)
    glPixelStorei(GL_UNPACK_ALIGNMENT, 4)
    glBindTexture(GL_TEXTURE_2D, texture_id)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)

    if is_hdr:
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, size[0], size[1], 0, GL_RGB, GL_FLOAT, image_data)
    else:
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, size[0], size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)

    return texture_id
Exemplo n.º 9
0
 def test_enumerants(self):
     self.assertEqual(
         Imath.LevelMode("ONE_LEVEL").v,
         Imath.LevelMode(Imath.LevelMode.ONE_LEVEL).v)
     self.assertEqual(
         Imath.LevelMode("MIPMAP_LEVELS").v,
         Imath.LevelMode(Imath.LevelMode.MIPMAP_LEVELS).v)
     self.assertEqual(
         Imath.LevelMode("RIPMAP_LEVELS").v,
         Imath.LevelMode(Imath.LevelMode.RIPMAP_LEVELS).v)
Exemplo n.º 10
0
def load_hdr_multichannel(path):
    """
    Loads an HDR file with RGB, normal (3 channels) and depth (1 channel)
    :param path: file location
    :return: HDR image
    """
    pt = Imath.PixelType(Imath.PixelType.FLOAT)
    rgb_img_openexr = OpenEXR.InputFile(path)
    rgb_img = rgb_img_openexr.header()['dataWindow']
    size_img = (rgb_img.max.x - rgb_img.min.x + 1,
                rgb_img.max.y - rgb_img.min.y + 1)

    # color
    redstr = rgb_img_openexr.channel('color.R', pt)
    red = np.fromstring(redstr, dtype=np.float32)
    red.shape = (size_img[1], size_img[0])

    greenstr = rgb_img_openexr.channel('color.G', pt)
    green = np.fromstring(greenstr, dtype=np.float32)
    green.shape = (size_img[1], size_img[0])

    bluestr = rgb_img_openexr.channel('color.B', pt)
    blue = np.fromstring(bluestr, dtype=np.float32)
    blue.shape = (size_img[1], size_img[0])

    color = np.dstack((red, green, blue))

    # normal
    normal_x_str = rgb_img_openexr.channel('normal.R', pt)
    normal_x = np.fromstring(normal_x_str, dtype=np.float32)
    normal_x.shape = (size_img[1], size_img[0])

    normal_y_str = rgb_img_openexr.channel('normal.G', pt)
    normal_y = np.fromstring(normal_y_str, dtype=np.float32)
    normal_y.shape = (size_img[1], size_img[0])

    normal_z_str = rgb_img_openexr.channel('normal.B', pt)
    normal_z = np.fromstring(normal_z_str, dtype=np.float32)
    normal_z.shape = (size_img[1], size_img[0])

    normal = np.dstack((normal_x, normal_y, normal_z))

    # depth
    depth_str = rgb_img_openexr.channel('distance.Y', pt)
    depth = np.fromstring(depth_str, dtype=np.float32)
    depth.shape = (size_img[1], size_img[0])

    return color, depth, normal
Exemplo n.º 11
0
def main(exrfile, jpgfile):
    file = OpenEXR.InputFile(exrfile)
    pt = Imath.PixelType(Imath.PixelType.FLOAT)
    dw = file.header()['dataWindow']
    size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)

    rgbf = [Image.fromstring("F", size, file.channel(c, pt)) for c in "RGB"]

    extrema = [im.getextrema() for im in rgbf]
    darkest = min([lo for (lo,hi) in extrema])
    lighest = max([hi for (lo,hi) in extrema])
    scale = 255 / (lighest - darkest)
    def normalize_0_255(v):
        return (v * scale) + darkest
    rgb8 = [im.point(normalize_0_255).convert("L") for im in rgbf]
    Image.merge("RGB", rgb8).save(jpgfile)
def readEXRImage(filepath, channelrange):
    """Helper function for reading .exr files from the KAIST dataset.
    Returns an array with dimension ordering (C, H, W) as required by pytorch.
    """
    file = exr.InputFile(filepath)
    channels = ["w{}nm".format(wavelength) for wavelength in channelrange]
    header = file.header()
    ncols = header["displayWindow"].max.x + 1
    nrows = header["displayWindow"].max.y + 1
    pt = Imath.PixelType(Imath.PixelType.HALF)
    imgstrs = file.channels(channels, pt)
    full = np.zeros((len(channels), nrows, ncols), dtype=np.float16)
    for i, imgstr in enumerate(imgstrs):
        red = np.frombuffer(imgstr, dtype=np.float16)
        full[i, :, :] = np.reshape(red, (nrows, ncols))
    return full
Exemplo n.º 13
0
def readExr(file_path):
    exr_file = OpenEXR.InputFile(file_path)
    exr_header = exr_file.header()
    H, W = exr_header['dataWindow'].max.y + 1, exr_header[
        'dataWindow'].max.x + 1
    assert all(
        (exr_header['channels'][channel].type == Imath.PixelType(OpenEXR.HALF)
         for channel in ('R', 'G', 'B')))

    R, G, B = exr_file.channels(['R', 'G', 'B'])
    image_R = np.frombuffer(R, dtype=np.float16).reshape([H, W])
    image_G = np.frombuffer(G, dtype=np.float16).reshape([H, W])
    image_B = np.frombuffer(B, dtype=np.float16).reshape([H, W])
    image = np.stack([image_R, image_G, image_B], axis=2)

    return image
Exemplo n.º 14
0
    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))
Exemplo n.º 15
0
    def __init__(self, f):
        self.file = OpenEXR.InputFile(f)
        pixelType = Imath.PixelType(Imath.PixelType.FLOAT)

        dw = self.file.header()['dataWindow']
        self.width = dw.max.x - dw.min.x + 1
        self.height = dw.max.y - dw.min.y + 1
        self.size = (self.width, self.height)

        redStr = self.file.channel('R', pixelType)
        greenStr = self.file.channel('G', pixelType)
        blueStr = self.file.channel('B', pixelType)

        self.blue = array.array('f', blueStr)
        self.red = array.array('f', redStr)
        self.green = array.array('f', greenStr)
Exemplo n.º 16
0
def exr_to_png(exrfile, pngfile):
    File = OpenEXR.InputFile(exrfile)
    PixType = Imath.PixelType(Imath.PixelType.FLOAT)
    DW = File.header()['dataWindow']
    Size = (DW.max.x - DW.min.x + 1, DW.max.y - DW.min.y + 1)

    rgb = [
        numpy.fromstring(File.channel(c, PixType), dtype=numpy.float32)
        for c in 'RGB'
    ]
    for i in range(3):
        rgb[i] = numpy.where(rgb[i] <= 0.0031308, (rgb[i] * 12.92) * 255.0,
                             (1.055 * (rgb[i]**(1.0 / 2.2)) - 0.055) * 255.0)

    rgb8 = [Image.frombytes("F", Size, c.tostring()).convert("L") for c in rgb]
    Image.merge("RGB", rgb8).save(pngfile, "png", quality=100)
Exemplo n.º 17
0
def loadexr(filename):
    """Open an exr image and return a numpy array."""
    f = OpenEXR.InputFile(filename)
    dw = f.header()['dataWindow']
    sz = (dw.max.y - dw.min.y + 1, dw.max.x - dw.min.x + 1)

    # Read the three color channels as 32-bit floats
    FLOAT = Imath.PixelType(Imath.PixelType.FLOAT)
    image = np.empty((sz[0], sz[1], 3), dtype=np.float32)
    image[..., 0] = np.fromstring(f.channel("R", FLOAT),
                                  dtype=np.float32).reshape(sz)
    image[..., 1] = np.fromstring(f.channel("G", FLOAT),
                                  dtype=np.float32).reshape(sz)
    image[..., 2] = np.fromstring(f.channel("B", FLOAT),
                                  dtype=np.float32).reshape(sz)

    return image
Exemplo n.º 18
0
    def test_metadata_roundtrip(self):
        infile = OpenEXR.InputFile("GoldenGate.exr")
        h = infile.header()
        channels = h['channels'].keys()
        newchannels = dict(zip(channels, infile.channels(channels)))

        h['fps'] = Imath.Rational(24, 1)
        h['lytro-metadata'] = b"Some custom data"

        out = OpenEXR.OutputFile("modified.exr", h)
        out.writePixels(newchannels)
        out.close()

        infile = OpenEXR.InputFile("modified.exr")
        h = infile.header()
        self.assertEqual(h['lytro-metadata'], b"Some custom data")
        self.assertEqual((h['fps'].n, h['fps'].d), (24, 1))
 def load_exr(self, prefix_dir, prefix, file_kind, expected_height,
              expected_width):
     exr_file = OpenEXR.InputFile(
         os.path.join(prefix_dir, prefix + "-" + file_kind + ".exr"))
     cm_dw = exr_file.header()['dataWindow']
     exr_data = np.fromstring(exr_file.channel(
         'R', Imath.PixelType(Imath.PixelType.HALF)),
                              dtype=np.float16)
     exr_data.shape = (cm_dw.max.y - cm_dw.min.y + 1,
                       cm_dw.max.x - cm_dw.min.x + 1)  # rows, cols
     if exr_data.shape[0] != expected_height:
         print("[ERROR] ", prefix, file_kind, " != expected image height",
               exr_data.shape[0], expected_height)
     if exr_data.shape[1] != expected_width:
         print("[ERROR] ", prefix, file_kind, " width != image width",
               exr_data.shape[1], expected_width)
     return exr_data
def ConvertEXRToJPG(exrfile, jpgfile):
    File = OpenEXR.InputFile(exrfile)
    PixType = Imath.PixelType(Imath.PixelType.FLOAT)
    DW = File.header()['dataWindow']
    Size = (DW.max.x - DW.min.x + 1, DW.max.y - DW.min.y + 1)

    rgb = [
        np.fromstring(File.channel(c, PixType), dtype=np.float32)
        for c in 'RGB'
    ]
    for i in range(3):
        rgb[i] = np.where(rgb[i] <= 0.0031308, (rgb[i] * 12.92) * 255.0,
                          (1.055 * (rgb[i]**(1.0 / 2.4)) - 0.055) * 255.0)

    rgb8 = [Image.frombytes("F", Size, c.tostring()).convert("L") for c in rgb]
    # rgb8 = [Image.fromarray(c.astype(int)) for c in rgb]
    Image.merge("RGB", rgb8).save(jpgfile, "JPEG", quality=95)
Exemplo n.º 21
0
    def __init__(self, image_path):
        exrfile = exr.InputFile(image_path)
        dw = exrfile.header()['dataWindow']
        channels = ['R', 'G', 'B', 'A']

        self.header = exrfile.header()
        self.channels = []
        self.size = (dw.max.y - dw.min.y + 1, dw.max.x - dw.min.x + 1)
        self.channelData = dict()

        for c in self.header['channels']:
            self.channels.append(c)
            C = exrfile.channel(c, Imath.PixelType(Imath.PixelType.FLOAT))
            C = np.fromstring(C, dtype=np.float32)
            C = np.reshape(C, self.size)

            self.channelData[c] = C
Exemplo n.º 22
0
def ext2hdr(exrpath):
    File = OpenEXR.InputFile(exrpath)
    PixType = Imath.PixelType(Imath.PixelType.FLOAT)
    DW = File.header()['dataWindow']
    Size = (DW.max.x - DW.min.x + 1, DW.max.y - DW.min.y + 1)
    rgb = [
        numpy.fromstring(File.channel(c, PixType), dtype=numpy.float32)
        for c in 'RGB'
    ]
    r = numpy.reshape(rgb[0], (Size[1], Size[0]))
    g = numpy.reshape(rgb[1], (Size[1], Size[0]))
    b = numpy.reshape(rgb[2], (Size[1], Size[0]))
    hdr = numpy.zeros((Size[1], Size[0], 3), dtype=numpy.float32)
    hdr[:, :, 0] = b
    hdr[:, :, 1] = g
    hdr[:, :, 2] = r
    return hdr
Exemplo n.º 23
0
def exr2arr(exrfile):
    file = OpenEXR.InputFile(exrfile)
    dw = file.header()['dataWindow']

    channels = file.header()['channels'].keys()
    channels_list = list()
    for c in ('R', 'G', 'B', 'A'):
        if c in channels:
            channels_list.append(c)

    # the shape had incorrect order
    #size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
    size = (dw.max.y - dw.min.y + 1, dw.max.x - dw.min.x + 1)
    color_channels = file.channels(channels_list, Imath.PixelType(Imath.PixelType.FLOAT))
    channels_tuple = [np.fromstring(channel, dtype='f') for channel in color_channels]
    res = np.dstack(channels_tuple)
    return res.reshape(size + (len(channels_tuple),))
Exemplo n.º 24
0
def get_color_array(path):
    pixel_type = Imath.PixelType(Imath.PixelType.FLOAT)
    file = OpenEXR.InputFile(path)
    data_window = file.header()['dataWindow']
    size = (data_window.max.x - data_window.min.x + 1,
            data_window.max.y - data_window.min.y + 1)
    r_str = file.channel('R', pixel_type)
    g_str = file.channel('G', pixel_type)
    b_str = file.channel('B', pixel_type)
    r = np.frombuffer(r_str, dtype=np.float32)
    r.shape = (size[1], size[0], 1)
    g = np.frombuffer(g_str, dtype=np.float32)
    g.shape = (size[1], size[0], 1)
    b = np.frombuffer(b_str, dtype=np.float32)
    b.shape = (size[1], size[0], 1)
    rgb = np.concatenate([r, g, b], axis=2)
    return rgb
Exemplo n.º 25
0
def readEXR(filename):
    """Read color + depth data from EXR image file.
    
    Parameters
    ----------
    filename : str
        File path.
        
    Returns
    -------
    img : Float matrix
    Z : Depth buffer in float32 format or None if the EXR file has no Z channel.
    """

    exrfile = exr.InputFile(filename)
    header = exrfile.header()

    dw = header["dataWindow"]
    isize = (dw.max.y - dw.min.y + 1, dw.max.x - dw.min.x + 1)

    channelData = dict()

    # convert all channels in the image to numpy arrays
    for c in header["channels"]:
        C = exrfile.channel(c, Imath.PixelType(Imath.PixelType.FLOAT))
        C = np.frombuffer(C, dtype=np.float32)
        C = np.reshape(C, isize)

        channelData[c] = C

    colorChannels = (["R", "G", "B", "A"]
                     if "A" in header["channels"] else ["R", "G", "B"])
    img = np.concatenate(
        [channelData[c][..., np.newaxis] for c in colorChannels], axis=2)

    # linear to standard RGB
    # img[..., :3] = np.where(img[..., :3] <= 0.0031308,
    #                       12.92 * img[..., :3],
    #                        1.055 * np.power(img[..., :3], 1 / 2.4) - 0.055)

    # sanitize image to be in range [0, 1]
    # img = np.where(img < 0.0, 0.0, np.where(img > 1.0, 1, img))

    Z = None if "Z" not in header["channels"] else channelData["Z"]

    return img, Z
Exemplo n.º 26
0
def read_openexr(fname):
    file = OpenEXR.InputFile(fname)
    header = file.header()
    dw = header['dataWindow']
    pt = Imath.PixelType(Imath.PixelType.HALF)
    shape = (dw.max.y - dw.min.y + 1, dw.max.x - dw.min.x + 1)
    r = np.frombuffer(file.channel('Color.R', pt),
                      dtype=np.float16).reshape(shape + (1, ))
    g = np.frombuffer(file.channel('Color.G', pt),
                      dtype=np.float16).reshape(shape + (1, ))
    b = np.frombuffer(file.channel('Color.B', pt),
                      dtype=np.float16).reshape(shape + (1, ))
    a = np.frombuffer(file.channel('Color.A', pt),
                      dtype=np.float16).reshape(shape + (1, ))
    img = np.concatenate((r, g, b, a), -1).astype(np.float32)
    file.close()
    return img
Exemplo n.º 27
0
def read_exr_image(exr_filename, channels=['R', 'G', 'B']):
    exrfile = exr.InputFile(exr_filename)
    dw = exrfile.header()['dataWindow']
    isize = (dw.max.y - dw.min.y + 1, dw.max.x - dw.min.x + 1)
    channelData_arr = dict()

    for c in channels:
        C = exrfile.channel(c, Imath.PixelType(Imath.PixelType.FLOAT))
        C = np.fromstring(C, dtype=np.float32)
        C = np.reshape(C, isize)
        channelData_arr[c] = C

    # get the whole array
    img_arr = np.concatenate(
        [channelData_arr[c][..., np.newaxis] for c in ['R', 'G', 'B']],
        axis=2)  # (res, res, 3)
    return img_arr
def loadEXR(fname, channelNames):
    # Open the input file
    f = OpenEXR.InputFile(fname)

    # Compute the size
    dw = f.header()['dataWindow']
    sz = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)

    # Read the three  color channels as 32-bit floats
    FLOAT = Imath.PixelType(Imath.PixelType.FLOAT)
    channels = [
        array.array('f', f.channel(Chan, FLOAT)).tolist()
        for Chan in channelNames
    ]

    channels = [np.array(channel).reshape(sz) for channel in channels]
    return np.array(channels)
Exemplo n.º 29
0
def process_depth(exr_path):
    depth_exr = OpenEXR.InputFile(exr_path)
    dw = depth_exr.header()['dataWindow']
    sz = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)

    depth = depth_exr.channel('Image.V', Imath.PixelType(Imath.PixelType.FLOAT))
    depth = np.fromstring(depth, dtype='float32')
    depth.shape = (sz[1], sz[0])
    depth = depth.astype('float32') * 10000

    depth = depth.astype(np.uint16)
    mask = 255 * np.ones(shape=depth.shape, dtype='uint8')
    mask[depth == 0] = 0

    os.remove(exr_path)

    return depth, mask
Exemplo n.º 30
0
def readEXR(filenameEXR):
    pt = Imath.PixelType(
        Imath.PixelType.FLOAT
    )  #only works hard-coding this and np.float32, instead of using the value from: exr.header()['channels'][c].type
    exr = OpenEXR.InputFile(filenameEXR)
    dw = exr.header()['dataWindow']
    size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
    #this needs to be fixed. 2 of the following 3 lines swap axes.
    rgb = np.swapaxes(
        np.array([
            np.fromstring(exr.channel(c, pt), dtype=np.float32) for c in "RGB"
        ]), 0, 1)  #I guess if we used HALF we would need to use np.float16
    rgb.shape = (size[1], size[0], 3)  #numpy array are (row, col) = (y, x)
    rgb = np.swapaxes(rgb, 0,
                      1)  #(y,x,c) -> (x,y,c) #probably (x,y,c) -> (y,x,c)
    exr.close()
    return rgb
Exemplo n.º 31
0
def getPixels(path):
    image = OpenEXR.InputFile(path)
    header = image.header()
    pt = Imath.PixelType(Imath.PixelType.FLOAT)
    dw = header['dataWindow']
    x, y = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)

    im = numpy.zeros((x, y, 3))
    im[:, :, 0] = numpy.frombuffer(image.channel('R', pt),
                                   dtype=numpy.float32).reshape((x, y))
    im[:, :, 1] = numpy.frombuffer(image.channel('G', pt),
                                   dtype=numpy.float32).reshape((x, y))
    im[:, :, 2] = numpy.frombuffer(image.channel('B', pt),
                                   dtype=numpy.float32).reshape((x, y))

    im = numpy.clip(im, 0, 1)
    return srgb.to(im), x, y