示例#1
0
def is_ok(path):
    if not OpenEXR.isOpenExrFile(path): 
        return False
    img = OpenEXR.InputFile(path)
    if not img.isComplete():
        return False
    return True
示例#2
0
    def load(self, path = ""):
        if type(path) is not str:
            raise TypeError("Path must be string")
        if path == "":
            path = self._path
        if path == "":
            raise ValueError("Path must be set")
        if not OpenEXR.isOpenExrFile(path): 
            raise FileNotFoundError(path)
        img = OpenEXR.InputFile(path)
        if not img.isComplete():
            raise IOError("File is corrupted")
        dw = img.header()['displayWindow']
        size = (dw.max.y - dw.min.y + 1, dw.max.x - dw.min.x + 1)

        # compression type
        self._compression = compress.str_to_obj(img.header()["compression"])

        # load data
        for channel_name, channel_type in img.header()["channels"].items():
            # data
            data = img.channel(channel_name)
            
            # pixel data type
            pix_type = np.float32
            if channel_type == Imath.Channel( Imath.PixelType( Imath.PixelType.HALF ) ):
                pix_type = np.float16
            elif channel_type == Imath.Channel( Imath.PixelType( Imath.PixelType.UINT ) ):
                pix_type = np.np.uint64
                
            # create numpy channel in dictionary
            if channel_name not in self or self._preserve_channels:
                self[channel_name] = np.fromstring(data, dtype = pix_type).reshape(size)
        self._shape = size
        print("HEADER: ", img.header() )
示例#3
0
def load_depth(filePath):
    ''' Loads an depth OpenEXR image.'''

    if oe.isOpenExrFile(filePath) is not True:
        raise Exception("File ", filePath, " does not exist!")

    try:
        ifi = oe.InputFile(filePath)

        # Compute size
        header = ifi.header()
        dw = header["dataWindow"]
        w, h = dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1

        # Read the three channels
        ifiType = header["channels"]["Z"].type.v
        if ifiType is not im.PixelType.FLOAT:
            raise Exception("Only float32 supported! (file is type ", ifiType)

        Z = ifi.channel("Z", im.PixelType(ifiType))
        ifi.close()

        image = np.zeros((h, w), dtype = np.float32) # order = "C"
        image[:, :] = np.core.multiarray.fromstring(Z, dtype = np.float32).reshape(h, w)

    except:
        raise

    return image
示例#4
0
def load_depth(filePath):
    ''' Loads an depth OpenEXR image.'''

    if oe.isOpenExrFile(filePath) is not True:
        raise Exception("File ", filePath, " does not exist!")

    try:
        ifi = oe.InputFile(filePath)

        # Compute size
        header = ifi.header()
        dw = header["dataWindow"]
        w, h = dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1

        # Read the three channels
        ifiType = header["channels"]["Z"].type.v
        if ifiType is not im.PixelType.FLOAT:
            raise Exception("Only float32 supported! (file is type ", ifiType)

        Z = ifi.channel("Z", im.PixelType(ifiType))
        ifi.close()

        image = np.zeros((h, w), dtype=np.float32)  # order = "C"
        image[:, :] = np.core.multiarray.fromstring(Z,
                                                    dtype=np.float32).reshape(
                                                        h, w)

    except:
        raise

    return image
示例#5
0
文件: exr.py 项目: pobrien11/PyAniLib
 def is_valid_exr(self, exr_handle=None):
     """
     Check if exr is valid and complete (all data present)
     :param exr_handle: optional - an exr InputFile handle. If not provided one is created
     :return: The error if not readable or missing pixels, None otherwise
     """
     # check if a file handle was given
     if not exr_handle:
         # no handle provided so open the exr and get one
         exr_handle = self._open_exr_file_handle(self.path)
         # check for errors
         if not isinstance(exr_handle, OpenEXR.InputFile):
             return exr_handle
     # check of the exr is readable
     if not OpenEXR.isOpenExrFile(self.path):
         error = "The following exr does not exist or is not readable: {0}".format(
             self.path)
         logging.exception(error)
         exr_handle.close()
         return error
     # check if the exr has complete pixel information
     if not exr_handle.isComplete():
         error = "The following exr has missing pixels: {0}".format(
             self.path)
         logging.exception(error)
         exr_handle.close()
         return error
     return None
