Load image using Numpy.
517364
def _load_npy(self, filename):
        
        self._channel_data = []
        self._original_channel_data = []
        file_channel_data = np.load(filename)
        file_channel_data = file_channel_data / file_channel_data.max()

        for i in range(file_channel_data.shape[2]):
            self._channel_data.append(file_channel_data[:, :, i])
            self._original_channel_data.append(file_channel_data[:, :, i])

        self._image = file_channel_data.sum(2) / file_channel_data.shape[2]
1020092
def read_numpy(fd, byte_order, dtype, count):
    """"""
    return numpy.fromfile(fd, byte_order+dtype[-1], count)
377796
def load_image(self, idx):
        
        im = Image.open('{}/data/images/img_{}.png'.format(self.nyud_dir, idx))
        in_ = np.array(im, dtype=np.float32)
        in_ = in_[:,:,::-1]
        in_ -= self.mean_bgr
        in_ = in_.transpose((2,0,1))
        return in_
21776
def _image_of_size(image_size):
  """"""
  return np.random.uniform(0, 256, [image_size, image_size, 3]).astype(np.uint8)
689129
def load_image(self, imagepath, width=None, height=None):
        """"""

        if width:
            self.width = width
            self.canvas["width"] = width
        if height:
            self.height = height
            self.canvas["height"] = height

        self.image = imagepath
        size = (self.width, self.height)
        load_image(self.canvas, self.image, bounds=size)
        self.canvas.update_idletasks()
1296040
def _load_int(self):
        """"""
        values = numpy.fromfile(self.filepath_int)
        if self.NDIM > 0:
            values = values.reshape(self.seriesshape)
        return values
1257748
def _image2array(filepath):
    '''
    
    '''
    im = Pimage.open(filepath).convert('RGB')
    (width, height) = im.size
    _r = np.array(list(im.getdata(0)))/255.0
    _g = np.array(list(im.getdata(1)))/255.0
    _b = np.array(list(im.getdata(2)))/255.0
    _r = _r.reshape((height, width))
    _g = _g.reshape((height, width))
    _b = _b.reshape((height, width))
    return _r, _g, _b
227268
def save(self, fn:PathOrStr):
        ""
        x = image2np(self.data*255).astype(np.uint8)
        PIL.Image.fromarray(x).save(fn)
616931
def load_tiff(file):
    
    ndv, xsize, ysize, geot, projection, datatype = get_geo_info(file)
    data = gdalnumeric.LoadFile(file)
    data = np.ma.masked_array(data, mask=data == ndv, fill_value=ndv)
    return data
