Load a texture from a file into a PIL image.
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
1144545
def convert(filepath, outfilepath):
    """"""

    logger = logging.getLogger("example1")
    logger.setLevel(logging.INFO)
    fmt = logging.Formatter(STD_FORMAT)
    stderrHdlr = logging.StreamHandler()
    stderrHdlr.setFormatter(fmt)
    logger.addHandler(stderrHdlr)

    fi = ImageViewCairo(logger)
    fi.configure(500, 1000)

    # Load fits file
    image = load_data(filepath, logger=logger)

    # Make any adjustments to the image that we want
    fi.set_bg(1.0, 1.0, 1.0)
    fi.set_image(image)
    fi.auto_levels()
    fi.zoom_fit()
    fi.center_image()

    ht_pts = 11.0 / point_in
    wd_pts = 8.5 / point_in
    off_x, off_y = 0, 0

    out_f = open(outfilepath, 'w')
    surface = cairo.PDFSurface(out_f, wd_pts, ht_pts)
    # set pixels per inch
    surface.set_fallback_resolution(300, 300)
    surface.set_device_offset(off_x, off_y)
    try:
        fi.save_image_as_surface(surface)
        surface.show_page()
        surface.flush()
        surface.finish()
    finally:
        out_f.close()
293983
def numpy_to_texture(image):
    """"""
    if not isinstance(image, np.ndarray):
        raise TypeError('Unknown input type ({})'.format(type(image)))
    if image.ndim != 3 or image.shape[2] != 3:
        raise AssertionError('Input image must be nn by nm by RGB')
    grid = vtki.UniformGrid((image.shape[1], image.shape[0], 1))
    grid.point_arrays['Image'] = np.flip(image.swapaxes(0,1), axis=1).reshape((-1, 3), order='F')
    grid.set_active_scalar('Image')
    return image_to_texture(grid)
862796
def _load_image(cls, rkey):
        """"""

        v = cls._stock[rkey]
        img = None
        itype = v['type']
        if itype in ('stock', 'data'):
            img = tk.PhotoImage(format=v['format'], data=v['data'])
        elif itype == 'created':
            img = v['image']
        else:
            img = tk.PhotoImage(file=v['filename'])
        cls._cached[rkey] = img
        logger.info('Loaded resource %s.' % rkey)
        return img
1080234
def loader():
    """"""
    url = request.args.get('url')  # read image URL as a request URL param
    response = requests.get(url)  # make request to static image file
    return response.content
1182098
def loadIntoTextureD3D11_Async(self, textureId, pDstTexture):
        """"""

        fn = self.function_table.loadIntoTextureD3D11_Async
        result = fn(textureId, pDstTexture)
        return result
628241
def select_ocr_image(infiles, output_file, log, context):
    """"""

    image = infiles[0]
    options = context.get_options()
    pageinfo = get_pageinfo(image, context)

    with Image.open(image) as im:
        from PIL import ImageColor
        from PIL import ImageDraw

        white = ImageColor.getcolor('#ffffff', im.mode)
        # pink = ImageColor.getcolor('#ff0080', im.mode)
        draw = ImageDraw.ImageDraw(im)

        xres, yres = im.info['dpi']
        log.debug('resolution %r %r', xres, yres)

        if not options.force_ocr:
            # Do not mask text areas when forcing OCR, because we need to OCR
            # all text areas
            mask = None  # Exclude both visible and invisible text from OCR
            if options.redo_ocr:
                mask = True  # Mask visible text, but not invisible text

            for textarea in pageinfo.get_textareas(visible=mask, corrupt=None):
                # Calculate resolution based on the image size and page dimensions
                # without regard whatever resolution is in pageinfo (may differ or
                # be None)
                bbox = [float(v) for v in textarea]
                xscale, yscale = float(xres) / 72.0, float(yres) / 72.0
                pixcoords = [
                    bbox[0] * xscale,
                    im.height - bbox[3] * yscale,
                    bbox[2] * xscale,
                    im.height - bbox[1] * yscale,
                ]
                pixcoords = [int(round(c)) for c in pixcoords]
                log.debug('blanking %r', pixcoords)
                draw.rectangle(pixcoords, fill=white)
                # draw.rectangle(pixcoords, outline=pink)

        if options.mask_barcodes or options.threshold:
            pix = leptonica.Pix.frompil(im)
            if options.threshold:
                pix = pix.masked_threshold_on_background_norm()
            if options.mask_barcodes:
                barcodes = pix.locate_barcodes()
                for barcode in barcodes:
                    decoded, rect = barcode
                    log.info('masking barcode %s %r', decoded, rect)
                    draw.rectangle(rect, fill=white)
            im = pix.topil()

        del draw
        # Pillow requires integer DPI
        dpi = round(xres), round(yres)
        im.save(output_file, dpi=dpi)