示例#6
0
def _open_inputfile(filename):
    if not OpenEXR.isOpenExrFile(filename):
        print(
            "Failed reading image. File can't be opened or is not an OpenEXR image."
        )
        raise SystemExit(1)
    exr_file = OpenEXR.InputFile(filename)
    if not exr_file.isComplete():
        print(
            "WARNING: File seems incomplete (corrupted or still being written)."
        )
    return exr_file
def matte_pass_channel_cleanup(in_path, out_path):
    """
    @params:
        in_path: Path to exr file.
        out_path: Path to write out the new exr file.
    """

    if os.path.exists(in_path) and OpenEXR.isOpenExrFile(in_path):
        channels_to_merge = defaultdict(list)
        base_channels = []

        # Read the file and header
        handle = OpenEXR.InputFile(in_path)
        header = handle.header()

        # Get the channels
        channels = header['channels']
        header['channels'] = {}
        new_channels = {}

        for channel_name, channel_data in channels.iteritems():
            match = CHANNEL_MATCH.match(channel_name)
            if match:
                layer, channel = match.groups()
                channels_to_merge[layer].append(channel)

            elif not ALPHA_MATCH.match(channel_name):
                base_channels.append(channel_name)

        for layer in base_channels:
            all_pixels = array.array( 'f', handle.channel(layer,
                 Imath.PixelType(Imath.PixelType.HALF))).tolist()
            new_channels[layer] = array.array('f', all_pixels).tostring()

        for layer, data in channels_to_merge.iteritems():
            new_pixels = []

            try:
                new_layer_name = layer.split('_')[1]
            except:
                new_layer_name = layer

            # new pixels
            new_pixels = array.array('f',
                    handle.channel('{0}.{1}'.format(layer, data[0])))
            new_channels['matte.{0}'.format(new_layer_name)] = array.array('f',
                                                         new_pixels).tostring()

        # write out new exr
        header['channels'] = dict([(c, HALF) for c in new_channels.keys()])
        out = OpenEXR.OutputFile(out_path, header)
        out.writePixels(new_channels)
示例#8
0
    def __init__(self, image):
        super(AniImage, self).__init__()
        self.image = image
        # allow user to pass a AnImage object, or a string path
        self.__path = getattr(image, 'path', None)
        if self.__path is None:
            self.__path = str(image)

        # image parts
        self.__dirname, self.__filename = os.path.split(self.__path)
        # all numeric parts image name
        self.__digits = util.DIGITS_RE.findall(self.name)
        # get all non numeric parts of image name
        self.__parts = util.DIGITS_RE.split(self.name)
        self.__size = (0, 0)

        # get image size using OpenExr for exrs and PIL for other image formats. Lighter weight than using cv2 which
        # causes standalone executable to be 30 megs bigger
        if OpenEXR.isOpenExrFile(self.path):
            try:
                exr_image = OpenEXR.InputFile(self.path)
                dw = exr_image.header()['dataWindow']
                self.__size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
                exr_image.close()
            except (IOError, OSError, ValueError) as e:
                raise AniImageError('Image: {0} is not a valid exr.'.format(self.path))
        else:
            try:
                with Image.open(self.path) as img:
                    self.__size = img.size
            except (IOError, OSError, ValueError) as e:
                raise AniImageError('Image: {0} does not exist on disk or is invalid.'.format(self.path))

        try:
            # get the frame as a pyani.core. AniFrame object
            self.__frame = AniFrame(self.path)
        except IndexError:
            # image must not have a frame
            self.__frame = None

        # the start_and end are at the . in file name, or whatever separates frame number from extension and image name
        # subtract one from start to get image name no '.' and add one to get extension no '.'
        if self.frame:
            self.__base_name = self.name[:self.frame.start - 1]
            self.__ext = self.name[self.frame.end+1:]
        else:
            # no frame in image name, split at extension
            split_name = self.name.split(".")
            self.__base_name = ".".join(split_name[:-1])
            self.__ext = split_name[-1]
