Compose the PSD image.

        See :py:func:`~psd_tools.compose` for available extra arguments.

        :param bbox: Viewport tuple (left, top, right, bottom).
        :return: :py:class:`PIL.Image`, or `None` if there is no pixel.
343670
def compose(self, force=False, bbox=None, **kwargs):
        
        from psd_tools.api.composer import compose
        image = None
        if not force or len(self) == 0:
            image = self.topil(**kwargs)
        if image is None:
            image = compose(
                self, bbox=bbox or self.viewbox, force=force, **kwargs
            )
        return image
186008
def image_coordinates(self, point):
        ''''''
        # the dragpos is the top left position in image coordinates
        ret = wx.Point(int(self.dragpos.x + point.x/self.zoom),
                       int(self.dragpos.y + point.y/self.zoom))
        return ret
737608
def show(self, y:Image=None, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True,
        color:str='white', **kwargs):
        ""
        if ax is None: _,ax = plt.subplots(figsize=figsize)
        bboxes, lbls = self._compute_boxes()
        h,w = self.flow.size
        bboxes.add_(1).mul_(torch.tensor([h/2, w/2, h/2, w/2])).long()
        for i, bbox in enumerate(bboxes):
            if lbls is not None: text = str(lbls[i])
            else: text=None
            _draw_rect(ax, bb2hw(bbox), text=text, color=color)
182565
def _replace_bbox_none(self, bbox):
        """"""

        (bb_top, bb_left), (bb_bottom, bb_right) = bbox

        if bb_top is None:
            bb_top = 0

        if bb_left is None:
            bb_left = 0

        if bb_bottom is None:
            bb_bottom = self.code_array.shape[0] - 1

        if bb_right is None:
            bb_right = self.code_array.shape[1] - 1

        return (bb_top, bb_left), (bb_bottom, bb_right)
459308
def display(self, image):
        
        assert(image.mode == self.mode)
        assert(image.size == self.size)

        image = self.preprocess(image)

        if self.framebuffer.redraw_required(image):
            left, top, right, bottom = self._apply_offsets(self.framebuffer.bounding_box)
            width = right - left
            height = bottom - top

            self._set_position(top, right, bottom, left)

            i = 0
            buf = bytearray(width * height * 2)
            for r, g, b in self.framebuffer.getdata():
                if not(r == g == b == 0):
                    # 65K format 1
                    buf[i] = r & 0xF8 | g >> 5
                    buf[i + 1] = g << 3 & 0xE0 | b >> 3
                i += 2

            self.data(list(buf))
967248
def convert_image_data_to_pil(psd, apply_icc=True, **kwargs):
    
    from PIL import Image, ImageOps
    header = psd.header
    size = (header.width, header.height)
    channels = []
    for channel_data in psd.image_data.get_data(header):
        channels.append(_create_channel(size, channel_data, header.depth))
    alpha = _get_alpha_use(psd)
    mode = get_pil_mode(header.color_mode.name)
    if mode == 'P':
        image = Image.merge('L', channels[:get_pil_channels(mode)])
        image.putpalette(psd.color_mode_data.interleave())
    elif mode == 'MULTICHANNEL':
        image = channels[0]  # Multi-channel mode is a collection of alpha.
    else:
        image = Image.merge(mode, channels[:get_pil_channels(mode)])
    if mode == 'CMYK':
        image = image.point(lambda x: 255 - x)
    if apply_icc and 'ICC_PROFILE' in psd.image_resources:
        image = _apply_icc(image, psd.image_resources.get_data('ICC_PROFILE'))
    if alpha and mode in ('L', 'RGB'):
        image.putalpha(channels[-1])
    return _remove_white_background(image)
43382
def get_bbox(self):
        
        resource_list = self.get_resource()
        bounding_box = namedtuple('boundingbox', ['southlatitude',
                                                  'westlongitude',
                                                  'northlatitude',
                                                  'eastlongitude'])
        try:
            return [bounding_box(*resource['bbox'])
                    for resource in resource_list]
        except (KeyError, TypeError):
            try:
                if isinstance(resource_list, dict):
                    resource_list = [resource_list]
                return [bounding_box(resource['BoundingBox']['SouthLatitude'],
                                     resource['BoundingBox']['WestLongitude'],
                                     resource['BoundingBox']['NorthLatitude'],
                                     resource['BoundingBox']['EastLongitude'])
                        for resource in resource_list]
            except (KeyError, TypeError) as exc:
                print(exc)
366659
def create(cls, h:int, w:int, bboxes:Collection[Collection[int]], labels:Collection=None, classes:dict=None,
               pad_idx:int=0, scale:bool=True)->'ImageBBox':
        ""
        if isinstance(bboxes, np.ndarray) and bboxes.dtype == np.object: bboxes = np.array([bb for bb in bboxes])
        bboxes = tensor(bboxes).float()
        tr_corners = torch.cat([bboxes[:,0][:,None], bboxes[:,3][:,None]], 1)
        bl_corners = bboxes[:,1:3].flip(1)
        bboxes = torch.cat([bboxes[:,:2], tr_corners, bl_corners, bboxes[:,2:]], 1)
        flow = FlowField((h,w), bboxes.view(-1,2))
        return cls(flow, labels=labels, classes=classes, pad_idx=pad_idx, y_first=True, scale=scale)
