o
    :ήc5                     @   s   d Z ddlZddlmZ ddlmZmZ ddlm	Z	 ddl
mZmZmZmZ dd	lmZ dd
lmZmZmZmZmZ ddlmZmZ ddlmZ ddlmZ ddgZdd ZG dd dej Z!G dd de!Z"dS )z<
ImageViewer class for viewing and interacting with images.
    N   )io)dtype_rangeimg_as_float)rescale_intensity   )	QtWidgetsQtGuiQtSignal)Slider)dialogs
init_qtappfigimagestart_qtappupdate_axes_image)BlitManagerEventManager)Plugin)warnImageViewerCollectionViewerc                 C   sx   |   }|jdkr"| jj| jjf}t||d}| t|}t|S |jdkr8|jd dkr8t	
|t	|f}t|S )a  Return RGB image from the given matplotlib image object.

    Each image in a matplotlib figure has its own colormap and normalization
    function. Return RGBA (RGB + alpha channel) image with float dtype.

    Parameters
    ----------
    mpl_image : matplotlib.image.AxesImage object
        The image being converted.

    Returns
    -------
    img : array of float, shape (M, N, 4)
        An image of float values in [0, 1].
    r   )in_ranger   )	get_arrayndimnormvminvmaxr   cmapr   shapenpdstack	ones_like)	mpl_imageimageinput_range r&   B/tmp/pip-target-vg8gfxp4/lib/python/skimage/viewer/viewers/core.pympl_image_to_rgba   s   
r(   c                       s   e Zd ZdZejejejejdZ	e
ejZd. fdd	Zdd Zd/d	d
Zd0ddZdd Zdd Zd0ddZdd Zd1 fdd	Zd.ddZdd Zedd Zejdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Z d*d+ Z!d,d- Z"  Z#S )2r   a,  Viewer for displaying images.

    This viewer is a simple container object that holds a Matplotlib axes
    for showing images. `ImageViewer` doesn't subclass the Matplotlib axes (or
    figure) because of the high probability of name collisions.

    Subclasses and plugins will likely extend the `update_image` method to add
    custom overlays or filter the displayed image.

    Parameters
    ----------
    image : array
        Image being viewed.

    Attributes
    ----------
    canvas, fig, ax : Matplotlib canvas, figure, and axes
        Matplotlib canvas, figure, and axes used to display image.
    image : array
        Image being viewed. Setting this value will update the displayed frame.
    original_image : array
        Plugins typically operate on (but don't change) the *original* image.
    plugins : list
        List of attached plugins.

    Examples
    --------
    >>> from skimage import data
    >>> image = data.coins()
    >>> viewer = ImageViewer(image) # doctest: +SKIP
    >>> viewer.show()               # doctest: +SKIP

    )topbottomleftrightTc                    s  t dtdd t  tt|   | tj | 	d t
d| | _| jd| jtjtj  | jd| jtjtj  | jd| jtjtj  |  | j t
 | _| | j t|tru|}|j}|j| j |j | j! t"|\| _#| _$| j#j%| _%| j%&|  | j$j'd	d
 g | _(|| _)|rt*| j$| _+t,| j$| _-| j$j.d | _/| | g | _0t
1| j| _2| j23| j% | 4 }|j5| _6|7 }| j%7 }| 8|9 |: |:   | ;d| j< d S )Nz`viewer` is deprecated and will be removed in 0.20. For alternatives, refer to https://scikit-image.org/docs/stable/user_guide/visualization.htmlr   
stacklevelzImage Viewerz&Filez	Open filezSave to fileQuitF)enabler   motion_notify_event)=r   FutureWarningr   superr   __init__setAttributer
   WA_DeleteOnClosesetWindowTitler   QMenu	file_menu	addAction	open_fileCTRLKey_Osave_to_fileKey_ScloseKey_QmenuBaraddMenuQWidgetmain_widgetsetCentralWidget
isinstancer   filtered_imageimage_changedconnect_update_original_image_started_showr   figaxcanvas	setParent	autoscale_toolsuseblitr   _blit_managerr   _event_managerimages_image_plotpluginsQVBoxLayoutlayout	addWidget	statusBarshowMessagestatus_messagesizeHintresizewidthheightconnect_event_update_status_bar)selfr$   rT   plugin
status_barsb_sizecs_size	__class__r&   r'   r4   \   sZ   








