Convert a PIL image into a Cairo surface
973363
def image2surface(img):
    
    if not CAIRO_AVAILABLE:
        raise Exception("Cairo not available(). image2surface() cannot work.")

    # TODO(Jflesch): Python 3 problem
    # cairo.ImageSurface.create_for_data() raises NotImplementedYet ...

    # img.putalpha(256)
    # (width, height) = img.size
    # imgd = img.tobytes('raw', 'BGRA')
    # imga = array.array('B', imgd)
    # stride = width * 4
    #  return cairo.ImageSurface.create_for_data(
    #      imga, cairo.FORMAT_ARGB32, width, height, stride)

    # So we fall back to this method:
    global g_lock
    with g_lock:
        img_io = io.BytesIO()
        img.save(img_io, format="PNG")
        img_io.seek(0)
        return cairo.ImageSurface.create_from_png(img_io)
21306
def shift_to_coords(self, pix, fill_value=np.nan):
        """"""

        pix_offset = self.get_offsets(pix)
        dpix = np.zeros(len(self.shape) - 1)
        for i in range(len(self.shape) - 1):
            x = self.rebin * (pix[i] - pix_offset[i + 1]
                              ) + (self.rebin - 1.0) / 2.
            dpix[i] = x - self._pix_ref[i]

        pos = [pix_offset[i] + self.shape[i] // 2
               for i in range(self.data.ndim)]
        s0, s1 = utils.overlap_slices(self.shape_out, self.shape, pos)

        k = np.zeros(self.data.shape)
        for i in range(k.shape[0]):
            k[i] = shift(self._data_spline[i], dpix, cval=np.nan,
                         order=2, prefilter=False)

        for i in range(1, len(self.shape)):
            k = utils.sum_bins(k, i, self.rebin)

        k0 = np.ones(self.shape_out) * fill_value

        if k[s1].size == 0 or k0[s0].size == 0:
            return k0
        k0[s0] = k[s1]
        return k0
1150479
def surface_to_array(surface):
    
    if hasattr(surface, 'surfaces'):  # multiplanar surfaces
        n = len(surface.surfaces)
        arr = numpy.zeros((3, n, 4), F32)
        for i, surf in enumerate(surface.surfaces):
            arr[:, i] = surf.mesh.array
        return arr
    mesh = surface.mesh
    if len(mesh.lons.shape) == 1:  # 1D mesh
        shp = (3, 1) + mesh.lons.shape
    else:  # 2D mesh
        shp = (3,) + mesh.lons.shape
    return mesh.array.reshape(shp)
227268
def save(self, fn:PathOrStr):
        ""
        x = image2np(self.data*255).astype(np.uint8)
        PIL.Image.fromarray(x).save(fn)
436906
def _load_texture(file_name, resolver):
    
    file_data = resolver.get(file_name)
    image = PIL.Image.open(util.wrap_as_stream(file_data))
    return image
473817
def create_image(self, image_name=None, scale_ratio=1, window=None):
        
        size = 48 * scale_ratio
        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(image_name, -1, size, True)
        image = Gtk.Image()

        # Creating the cairo surface is necessary for proper scaling on HiDPI
        try:
            surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale_ratio, window)
            image.set_from_surface(surface)

        # Fallback for GTK+ older than 3.10
        except AttributeError:
            image.set_from_pixbuf(pixbuf)

        return image
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
146000
def convert_mask_to_pil(mask, real=True):
    """"""
    from PIL import Image
    header = mask._layer._psd._record.header
    channel_ids = [ci.id for ci in mask._layer._record.channel_info]
    if real and mask._has_real():
        width = mask._data.real_right - mask._data.real_left
        height = mask._data.real_bottom - mask._data.real_top
        channel = mask._layer._channels[
            channel_ids.index(ChannelID.REAL_USER_LAYER_MASK)
        ]
    else:
        width = mask._data.right - mask._data.left
        height = mask._data.bottom - mask._data.top
        channel = mask._layer._channels[
            channel_ids.index(ChannelID.USER_LAYER_MASK)
        ]
    data = channel.get_data(width, height, header.depth, header.version)
    return _create_channel((width, height), data, header.depth)
403533
def smoothscale(self, surface):
        
        return self._pygame.transform.smoothscale(surface, self._output_size)
837955
def pil2tensor(image:Union[NPImage,NPArray],dtype:np.dtype)->TensorImage:
    ""
    a = np.asarray(image)
    if a.ndim==2 : a = np.expand_dims(a,2)
    a = np.transpose(a, (1, 0, 2))
    a = np.transpose(a, (2, 1, 0))
    return torch.from_numpy(a.astype(dtype, copy=False) )