示例#9
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
示例#10
0
def inspect_file(in_path):
    """ TODO: add docstring.

    Args:
        in_path (str): File to read

    Raises:
        NoExrFileException
    """
    print 'Started inspect of {in_path}.'.format(in_path=in_path)

    # start time
    time_start = time.time()

    if not OpenEXR.isOpenExrFile(in_path):
        raise NoExrFileException(in_path)

    # open exr file
    in_exr_file = OpenEXR.InputFile(in_path)

    # get open exr header
    in_exr_header = in_exr_file.header()

    # printable_exr_header = {key: value for key, filter_jsonable(value) in in_exr_header.iteritems()}

    def catch_value(value):
        """ Catch non-jsonable values.

        Args:
            value (mixed): Value

        Returns:
            mixed
        """
        # if isinstance(value, Imath.Box2i):
        return repr(value)

    print json.dumps(filter_jsonable(in_exr_header, catch_value), indent=4)

    # stop time
    time_stop = time.time()

    # duration
    duration = round(time_stop - time_start)

    print 'Finished inspect for {in_path} ({duration}s).'.format(
        in_path=in_path, duration=duration)
示例#11
0
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
示例#12
0
def load_exr_as_tensor(filename):
    import OpenEXR
    import Imath
    if not OpenEXR.isOpenExrFile(filename):
        raise Exception(f"File {filename} is not an EXR file.")
    exr_data = OpenEXR.InputFile(filename)

    exr_header = exr_data.header()
    dw = exr_header['dataWindow']
    width = dw.max.x - dw.min.x + 1
    height = dw.max.y - dw.min.y + 1

    red_channel = np.frombuffer(exr_data.channels('R')[0], dtype=np.float32).reshape(height, width)
    green_channel = np.frombuffer(exr_data.channels('G')[0], dtype=np.float32).reshape(height, width)
    blue_channel = np.frombuffer(exr_data.channels('B')[0], dtype=np.float32).reshape(height, width)

    image_tensor = np.stack((red_channel, green_channel, blue_channel), axis=0)

    return torch.Tensor(image_tensor)
示例#13
0
def read_exr_header(fullpath):
    # type: (Union[str, Path]) -> dict
    '''
    Reads an OpenEXR image file header.

    Args:
        fullpath (str or Path): Image file path.

    Raises:
        IOError: If given filepath is not an EXR file.

    Returns:
        dict: EXR header.
    '''
    fullpath = Path(fullpath).absolute().as_posix()
    if not openexr.isOpenExrFile(fullpath):
        msg = f'{fullpath} is not an EXR file.'
        raise IOError(msg)

    img = openexr.InputFile(fullpath)
    return img.header()
def load_exr(filename, datatype=np.float16):
    import OpenEXR
    import Imath
    HALF = Imath.PixelType(Imath.PixelType.HALF)
    if not OpenEXR.isOpenExrFile(filename):
        raise Exception("File '%s' is not an EXR file." % filename)
    infile = OpenEXR.InputFile(filename)

    header = infile.header()
    dw = header['dataWindow']
    width = dw.max.x - dw.min.x + 1
    height = dw.max.y - dw.min.y + 1

    return_matrix_ch_B = np.fromstring(infile.channels('B')[0],
                                       dtype=datatype).reshape(height, width)
    return_matrix_ch_G = np.fromstring(infile.channels('G')[0],
                                       dtype=datatype).reshape(height, width)
    return_matrix_ch_R = np.fromstring(infile.channels('R')[0],
                                       dtype=datatype).reshape(height, width)
    matrix_new = np.stack(
        (return_matrix_ch_R, return_matrix_ch_G, return_matrix_ch_B), axis=-1)
    return matrix_new
示例#15
0
def load_rgb(filePath):
    ''' Loads an rgb OpenEXR image.'''

    if oe.isOpenExrFile(filePath) is not True:
        raise Exception("File ", filePath, " does not exist!")

    try:
        ifi = oe.InputFile(filePath)

        # Compute size
        header = ifi.header()
        dw = header["dataWindow"]
        w, h = dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1

        # Read the three channels
        ifiType = header["channels"]["R"].type.v
        if ifiType is not im.PixelType.UINT:
            raise Exception("Only uint32 supported! (file is type ", ifiType)

        R = ifi.channel("R", im.PixelType(ifiType))
        G = ifi.channel("G", im.PixelType(ifiType))
        B = ifi.channel("B", im.PixelType(ifiType))
        ifi.close()

        image = np.zeros((h, w, 3), dtype=np.uint32)  # order = "C"
        image[:, :,
              0] = np.core.multiarray.fromstring(R, dtype=np.uint32).reshape(
                  h, w)
        image[:, :,
              1] = np.core.multiarray.fromstring(G, dtype=np.uint32).reshape(
                  h, w)
        image[:, :,
              2] = np.core.multiarray.fromstring(B, dtype=np.uint32).reshape(
                  h, w)

    except:
        raise

    return image