904306
def doblob(morphed, blobdet, img, anno=True):
    
    keypoints = blobdet.detect(morphed)
    nkey = len(keypoints)
    kpsize = asarray([k.size for k in keypoints])
    final = img.copy()  # is the .copy necessary?

    final = cv2.drawKeypoints(img, keypoints, outImage=final,
                              flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# %% plot count of blobs
    if anno:
        cv2.putText(final, text=str(nkey), org=(int(img.shape[1]*.9), 25),
                    fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=2,
                    color=(0, 255, 0), thickness=2)

    return final, nkey, kpsize
1121050
def create(self, image, geometry, options):
        
        image = self.cropbox(image, geometry, options)
        image = self.orientation(image, geometry, options)
        image = self.colorspace(image, geometry, options)
        image = self.remove_border(image, options)
        image = self.scale(image, geometry, options)
        image = self.crop(image, geometry, options)
        image = self.rounded(image, geometry, options)
        image = self.blur(image, geometry, options)
        image = self.padding(image, geometry, options)
        return image
927673
def flatten(image, bgcolor=None):
        
        if bgcolor:
            background = PIL.Image.new('RGB', image.size, bgcolor)
            background.paste(image, mask=image.split()[3])
            return background

        return image.convert('RGB')
409369
def compose_layer(layer, force=False, **kwargs):
    """"""
    from PIL import Image, ImageChops
    assert layer.bbox != (0, 0, 0, 0), 'Layer bbox is (0, 0, 0, 0)'

    image = layer.topil(**kwargs)
    if image is None or force:
        texture = create_fill(layer)
        if texture is not None:
            image = texture

    if image is None:
        return image

    # TODO: Group should have the following too.

    # Apply mask.
    if layer.has_mask() and not layer.mask.disabled:
        mask_bbox = layer.mask.bbox
        if (
            (mask_bbox[2] - mask_bbox[0]) > 0 and
            (mask_bbox[3] - mask_bbox[1]) > 0
        ):
            color = layer.mask.background_color
            offset = (mask_bbox[0] - layer.left, mask_bbox[1] - layer.top)
            mask = Image.new('L', image.size, color=color)
            mask.paste(layer.mask.topil(), offset)
            if image.mode.endswith('A'):
                # What should we do here? There are two alpha channels.
                pass
            image.putalpha(mask)
    elif layer.has_vector_mask() and (force or not layer.has_pixels()):
        mask = draw_vector_mask(layer)
        # TODO: Stroke drawing.
        texture = image
        image = Image.new(image.mode, image.size, 'white')
        image.paste(texture, mask=mask)

    # Apply layer fill effects.
    apply_effect(layer, image)

    # Clip layers.
    if layer.has_clip_layers():
        clip_box = extract_bbox(layer.clip_layers)
        inter_box = intersect(layer.bbox, clip_box)
        if inter_box != (0, 0, 0, 0):
            clip_image = compose(layer.clip_layers, bbox=layer.bbox)
            mask = image.getchannel('A')
            if clip_image.mode.endswith('A'):
                mask = ImageChops.multiply(clip_image.getchannel('A'), mask)
            clip_image.putalpha(mask)
            image = _blend(image, clip_image, (0, 0))

    # Apply opacity.
    if layer.opacity < 255:
        opacity = layer.opacity
        if image.mode.endswith('A'):
            opacity = opacity / 255.
            channels = list(image.split())
            channels[-1] = channels[-1].point(lambda x: int(x * opacity))
            image = Image.merge(image.mode, channels)
        else:
            image.putalpha(opacity)

    return image
11541
def make_thumbnail(file, size, bbox=None):
    '''
    
    '''
    image = Image.open(file)
    if bbox:
        thumbnail = crop_thumbnail(image, size, bbox)
    else:
        thumbnail = center_thumbnail(image, size)
    return _img_to_file(thumbnail)
700057
def get_bbox(self):
        """"""

        x_min = self.x
        x_max = x_min + self.width
        y_min = self.y
        y_max = self.y + self.height

        return x_min, x_max, y_min, y_max
796690
def fig2bmp(figure, width, height, dpi, zoom):
    

    dpi *= float(zoom)

    figure.set_figwidth(width / dpi)
    figure.set_figheight(height / dpi)
    figure.subplots_adjust()

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")

    try:
        # The padding is too small for small sizes. This fixes it.
        figure.tight_layout(pad=1.0/zoom)
    except ValueError:
        pass

    figure.set_canvas(FigureCanvas(figure))
    png_stream = StringIO()

    figure.savefig(png_stream, format='png', dpi=(dpi))

    png_stream.seek(0)
    img = wx.ImageFromStream(png_stream, type=wx.BITMAP_TYPE_PNG)

    return wx.BitmapFromImage(img)
975168
def export_image(self, bbox, zoomlevel, imagepath):
        
        assert has_pil, _("Cannot export image without python PIL")
        grid = self.grid_tiles(bbox, zoomlevel)
        width = len(grid[0])
        height = len(grid)
        widthpix = width * self.tile_size
        heightpix = height * self.tile_size

        result = Image.new("RGBA", (widthpix, heightpix))
        offset = (0, 0)
        for i, row in enumerate(grid):
            for j, (x, y) in enumerate(row):
                offset = (j * self.tile_size, i * self.tile_size)
                img = self._tile_image(self.tile((zoomlevel, x, y)))
                result.paste(img, offset)
        logger.info(_("Save resulting image to '%s'") % imagepath)
        result.save(imagepath)
322548
def blit(self, bbox=None):
        
        if bbox is None:
            self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
            self.gui_repaint()
            return

        l, b, w, h = bbox.bounds
        r = l + w
        t = b + h
        x = int(l)
        y = int(self.bitmap.GetHeight() - t)

        srcBmp = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
        srcDC = wx.MemoryDC()
        srcDC.SelectObject(srcBmp)

        destDC = wx.MemoryDC()
        destDC.SelectObject(self.bitmap)

        destDC.BeginDrawing()
        destDC.Blit(x, y, int(w), int(h), srcDC, x, y)
        destDC.EndDrawing()

        destDC.SelectObject(wx.NullBitmap)
        srcDC.SelectObject(wx.NullBitmap)
        self.gui_repaint()