994738
def from_image(cls, image):
        
        (w, h) = image.size

        # Thermal paper is 512 pixels wide
        if w > 512:
            ratio = 512. / w
            h = int(h * ratio)
            image = image.resize((512, h), Image.ANTIALIAS)
        if image.mode != '1':
            image = image.convert('1')

        pixels = np.array(list(image.getdata())).reshape(h, w)

        # Add white pixels so that image fits into bytes
        extra_rows = int(math.ceil(h / 24)) * 24 - h
        extra_pixels = np.ones((extra_rows, w), dtype=bool)
        pixels = np.vstack((pixels, extra_pixels))
        h += extra_rows
        nb_stripes = h / 24
        pixels = pixels.reshape(nb_stripes, 24, w).swapaxes(1, 2).reshape(-1, 8)

        nh = int(w / 256)
        nl = w % 256
        data = []

        pixels = np.invert(np.packbits(pixels))
        stripes = np.split(pixels, nb_stripes)

        for stripe in stripes:

            data.extend([
                ESC,
                42,  # *
                33,  # double density mode
                nl,
                nh])

            data.extend(stripe)
            data.extend([
                27,   # ESC
                74,   # J
                48])

        # account for double density mode
        height = h * 2
        return cls(data, height)
762334
def tiles_to_pixels(self, tiles):
        """"""
        pixel_coords = Vector2()
        pixel_coords.X = tiles[0] * self.spritesheet[0].width
        pixel_coords.Y = tiles[1] * self.spritesheet[0].height
        return pixel_coords
1131111
def frompil(self, pillow_image):
        """"""
        bio = BytesIO()
        pillow_image.save(bio, format='png', compress_level=1)
        py_buffer = bio.getbuffer()
        c_buffer = ffi.from_buffer(py_buffer)
        with _LeptonicaErrorTrap():
            pix = Pix(lept.pixReadMem(c_buffer, len(c_buffer)))
            return pix
1316539
def convert_to_odl(image):
    """"""

    shape = image.shape

    if len(shape) == 2:
        space = odl.uniform_discr([0, 0], shape, shape)
    elif len(shape) == 3:
        d = shape[2]
        shape = shape[:2]
        image = np.transpose(image, (2, 0, 1))
        space = odl.uniform_discr([0, 0], shape, shape) ** d

    image = space.element(image)

    return image
1047619
def _load_pil_image(self, filename):
        
        self._channel_data = []
        self._original_channel_data = []

        im = Image.open(filename)
        self._image = ImageOps.grayscale(im)
        im.load()

        file_data = np.asarray(im, float)
        file_data = file_data / file_data.max()

        # if the image has more than one channel, load them
        if( len(file_data.shape) == 3 ):
            num_channels = file_data.shape[2]
            for i in range(num_channels):
                self._channel_data.append( file_data[:, :, i])
                self._original_channel_data.append( file_data[:, :, i] )
308534
def dump(self):
        """"""
        scan_lines = bytearray()
        for y in range(self.height):
            scan_lines.append(0)  # filter type 0 (None)
            scan_lines.extend(
                self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)]
            )
        # image represented as RGBA tuples, no interlacing
        return SIGNATURE + \
            self.pack_chunk(b'IHDR', struct.pack(b"!2I5B",
                                                 self.width, self.height,
                                                 8, 6, 0, 0, 0)) + \
            self.pack_chunk(b'IDAT', zlib.compress(bytes(scan_lines), 9)) + \
            self.pack_chunk(b'IEND', b'')
206493
def render_image(self, rgbobj, dst_x, dst_y):
        
        self.logger.debug("redraw surface")
        if self.surface is None:
            return

        # Prepare array for Cairo rendering
        # TODO: is there some high-bit depth option for Cairo?
        arr = rgbobj.get_array(self.rgb_order, dtype=np.uint8)

        daht, dawd, depth = arr.shape
        self.logger.debug("arr shape is %dx%dx%d" % (dawd, daht, depth))

        cr = cairo.Context(self.surface)
        # TODO: is it really necessary to hang on to this context?
        self.cr = cr

        # fill surface with background color
        imgwin_wd, imgwin_ht = self.viewer.get_window_size()
        cr.rectangle(0, 0, imgwin_wd, imgwin_ht)
        r, g, b = self.viewer.get_bg()
        cr.set_source_rgba(r, g, b)
        cr.fill()

        stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32,
                                                            dawd)
        img_surface = cairo.ImageSurface.create_for_data(arr,
                                                         cairo.FORMAT_ARGB32,
                                                         dawd, daht, stride)

        cr.set_source_surface(img_surface, dst_x, dst_y)
        cr.set_operator(cairo.OPERATOR_SOURCE)

        cr.mask_surface(img_surface, dst_x, dst_y)
        cr.fill()