示例#16
0
def read_openexr_image(filename):
    """Read image in OpenEXR file format into numpy array."""
    filename = check_file_ext(filename, ".exr")

    if not OpenEXR.isOpenExrFile(str(filename)):
        return None

    image = OpenEXR.InputFile(str(filename))

    if not image.isComplete():
        return None

    header = image.header()

    size = header["displayWindow"]
    resolution = (size.max.x - size.min.x + 1, size.max.y - size.min.y + 1)

    ch_info = header["channels"]
    if "R" in ch_info and "G" in ch_info and "B" in ch_info:
        if "A" in ch_info:
            channels = 4
        else:
            channels = 3
    else:
        return None

    image_o = np.zeros((resolution[1],resolution[0],channels), np.float32)

    ch = ["R", "G", "B", "A"]
    pt = Imath.PixelType(Imath.PixelType.FLOAT)

    for c in range(0, channels):
        image_channel = np.fromstring(image.channel(ch[c], pt), np.float32)
        image_o[:, :, c] = image_channel.reshape(resolution[1], resolution[0])

    image.close()

    return image_o
示例#17
0
def read_openexr_image(filename):
    """Read image in OpenEXR file format into numpy array."""

    if not OpenEXR.isOpenExrFile(str(filename)):
        return None

    img = OpenEXR.InputFile(str(filename))

    if not img.isComplete():
        return None

    header = img.header()

    size = header["displayWindow"]
    resolution = (size.max.x - size.min.x + 1, size.max.y - size.min.y + 1)

    ch_info = header["channels"]
    if "R" in ch_info and "G" in ch_info and "B" in ch_info:
        if "A" in ch_info:
            channels = 4
        else:
            channels = 3
    else:
        return None

    image_o = np.zeros((resolution[1], resolution[0], channels), np.float32)

    chn = ["R", "G", "B", "A"]
    pix_t = Imath.PixelType(Imath.PixelType.FLOAT)

    for channel in range(0, channels):
        img_chn = np.frombuffer(img.channel(chn[channel], pix_t), np.float32)
        image_o[:, :, channel] = img_chn.reshape(resolution[1], resolution[0])

    img.close()

    return image_o
def exrHeaderInfo(imagePath):
    '''
    check if the EXR is valid, read the header and return a key, value dict of its values
    '''
    if not 'OpenEXR' in sys.modules.keys():
        print "No openEXR module"
        return

    #check it is a valid EXR
    if OpenEXR.isOpenExrFile(imagePath):
        infile = OpenEXR.InputFile(imagePath)

    if not infile.isComplete():
        print "Invalid EXR: %s" %imagePath
        #return True here as we still want the directory scan to continue
        return True

    EXRheader = infile.header()
    rDict = {}
    for k,v in EXRheader.iteritems():
        rDict[k]=v
        #print k,v

    return rDict
示例#19
0
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)
示例#20
0
def check_exr(path):
    if not OpenEXR.isOpenExrFile(path):
        logging.warning("EXR_ERROR %s : OpenEXR could not read file", path)
        return {'valid': False, 'message': 'OpenEXR could not read file'}
    return {'valid': True, 'message': 'ok'}