871234
def bind_texture(texture):
    """"""
    if not getattr(texture, 'image', None):
        texture.image = load_image(texture.path)

    glEnable(texture.image.target)
    glBindTexture(texture.image.target, texture.image.id)
    gl.glTexParameterf(texture.image.target,
                       gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE)
    gl.glTexParameterf(texture.image.target,
                       gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE)
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
231129
function getTextureFromData(gl, data, opts) {
  if (data instanceof Texture2D) {
    return data;
  }
  return new Texture2D(gl, Object.assign({data}, opts));
}
397583
def resolve_image_as_pil(self, image_url, coords=None):
        
        files = self.mets.find_files(url=image_url)
        if files:
            image_filename = self.download_file(files[0]).local_filename
        else:
            image_filename = self.download_url(image_url)

        if image_url not in self.image_cache['pil']:
            self.image_cache['pil'][image_url] = Image.open(image_filename)

        pil_image = self.image_cache['pil'][image_url]

        if coords is None:
            return pil_image
        if image_url not in self.image_cache['cv2']:
            log.debug("Converting PIL to OpenCV: %s", image_url)
            color_conversion = cv2.COLOR_GRAY2BGR if pil_image.mode in ('1', 'L') else  cv2.COLOR_RGB2BGR
            pil_as_np_array = np.array(pil_image).astype('uint8') if pil_image.mode == '1' else np.array(pil_image)
            self.image_cache['cv2'][image_url] = cv2.cvtColor(pil_as_np_array, color_conversion)
        cv2_image = self.image_cache['cv2'][image_url]
        poly = np.array(coords, np.int32)
        log.debug("Cutting region %s from %s", coords, image_url)
        region_cut = cv2_image[
            np.min(poly[:, 1]):np.max(poly[:, 1]),
            np.min(poly[:, 0]):np.max(poly[:, 0])
        ]
        return Image.fromarray(region_cut)
862311
def LoadImage(filename):
    ''''''
    app_dir = os.path.dirname(os.path.realpath(__file__))
    path = os.path.join(app_dir, 'images', filename)
    return Tkinter.PhotoImage(file=path)
277239
def load_texture(self, file_path, cell_size=(256, 256)):
        
        super(SpriteSheet, self).load_texture(file_path)
        self.__cell_bounds = cell_size
        self.__generate_cells()
1336983
def load_object(filename):
    """"""
    logging.info('loading {}...'.format(filename))
    try:
        with gzip.GzipFile(filename, 'rb') as f:
            buf = ''
            while True:
                data = f.read()
                if data == '':
                    break
                buf += data
            return pickle.loads(buf)
    except Exception as e:
        logging.error('load failure: {}'.format(e))
        raise
259924
def convert_thumbnail_to_pil(thumbnail, mode='RGB'):
    """"""
    from PIL import Image
    if thumbnail.fmt == 0:
        size = (thumbnail.width, thumbnail.height)
        stride = thumbnail.widthbytes
        return Image.frombytes('RGBX', size, thumbnail.data, 'raw', mode,
                                stride)
    elif thumbnail.fmt == 1:
        return Image.open(io.BytesIO(thumbnail.data))
    else:
        raise ValueError('Unknown thumbnail format %d' % (thumbnail.fmt))
1352554
def load_from(self, image):
        
        if not isinstance(image, self.__class__):
            raise ConuException("Invalid source image type", type(image))
        image.save_to(self)
402197
def pil(self, **params_to_override):
        """"""
        from PIL.Image import fromarray
        nchans = self.num_channels()

        if nchans in [0, 1]:
            mode, arr = None, self(**params_to_override)
            arr = (255.0 / arr.max() * (arr - arr.min())).astype(np.uint8)

        elif nchans in [3,4]:
            mode = 'RGB' if nchans==3 else 'RGBA'
            arr = np.dstack(self.channels(**params_to_override).values()[1:])
            arr = (255.0*arr).astype(np.uint8)

        else:
            raise ValueError("Unsupported number of channels")

        return fromarray(arr, mode)