zImageViewer.__init__c                 C   s   | |  | j|j |jrH| j|j }t|}t	 }|
| ||j | || | jd | jd f}||v r?dnd}| j||d | S )zAdd plugin to ImageViewerr+   r,   rb   rc   )	dimension)attachoriginal_image_changedrJ   rK   dock
dock_areasr
   DockWidgetArear   QDockWidget	setWidgetr7   nameaddDockWidget_add_widget_size)rf   rg   locationdock_locationrp   horizrm   r&   r&   r'   __add__   s   


zImageViewer.__add__rb   c           	      C   sb   |  }|  }d }}|dkr| }n|dkr| }| }| }| || ||  d S )Nr   rb   rc   )r`   frameGeometryrb   rc   ra   )	rf   widgetrm   widget_sizeviewer_sizedxdywhr&   r&   r'   rw      s   
zImageViewer._add_widget_sizeNc                 C   s4   |du rt  }|du rdS t|}| | dS )z&Open image file and display in viewer.N)r   open_file_dialogr   imreadrK   )rf   filenamer$   r&   r&   r'   r;      s   
zImageViewer.open_filec                 C   s   |  | dS )zUpdate displayed image.

        This method can be overridden or extended in subclasses and plugins to
        react to image changes.
        N)rK   rf   r$   r&   r&   r'   update_image   s   zImageViewer.update_imagec                 C   s    || _ | | _| j| d S N)original_imagecopyr$   ro   emitr   r&   r&   r'   rK      s   
z"ImageViewer._update_original_imagec                 C   s  |du rt  }|du rdS t| jjdkrt|| j dS t| jjd }t| jjd }|dddddf }t	
|dkrNt	|| jjd   }|ddddt	jf }|ddddddf | |ddddddf d|   }t|| dS )a!  Save current image to file.

        The current behavior is not ideal: It saves the image displayed on
        screen, so all images will be converted to RGB, and the image size is
        not preserved (resizing the viewer window will alter the size of the
        saved image).
        N   r   r   )r   save_file_dialoglenrO   rW   r   imsaver$   r(   r    allr"   	get_alphanewaxis)rf   r   underlayoverlayalpha	compositer&   r&   r'   r>      s     zImageViewer.save_to_filec                 C   s   |    d S r   )r@   rf   eventr&   r&   r'   
closeEvent   s   zImageViewer.closeEventr   c                    sB   |  |d | jD ]}|  q	tt|   |   |   d S )Nr   )moverY   showr3   r   activateWindowraise_)rf   xprk   r&   r'   rM      s   

zImageViewer._showc                 C   s"   |    |r	t  dd | jD S )z|Show ImageViewer and attached plugins.

        This behaves much like `matplotlib.pyplot.show` and `QWidget.show`.
        c                 S   s   g | ]}|  qS r&   )output).0r   r&   r&   r'   
<listcomp>   s    z$ImageViewer.show.<locals>.<listcomp>)rM   r   rY   )rf   main_windowr&   r&   r'   r      s   zImageViewer.showc                 C   s"   | j r
| j  d S | j  d S r   )rT   rU   redrawrP   	draw_idlerf   r&   r&   r'   r     s   zImageViewer.redrawc                 C   s   | j S r   )_imgr   r&   r&   r'   r$     s   zImageViewer.imagec                 C   s   || _ t| j| |jd d \}}| jd| | j|d t|jj	 }|d dk r8|
 dkr8d|d f}| j| | jrEd | j_|   d S )Nr   r   r   )r   r   rX   r   rO   set_xlimset_ylimr   dtypetypeminset_climrT   rU   
backgroundr   )rf   r$   r   r   climr&   r&   r'   r$     s   c                 C   s   | j  | _d S r   )r   r   r$   r   r&   r&   r'   reset_image!  s   zImageViewer.reset_imagec                 C   s   | j ||}|S )z<Connect callback function to matplotlib event and return id.)rP   mpl_connect)rf   r   callbackcidr&   r&   r'   rd   $  s   zImageViewer.connect_eventc                 C   s   | j | dS )z<Disconnect callback by its id (returned by `connect_event`).N)rP   mpl_disconnect)rf   callback_idr&   r&   r'   disconnect_event)  s   zImageViewer.disconnect_eventc                 C   s8   |j r|j  r| | |j|j d S | d d S )N )inaxesget_navigater_   _format_coordxdataydatar   r&   r&   r'   re   -  s   zImageViewer._update_status_barc                 C   s0   | j r
| j|j | j| | j| d S r   )rT   rU   add_artistsartistsrS   appendrV   rn   rf   toolr&   r&   r'   add_tool3  s   zImageViewer.add_toolc                 C   s>   || j vrd S | jr| j|j | j | | j| d S r   )rS   rT   rU   remove_artistsr   removerV   detachr   r&   r&   r'   remove_tool9  s   
zImageViewer.remove_toolc                 C   sH   t |d }t |d }zd| j||f ||f W S  ty#   Y dS w )Ng      ?z%4s @ [%4s, %4s]r   )intr$   
IndexError)rf   r   yr&   r&   r'   r   A  s   zImageViewer._format_coord)T)rb   r   )r   )$__name__
__module____qualname____doc__r
   TopDockWidgetAreaBottomDockWidgetAreaLeftDockWidgetAreaRightDockWidgetArearq   r   r    ndarrayro   r4   r{   rw   r;   r   rK   r>   r   rM   r   r   propertyr$   setterr   rd   r   re   r   r   r   __classcell__r&   r&   rk   r'   r   1   s<    "
=

	




c                       s2   e Zd ZdZd	 fdd	Zdd Zdd Z  ZS )
r   aU  Viewer for displaying image collections.

    Select the displayed frame of the image collection using the slider or
    with the following keyboard shortcuts:

        left/right arrows
            Previous/next image in collection.
        number keys, 0--9
            0% to 90% of collection. For example, "5" goes to the image in the
            middle (i.e. 50%) of the collection.
        home/end keys
            First/last image in collection.

    Parameters
    ----------
    image_collection : list of images
        List of images to be displayed.
    update_on : {'move' | 'release'}
        Control whether image is updated on slide or release of the image
        slider. Using 'on_release' will give smoother behavior when displaying
        large images or when writing a plugin/subclass that requires heavy
        computation.
    r   c                    s   t dtdd || _d| _t| j| _|d }tt| | t	dd| jd d}||d< | j
|d< d	|d
< tdi || _| j| j d S )Nz`CollectionViewer` is deprecated and will be removed in 0.20. For alternatives, refer to https://scikit-image.org/docs/stable/user_guide/visualization.htmlr   r-   r   r   )valuelowhigh	update_onr   r   
value_typeframe)r   )r   r2   image_collectionindexr   
num_imagesr3   r   r4   dictupdate_indexr   sliderr[   r\   )rf   r   r   kwargsfirst_image
slider_kwsrk   r&   r'   r4   d  s   
zCollectionViewer.__init__c                 C   sV   t t|}|| jkrdS t|d}t|| jd }|| _|| j_| | j	|  dS )z:Select image on display using index into image collection.Nr   r   )
r   roundr   maxr   r   r   valr   r   )rf   ru   r   r&   r&   r'   r   }  s   

zCollectionViewer.update_indexc                 C   st   t |tjkr4| }d|  krdk r.n ntd|d  | j }| d| |  d S |  d S |  d S )N0   :   g?r   )	r   r	   	QKeyEventkeyr   r   r   acceptignore)rf   r   r   r   r&   r&   r'   keyPressEvent  s   zCollectionViewer.keyPressEvent)r   )r   r   r   r   r4   r   r   r   r&   r&   rk   r'   r   K  s
    )#r   numpyr    r   r   
util.dtyper   r   exposurer   qtr   r	   r
   r   widgetsr   utilsr   r   r   r   r   utils.canvasr   r   plugins.baser   warningsr   __all__r(   QMainWindowr   r   r&   r&   r&   r'   <module>   s"      