示例#21
0
def preview_file(in_path, out_path, layer=None):
    """ Create preview of exr files by normalizing the color range to 8bit.

    Args:
        in_path (str): File to read
        out_path (str): File to write

    Raises:
        NoExrFileException
    """
    console.info('Started preview of {in_path}.'.format(
        in_path=os.path.basename(in_path)))

    if in_path == out_path:
        raise SameFileException(out_path)

    # start time
    time_start = time.time()

    if not OpenEXR.isOpenExrFile(in_path):
        raise NoExrFileException(in_path)

    # open exr file
    in_exr_file = OpenEXR.InputFile(in_path)

    # get open exr header
    in_exr_header = in_exr_file.header()

    pixel_type = Imath.PixelType(Imath.PixelType.FLOAT)
    data_window = in_exr_header['dataWindow']
    size = (data_window.max.x - data_window.min.x + 1,
            data_window.max.y - data_window.min.y + 1)

    # default channels
    channels = 'RGB'

    if layer:
        selected_channels = []

        for layer_name, value in in_exr_header['channels'].iteritems():
            if re.search(r'{}'.format(layer), layer_name, flags=re.IGNORECASE):
                if not layer_name in selected_channels:
                    selected_channels.append(layer_name)

        selected_channels = sort_rgba(selected_channels)

        if selected_channels:
            if len(selected_channels) < 3:
                # create greyscale image from first channel
                channels = [
                    selected_channels[0], selected_channels[0],
                    selected_channels[0]
                ]
            elif len(selected_channels) > 3:
                # maximum of 3 channels
                channels = selected_channels[:3]
            else:
                channels = selected_channels

        console.debug(channels)

    rgbf = [
        Image.fromstring("F", size, in_exr_file.channel(c, pixel_type))
        for c in channels
    ]

    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(value):
        """ Normalize value.

        Args:
            value (float): Value to normalize
        """
        return (value * scale) + darkest

    rgb8 = [im.point(normalize_0_255).convert("L") for im in rgbf]

    Image.merge("RGB", rgb8).save(out_path)

    # stop time
    time_stop = time.time()

    # duration
    duration = round(time_stop - time_start)

    console.info('Finished preview for {out_path} ({duration}s).'.format(
        out_path=os.path.basename(out_path), duration=duration))
示例#22
0
def supported(path):
    return OpenEXR.isOpenExrFile(path)
示例#23
0
def rechannel_file(in_path, out_path, layer_map=None):
    """ Rechannel layers of exr file at in_path by replacing layer names via regular expression provided by layer_map and storing a new exr file at out_path.

    Args:
        in_path (str): File to read
        out_path (str): File to write
        layer_map (dict): Regular expression / replacement name pairs

    Raises:
        NoExrFileException
    """
    console.info('Started rechannel of {in_path}.'.format(
        in_path=os.path.basename(in_path)))

    if in_path == out_path:
        raise SameFileException(out_path)

    # start time
    time_start = time.time()

    if not layer_map:
        layer_map = {}

    if not OpenEXR.isOpenExrFile(in_path):
        raise NoExrFileException(in_path)

    # open exr file
    in_exr_file = OpenEXR.InputFile(in_path)

    # get open exr header
    in_exr_header = in_exr_file.header()

    # create new copy from header
    out_exr_header = copy.deepcopy(in_exr_header)

    # reset channels
    out_exr_header['channels'] = {}

    # empty dict for matched layers
    matched_layers = {}

    for layer_name, value in in_exr_header['channels'].iteritems():
        for pattern, replacement_name in layer_map.iteritems():
            matches = re.search(r'{}'.format(pattern),
                                layer_name,
                                flags=re.IGNORECASE)

            if matches:
                match_data = matches.groupdict()

                if 'channel' in match_data.keys():
                    out_channel_name = replacement_name + '.' + match_data[
                        'channel']
                else:
                    out_channel_name = replacement_name

                # insert rechanneld channel into header with old channel value
                out_exr_header['channels'].update({out_channel_name: value})

                # store rechanneld layer with data
                matched_layers[out_channel_name] = in_exr_file.channel(
                    layer_name)

    out_exr_file = OpenEXR.OutputFile(out_path, out_exr_header)

    # copy matched layers
    if matched_layers:
        out_exr_file.writePixels(matched_layers)

    out_exr_file.close()

    # stop time
    time_stop = time.time()

    # duration
    duration = round(time_stop - time_start)

    console.info('Finished rechannel of of {out_path} ({duration}s).'.format(
        out_path=os.path.basename(out_path), duration=duration))