571699
def load_image(file) -> DataAndMetadata.DataAndMetadata:
    
    if isinstance(file, str) or isinstance(file, str):
        with open(file, "rb") as f:
            return load_image(f)
    dmtag = parse_dm3.parse_dm_header(file)
    dmtag = fix_strings(dmtag)
    # display_keys(dmtag)
    img_index = -1
    image_tags = dmtag['ImageList'][img_index]
    data = imagedatadict_to_ndarray(image_tags['ImageData'])
    calibrations = []
    calibration_tags = image_tags['ImageData'].get('Calibrations', dict())
    for dimension in calibration_tags.get('Dimension', list()):
        origin, scale, units = dimension.get('Origin', 0.0), dimension.get('Scale', 1.0), dimension.get('Units', str())
        calibrations.append((-origin * scale, scale, units))
    calibrations = tuple(reversed(calibrations))
    if len(data.shape) == 3 and data.dtype != numpy.uint8:
        if image_tags['ImageTags'].get('Meta Data', dict()).get("Format", str()).lower() in ("spectrum", "spectrum image"):
            if data.shape[1] == 1:
                data = numpy.squeeze(data, 1)
                data = numpy.moveaxis(data, 0, 1)
                data_descriptor = DataAndMetadata.DataDescriptor(False, 1, 1)
                calibrations = (calibrations[2], calibrations[0])
            else:
                data = numpy.moveaxis(data, 0, 2)
                data_descriptor = DataAndMetadata.DataDescriptor(False, 2, 1)
                calibrations = tuple(calibrations[1:]) + (calibrations[0],)
        else:
            data_descriptor = DataAndMetadata.DataDescriptor(False, 1, 2)
    elif len(data.shape) == 4 and data.dtype != numpy.uint8:
        # data = numpy.moveaxis(data, 0, 2)
        data_descriptor = DataAndMetadata.DataDescriptor(False, 2, 2)
    elif data.dtype == numpy.uint8:
        data_descriptor = DataAndMetadata.DataDescriptor(False, 0, len(data.shape[:-1]))
    else:
        data_descriptor = DataAndMetadata.DataDescriptor(False, 0, len(data.shape))
    brightness = calibration_tags.get('Brightness', dict())
    origin, scale, units = brightness.get('Origin', 0.0), brightness.get('Scale', 1.0), brightness.get('Units', str())
    intensity = -origin * scale, scale, units
    timestamp = None
    timezone = None
    timezone_offset = None
    title = image_tags.get('Name')
    properties = dict()
    if 'ImageTags' in image_tags:
        voltage = image_tags['ImageTags'].get('ImageScanned', dict()).get('EHT', dict())
        if voltage:
            properties.setdefault("hardware_source", dict())["autostem"] = { "high_tension_v": float(voltage) }
        dm_metadata_signal = image_tags['ImageTags'].get('Meta Data', dict()).get('Signal')
        if dm_metadata_signal and dm_metadata_signal.lower() == "eels":
            properties.setdefault("hardware_source", dict())["signal_type"] = dm_metadata_signal
        if image_tags['ImageTags'].get('Meta Data', dict()).get("Format", str()).lower() in ("spectrum", "spectrum image"):
            data_descriptor.collection_dimension_count += data_descriptor.datum_dimension_count - 1
            data_descriptor.datum_dimension_count = 1
        if image_tags['ImageTags'].get('Meta Data', dict()).get("IsSequence", False) and data_descriptor.collection_dimension_count > 0:
            data_descriptor.is_sequence = True
            data_descriptor.collection_dimension_count -= 1
        timestamp_str = image_tags['ImageTags'].get("Timestamp")
        if timestamp_str:
            timestamp = get_datetime_from_timestamp_str(timestamp_str)
        timezone = image_tags['ImageTags'].get("Timezone")
        timezone_offset = image_tags['ImageTags'].get("TimezoneOffset")
        # to avoid having duplicate copies in Swift, get rid of these tags
        image_tags['ImageTags'].pop("Timestamp", None)
        image_tags['ImageTags'].pop("Timezone", None)
        image_tags['ImageTags'].pop("TimezoneOffset", None)
        # put the image tags into properties
        properties.update(image_tags['ImageTags'])
    dimensional_calibrations = [Calibration.Calibration(c[0], c[1], c[2]) for c in calibrations]
    while len(dimensional_calibrations) < data_descriptor.expected_dimension_count:
        dimensional_calibrations.append(Calibration.Calibration())
    intensity_calibration = Calibration.Calibration(intensity[0], intensity[1], intensity[2])
    return DataAndMetadata.new_data_and_metadata(data,
                                                 data_descriptor=data_descriptor,
                                                 dimensional_calibrations=dimensional_calibrations,
                                                 intensity_calibration=intensity_calibration,
                                                 metadata=properties,
                                                 timestamp=timestamp,
                                                 timezone=timezone,
                                                 timezone_offset=timezone_offset)
403139
def load(self, draw_bbox = False, **kwargs):
        '''  '''
        im = Image.new('RGBA', self.img_size)
        draw = None
        if draw_bbox:
            draw = ImageDraw.Draw(im)

        for sprite in self.images:
            data = sprite.load()
            sprite_im = Image.open(BytesIO(data))

            size = sprite.imgrect
            im.paste(sprite_im, (size[0], size[2]))
            if draw_bbox:
                draw.rectangle((size[0], size[2], size[1], size[3]), outline='red')

        del draw
        b = BytesIO()
        im.save(b, format = 'PNG')
        return b.getvalue()
1254636
def save_img(object, handle, **kwargs):
    """"""

    if isinstance(object, np.ndarray):
        normalized = _normalize_array(object)
        object = PIL.Image.fromarray(normalized)

    if isinstance(object, PIL.Image.Image):
        object.save(handle, **kwargs)  # will infer format from handle's url ext.
    else:
        raise ValueError("Can only save_img for numpy arrays or PIL.Images!")
1337025
def png(self):
        """"""
        use_plugin('freeimage')
        with TemporaryFilePath(suffix='.png') as tmp:
            safe_range_im = 255 * normalise(self)
            imsave(tmp.fpath, safe_range_im.astype(np.uint8))
            with open(tmp.fpath, 'rb') as fh:
                return fh.read()
266229
def _from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False):
    
    if is_rgb: has_components = True
    ndim = data.ndim
    if has_components:
        ndim -= 1
    dtype = data.dtype.name
    ptype = _npy_to_itk_map[dtype]

    data = np.array(data)

    if origin is None: origin = tuple([0.]*ndim)
    if spacing is None: spacing = tuple([1.]*ndim)
    if direction is None: direction = np.eye(ndim)

    libfn = utils.get_lib_fn('fromNumpy%s%i' % (_ntype_type_map[dtype], ndim))

    if not has_components:
        itk_image = libfn(data, data.shape[::-1])
        ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=1, pointer=itk_image)
        ants_image.set_origin(origin)
        ants_image.set_spacing(spacing)
        ants_image.set_direction(direction)
        ants_image._ndarr = data
    else:
        arrays = [data[i,...].copy() for i in range(data.shape[0])]
        data_shape = arrays[0].shape
        ants_images = []
        for i in range(len(arrays)):
            tmp_ptr = libfn(arrays[i], data_shape[::-1])
            tmp_img = iio.ANTsImage(pixeltype=ptype,
                                    dimension=ndim,
                                    components=1,
                                    pointer=tmp_ptr)
            tmp_img.set_origin(origin)
            tmp_img.set_spacing(spacing)
            tmp_img.set_direction(direction)
            tmp_img._ndarr = arrays[i]
            ants_images.append(tmp_img)
        ants_image = utils.merge_channels(ants_images)
        if is_rgb: ants_image = ants_image.vector_to_rgb()
    return ants_image
1216888
def from_dimensions(cls, width, height, channels, filename=None,
                        grayscale=False, channel_bitdepth=8,
                        has_alpha=False, palette=None):
        
        assert 1 <= channels <= 4, "PNG only supports 1 to 4 channels per pixel. Error writing %s." % filename

        dimensions = (height, width, channels)
        if channels == 1:
            dimensions = (height, width)  # keep the array 2-dimensional when possible

        _array = numpy.zeros(dimensions, dtype=PNGWriter.get_dtype(channel_bitdepth))
        return cls(_array, filename,
                   grayscale=grayscale, channel_bitdepth=channel_bitdepth,
                   has_alpha=has_alpha, palette=palette, channels=channels)
292322
def image(self, img):
        """"""
        if img.mode != '1':
            raise ValueError('Image must be in mode 1.')
        imwidth, imheight = img.size
        if imwidth != self.width or imheight != self.height:
            raise ValueError('Image must be same dimensions as display ({0}x{1}).' \
                .format(self.width, self.height))
        # Grab all the pixels from the image, faster than getpixel.
        pixels = img.load()
        # Clear buffer
        for i in range(len(self.buf)):
            self.buf[i] = 0
        # Iterate through the pixels
        for x in range(self.width):       # yes this double loop is slow,
            for y in range(self.height):  #  but these displays are small!
                if pixels[(x, y)]:
                    self.pixel(x, y, 1)
476949
def from_image(cls, img_filename, mipmap=False, **kwargs):
        """"""
        img = pyglet.image.load(img_filename)
        tex = img.get_mipmapped_texture() if mipmap else img.get_texture()
        gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
        return cls(id=tex.id, data=tex, mipmap=mipmap, **kwargs)