示例#24
0
文件: exr.py 项目: tvogels/pyexr
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)
示例#25
0
def readOpenEXR(filename):
    """ Simple read function for an OpenEXR file

    Use of this function requires that the OpenEXR package be installed.
    :param filename: The name of the OpenEXR file
    :return channel_names: List of image channel names found in the OpenEXR file
    :return im_dict: All image data in a dictionary keyed by channel names or channel groups. Channels are grouped
        into RGB triplets if the channel names have the form prefix.R, prefix.G and prefix.B.
        All image data is returned as numpy arrays.
    :return header: OpenEXR header as a dictionary.
    """
    import OpenEXR
    import Imath
    if not OpenEXR.isOpenExrFile(filename):
        raise IOError('OpenEXR file was not found, or file is not OpenEXR.')
    exr_file = OpenEXR.InputFile(filename)
    header = exr_file.header()  # Returns a dict
    channel_names = header['channels'].keys()
    data_window = header['dataWindow']
    size = (data_window.max.x - data_window.min.x + 1, data_window.max.y - data_window.min.y + 1)
    # Read all channels
    im_FLOAT = np.array([], dtype=np.float32)
    im_HALF = np.array([], dtype=np.float16)
    im_UINT = np.array([], dtype=np.uint32)
    im_dict = {}
    triplets = {}
    for i_chan, chan_name in enumerate(channel_names):
        pixel_type = str(header['channels'][chan_name]).split()[0]
        if pixel_type == 'FLOAT':
            imath_type = Imath.PixelType(Imath.PixelType.FLOAT)
        elif pixel_type == 'HALF':
            imath_type = Imath.PixelType(Imath.PixelType.HALF)
        elif pixel_type == 'UINT':
            imath_type = Imath.PixelType(Imath.PixelType.UINT)
        chan_data_str = exr_file.channel(chan_name, imath_type)
        if pixel_type == 'FLOAT':
            chan_data = np.fromstring(chan_data_str, dtype=np.float32).reshape((size[1], size[0]))
            if im_FLOAT.size == 0:
                im_FLOAT = chan_data
            else:
                im_FLOAT= np.dstack((im_FLOAT, chan_data))
        elif pixel_type == 'HALF':
            chan_data = np.fromstring(chan_data_str, dtype=np.float16).reshape((size[1], size[0]))
            if im_HALF.size == 0:
                im_HALF = chan_data
            else:
                im_HALF = np.dstack((im_HALF, chan_data))
        elif pixel_type == 'UINT':
            chan_data = np.fromstring(chan_data_str, dtype=np.uint32).reshape((size[1], size[0]))
            if im_UINT.size == 0:
                im_UINT = chan_data
            else:
                im_UINT = np.dstack((im_UINT, chan_data))
        else:
            raise ValueError('Unknown image pixel type in OpenEXR file.')
        im_dict[chan_name] = chan_data
        rgbya = chan_name[-1]  # red, green, blue, luminance, transparency
        prefix = chan_name.split('.')[0]
        if prefix == rgbya:
            prefix = 'rgb'
        if rgbya in 'RGB':
            if (prefix in triplets):
                triplets[prefix][rgbya] = chan_name
            else:
                triplets[prefix] = {rgbya: chan_name}
    for triplet in triplets:
        im_dict[triplet] = np.dstack((im_dict[triplets[triplet]['R']],
                                      im_dict[triplets[triplet]['G']],
                                      im_dict[triplets[triplet]['B']]))
    return channel_names, im_dict, header
示例#26
-1
def load_rgb(filePath):
    ''' Loads an rgb OpenEXR image.'''

    if oe.isOpenExrFile(filePath) is not True:
        raise Exception("File ", filePath, " does not exist!")

    try:
        ifi = oe.InputFile(filePath)

        # Compute size
        header = ifi.header()
        dw = header["dataWindow"]
        w, h = dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1

        # Read the three channels
        ifiType = header["channels"]["R"].type.v
        if ifiType is not im.PixelType.UINT:
            raise Exception("Only uint32 supported! (file is type ", ifiType)

        R = ifi.channel("R", im.PixelType(ifiType))
        G = ifi.channel("G", im.PixelType(ifiType))
        B = ifi.channel("B", im.PixelType(ifiType))
        ifi.close()

        image = np.zeros((h, w, 3), dtype = np.uint32) # order = "C"
        image[:, :, 0] = np.core.multiarray.fromstring(R, dtype = np.uint32).reshape(h, w)
        image[:, :, 1] = np.core.multiarray.fromstring(G, dtype = np.uint32).reshape(h, w)
        image[:, :, 2] = np.core.multiarray.fromstring(B, dtype = np.uint32).reshape(h, w)

    except:
        raise

    return image