
    e                     x   d Z ddlZddlmZ ddlmZ ddlZddlm	Z	 ddlm
Z ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZmZmZ ddlmZ ddlm Z! 	 ddl"m#Z#m$Z$ ejL                  jN                  Z' G d de      Z( G d dejR                        Z*y# e%$ r ddlm#Z#m$Z$ Y Fw xY w)a  
ImageView.py -  Widget for basic image dispay and analysis
Copyright 2010  Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more information.

Widget used for displaying 2D or 3D data. Features:
  - float or int (including 16-bit int) image display via ImageItem
  - zoom/pan via GraphicsView
  - black/white level controls
  - time slider for 3D data sets
  - ROI plotting
  - Image normalization through a variety of methods
    N)log10)perf_counter   )debug)	functions)getConfigOption)addGradientListToDocstring)	ImageItem)InfiniteLine)LinearRegionItem)ROI)ViewBox)
VTickGroup)QtCoreQtGui	QtWidgets)SignalProxy   )ImageViewTemplate_generic)nanmaxnanminc                       e Zd Zd Zy)PlotROIc                     t        j                  | ddg|       | j                  ddgddg       | j                  ddgddg       y )Nr   )possizer         ?)r   __init__addScaleHandleaddRotateHandle)selfr   s     ?/usr/lib/python3/dist-packages/pyqtgraph/imageview/ImageView.pyr   zPlotROI.__init__+   sF    T!u40QFQF+aVc3Z0    N)__name__
__module____qualname__r    r#   r"   r   r   *   s    1r#   r   c                       e Zd ZdZ ej
                  ee      Z ej
                  e      Z	 	 	 	 	 	 	 	 d)dZ		 	 	 	 	 	 	 	 	 	 d*dZ
d Zd+dZd Zd+dZd Zd	 Zd
 Zd Zd Z fdZ fdZ fdZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d Z!d Z"d Z#d,dZ$d Z%d Z&d  Z'd! Z(d" Z)d# Z*d$ Z+d% Z,d& Z-d' Z. e/       d(        Z0 xZ1S )-	ImageViewa  
    Widget used for display and analysis of image data.
    Implements many features:
    
      * Displays 2D and 3D image data. For 3D data, a z-axis
        slider is displayed allowing the user to select which frame is displayed.
      * Displays histogram of image data with movable region defining the dark/light levels
      * Editable gradient provides a color lookup table
      * Frame slider may also be moved using left/right arrow keys as well as pgup, pgdn, home, and end.
      * Basic analysis features including:

          * ROI and embedded plot for measuring image values across frames
          * Image normalization / background subtraction
    
    Basic Usage::
    
        imv = pg.ImageView()
        imv.show()
        imv.setImage(data)
        
    **Keyboard interaction**
    
      * left/right arrows step forward/backward 1 frame when pressed,
        seek at 20fps when held.
      * up/down arrows seek at 100fps
      * pgup/pgdn seek at 1000fps
      * home/end seek immediately to the first/last frame
      * space begins playing frames. If time values (in seconds) are given
        for each frame, then playback is in realtime.
    c	           	         t        j                  j                  | |g|	  d| _        d| _        d| _        || _        d| _        i | _        d| _	        t        j                         | _        | j                  j                  |        | j                  j                  j                         | _        || _        | j                  j"                  j%                  |       d| _        |t)               | _        n|| _        | j                  j                  j-                  | j*                         | j*                  j/                  d       | j*                  j1                          d| _        | j                  j4                  j7                          |t9        d      | _        n|| _        | j:                  j=                  d       | j*                  j?                  | j:                         | j:                  j7                          |,t9        d      | _         | j@                  jC                  d       n|| _         | j@                  j=                  d       | j*                  j?                  | j@                         | j@                  j7                          g | _"        tG        dd      | _$        tK        d	      d
k(  r| jH                  jC                  d       n| jH                  jC                  d       | jH                  j=                  d       | j                  jL                  j?                  | jH                         | j                  jN                  jQ                  | jS                         dz
  dg       |tU               | _+        n4|| _+        | jY                  |j                  dd|j[                                | j*                  j?                  | jV                         d| _.        | j                  j"                  j_                  | jV                         | j                  j"                  j%                  |       | j                  jN                  }
|
ja                  d      jc                  d       |
je                  d       |
jg                  d       | j                  jL                  ji                  d       tk        ddgd      | _6        | j                  jL                  j?                  | jl                  d       i | _7        tq        jr                         | _:        d| _;        d| _<        d| _=        d| _>        t               | _@        | j                  j=                  d       | j                  jL                  j?                  | j                         | j                  j7                          dD ]#  }t        | |t        | j*                  |             % dD ]-  }t        | |t        | j                  j"                  |             / | jH                  j                  j                  | j                         | j                  j                  j                  j                  | j                         | j:                  j                  j                  | j                         | j                  j                  j                  j                  | j                         | j                  j                  j                  j                  | j                         | j                  j                  j                  j                  | j                         | j                  j                  j                  j                  | j                         | j                  j                  j                  j                  | j                         | j                  j                  j                  j                  | j                         | j                  j                  j                  j                  | j                         | jt                  j                  j                  | j                         t        | j                  j                  | j                  d      | _W        | j@                  j                  j                  | j                         | j                  jL                  j                  | j                  dz          | j*                  j                  | j                         tp        j                  j                  j                  tp        j                  j                  j                  tp        j                  j                  j                  tp        j                  j                  j                  tp        j                  j                  j                  tp        j                  j                  j                  g| _c        | j                          y)a  
        By default, this class creates an :class:`ImageItem <pyqtgraph.ImageItem>` to display image data
        and a :class:`ViewBox <pyqtgraph.ViewBox>` to contain the ImageItem.

        Parameters
        ----------
        parent : QWidget
            Specifies the parent widget to which this ImageView will belong. If None, then the ImageView is created with
            no parent.
        name : str
            The name used to register both the internal ViewBox and the PlotItem used to display ROI data. See the
            *name* argument to :func:`ViewBox.__init__() <pyqtgraph.ViewBox.__init__>`.
        view : ViewBox or PlotItem
            If specified, this will be used as the display area that contains the displayed image. Any
            :class:`ViewBox <pyqtgraph.ViewBox>`, :class:`PlotItem <pyqtgraph.PlotItem>`, or other compatible object is
            acceptable. Note: to display axis ticks inside the ImageView, instantiate it with a PlotItem instance as its
            view::

                pg.ImageView(view=pg.PlotItem())
        imageItem : ImageItem
            If specified, this object will be used to display the image. Must be an instance of ImageItem or other
            compatible object.
        levelMode : str
            See the *levelMode* argument to :func:`HistogramLUTItem.__init__() <pyqtgraph.HistogramLUTItem.__init__>`
        discreteTimeLine : bool
            Whether to snap to xvals / frame numbers when interacting with the timeline position.
        roi : ROI
            If specified, this object is used as ROI for the plot feature. Must be an instance of ROI.
        normRoi : ROI
            If specified, this object is used as ROI for the normalization feature. Must be an instance of ROI.
        NFT
      yr   )movable
backgroundw)r,   P   r1      )   r3   r   r2   r   #   )	autoRange
autoLevels	transformz)QSplitter::handle{background-color: grey}r   leftg?皙?)yrangepen)ignoreBounds)addItem
removeItem)setHistogramRangeautoHistogramRangegetLookupTable	getLevels)slot
threadSafe_ROI)dr   QWidgetr   _imageLevelslevelMinlevelMaxnameimageaxes	imageDispui_templateUi_FormuisetupUigraphicsViewscenediscreteTimeLine	histogramsetLevelModeignoreTimeLiner   viewsetCentralItemsetAspectLockedinvertYmenu	normGrouphider   roi	setZValuer=   normRoisetPen	roiCurvesr   timeLiner   roiPlotsplittersetSizesheightr
   	imageItemsetImager7   currentIndexsetImageItemhandle
setEnabledsetStyleSheetsetHandleWidthhideAxisr   
frameTickskeysPressedr   QTimer	playTimerplayRate_pausedPlayRatefpslastPlayTimer   normRgnsetattrgetattrsigPositionChangedconnecttimeLineChangedroiBtnclicked
roiClickedsigRegionChanged
roiChangedmenuBtnmenuClickednormDivideRadionormRadioChangednormSubtractRadionormOffRadionormROICheck
updateNormnormFrameChecknormTimeRangeChecktimeoutr   	normProxysigRegionChangeFinishedregisterPlotregisterQtKey	Key_RightKey_LeftKey_UpKey_Down
Key_PageUpKey_PageDownnoRepeatKeys)r!   parentrJ   rX   ri   	levelModerT   r_   ra   argssfns               r"   r   zImageView.__init__S   s   V 	""47$7 	
	%%'WW))//1
 0&&y1#<	DIDI++DII6		!!$'			 ;r{DHDH2		$((#?"2;DLLL$"DLr"		$,,'$Q5<(#-MM  !12MM  !34".!!4;;=#3R"89 &[DN&DNMM)//UuXaXkXkXmMn		$..)&&t~~6&&y1 GG	u%	CD	  ($S!H#>dC#')q!- , 	6BD"gdii45	6 ] 	>BD"gdgg&7&7<=	> 	((001E1EF&&t7!!))$//:''(8(89''//0E0EF!!))11$2G2GH$$,,T-B-BC$$,,T__=&&..t?""**224??C&&t||4$LL))

 	,,44T__E$$TYY%78		499% IIMM##IIMM""IIMM  IIMM""IIMM$$IIMM&&
 	r#   c                    t        j                         }t        d      r!j                  d      rj	                         t        t        j                        s/g d}t        fd|D              st        dt        |      z        | _        d| _        |%| j                  j                  j                  |        |        || j                   j"                  dk(  rdnd	\  }}j$                  d
k(  rd||dd| _        nj$                  dk(  r2j(                  d
   dk  rd||d
d| _        nd|dz   |dz   dd| _        nӉj$                  dk(  rd|dz   |dz   dd| _        nt+        dt        j(                        z        t        |t,              r|j/                         | _        njt        |t0              st        |t2              r3i | _        t5        t7        |            D ]  }|| j&                  ||   <    nt+        dt        |      z        dD ]+  }| j&                  j9                  |d      | j&                  |<   - | j&                  }||| _        nV|d   Qt        d      r	 j=                  |d         | _        n*t        j>                  j(                  |d            | _         |        d| _         | jC                  |
       ||r| jE                          | | jF                  |  | j                  jH                  jK                         r| jM                           |        | j&                  d   | j                  jN                  jQ                  | j:                  jS                         | j:                  jU                                | jV                  jY                  | j:                         | jZ                  j]                  d       t7        | j:                        dkD  ra| j:                  jS                         }| j:                  jU                         t_        | j:                  d   | j:                  d   z
        dz  z   }nAt7        | j:                        dk(  r%| j:                  d   dz
  }| j:                  d   dz   }nd}d}| jZ                  | j`                  fD ]  }|jc                  ||g         |        |	6te        jf                         }	| |	jh                  |  | |	jj                  |  | j                   jm                  |	        |        |r| jo                          | jq                           |        y#  t        j>                  j(                  |d            | _        Y xY w)a  
        Set the image to be displayed in the widget.

        Parameters
        ----------
        img : np.ndarray
            The image to be displayed. See :func:`ImageItem.setImage` and *notes* below.
        autoRange : bool
            Whether to scale/pan the view to fit the image.
        autoLevels : bool
            Whether to update the white/black levels to fit the image.
        levels : tuple
            (min, max) white and black level values to use.
        axes : dict
            Dictionary indicating the interpretation for each axis. This is only needed to override the default guess.
            Format is::

                {'t':0, 'x':1, 'y':2, 'c':3};
        xvals : np.ndarray
            1D array of values corresponding to the first axis in a 3D image. For video, this array should contain
            the time of each frame.
        pos
            Change the position of the displayed image
        scale
            Change the scale of the displayed image
        transform
            Set the transform of the displayed image. This option overrides *pos* and *scale*.
        autoHistogramRange : bool
            If True, the histogram y-range is automatically scaled to fit the image data.
        levelMode : str
            If specified, this sets the user interaction mode for setting image levels. Options are 'mono',
            which provides a single level control for all image channels, and 'rgb' or 'rgba', which provide
            individual controls for each channel.

        Notes
        -----
        For backward compatibility, image data is assumed to be in column-major order (column, row).
        However, most image data is stored in row-major order (row, column) and will need to be
        transposed before calling setImage()::
        
            imageview.setImage(imagedata.T)
            
        This requirement can be changed by the ``imageAxisOrder``
        :ref:`global configuration option <apiref_config>`.
        
implements	MetaArray)dtypemaxminndimshaper   c              3   6   K   | ]  }t        |        y wN)hasattr).0attrimgs     r"   	<genexpr>z%ImageView.setImage.<locals>.<genexpr>A  s     ?dwsD)?s   zYImage must be NumPy array or any object that provides compatible attributes/methods:
  %sN	col-major)r   r   )r   r   r   txr-   c      r   r   z*Can not interpret image with dimensions %szfCan not interpret axis specification %s. Must be like {'t': 2, 'x': 0, 'y': 1} or ('t', 'x', 'y', 'c')r   xvals)r@   g{Gz?r   )9r   Profilerr   r   asarray
isinstancenpndarrayall	TypeErrorstrrK   rM   rP   rU   rV   ri   	axisOrderr   rL   r   	ExceptiondictcopylisttuplerangelengettValsr   arangerk   updateImager6   	setLevelsr   	isCheckedr   re   	setXRanger   r   rr   setXValsrd   setValueabsrz   	setBoundsr   
QTransform	translatescalesetTransformr5   r   )r!   r   r5   r6   levelsrL   r   r   r   r7   r@   r   profilerrequiredr   r-   istartstopr   s    `                  r"   rj   zImageView.setImage   s   v >>#3%#..*E++-C#rzz*GH?h?? !'),X!7 8 8 
 GG**95
< NN44C&CAaxx1}"&QQTB	Q99Q<1$&* CDI&'ac!$ GDIQ"#!A#AaCa@	 LPSTWT]T]P^ _``d#		DId#z$'>DI3t9% '%&		$q'"'   E  IL  MQ  IR  S  T  T% 	2A99==D1DIIaL	2yyDJ#Y"sG$A!$49!5DJ  YYsyyc';<

,>?>jOODNNF#77>>##%OO
99S>%GGOO%%djjnn&6

8HIOO$$TZZ0MM""1%4::"

(zz~~'#djjntzz!}.L*MPT*TTTZZA%

1+zz!}s*mmT\\2 +UDM*+ 	
((*I #	##S) 	'##I.
NN
kA!#399T#Y+?!@DJs   3U ,Vc                 F    d | _         | j                  j                          y r   )rK   ri   clearr!   s    r"   r   zImageView.clear  s    
r#   c                    || j                   xs | j                  }|dk(  r| j                  dvr| j                  | _         || _        |dk(  r| j                  j	                          yt               | _        | j                  j                         s1| j                  j                  t        t        d|z                     yy)zBegin automatically stepping frames forward at the given rate (in fps).
        This can also be accessed by pressing the spacebar.Nr   Nr     )rw   rx   rv   ru   r   r   ry   isActiver   r   int)r!   rates     r"   playzImageView.play  s     <''3488D19i7#'==D 19NN!(N~~&&(NN  Sd^!45 )r#   c                 l   | j                   j                         r| j                  d       y | j                  dk(  r^| j                  | j                  }n3| j                         dz
  | j                  d   | j                  d   z
  z  }| j                  |       y | j                  | j                         y )Nr   r   r   )ru   r   r   rv   rw   nframesr   )r!   rx   s     r"   togglePausezImageView.togglePause  s    >>""$IIaL]]a##/**||~)djjntzz!}.LMIIcNIIdmm$r#   c                     | j                   j                  j                  } |j                  |fi | |dk(  r|j	                  d       | j                   j                  j                  d       y)z
        Set the label text of the histogram axis similar to
        :func:`AxisItem.setLabel() <pyqtgraph.AxisItem.setLabel>`
         F   N)rP   rU   axissetLabel	showLabelsetMinimumWidth)r!   textkwargsas       r"   setHistogramLabelzImageView.setHistogramLabel  sW    
 GG""

4"6"2:KK))#.r#   c                     | j                   y| j                  d   &| j                   j                  | j                  d      S y)zi
        Returns
        -------
        int
            The number of frames in the image data.
        r   r   r   )rK   rL   r   r   s    r"   r   zImageView.nframes  s?     ::YYs^'::##DIIcN33r#   c                 <    | j                  | j                         y)zGSet the min/max intensity levels automatically to match the image data.)rgbaN)r   rG   r   s    r"   r6   zImageView.autoLevels  s    D--.r#   c                 P     | j                   j                  j                  |i | y)zSet the min/max (bright and dark) levels.
        
        See :func:`HistogramLUTItem.setLevels <pyqtgraph.HistogramLUTItem.setLevels>`.
        N)rP   rU   r   )r!   r   kwdss      r"   r   zImageView.setLevels  s#    
 	$##T2T2r#   c                 X    | j                          | j                  j                          y)zPAuto scale and pan the view around the image such that the image fills the view.N)getProcessedImagerX   r5   r   s    r"   r5   zImageView.autoRange  s     		r#   c                 v   | j                   | j                  | j                        }|| _         | j                  | j                         | _        t        | j                  D cg c]  }|d   	 c}      | _        t        | j                  D cg c]  }|d   	 c}      | _        | j                   S c c}w c c}w )z`Returns the image data after it has been processed by any normalization options in use.
        r   r   )	rM   	normalizerK   quickMinMaxrG   r   rH   r   rI   )r!   rK   levels      r"   r   zImageView.getProcessedImage  s     >>!NN4::.E"DN $ 0 0 @Dt7H7H Ieq IJDMt7H7H Ieq IJDM~~ !J Is   "B1B6c                     | j                          d| _        | j                  j                  d       t        t
        |           | j                  d       y)zUCloses the widget nicely, making sure to clear the graphics scene and release memory.N)r   rM   ri   	setParentsuperr)   close)r!   	__class__s    r"   r  zImageView.close  s>    

  &i$&tr#   c                    | j                         st        | 	  |       y |j                         t        j
                  j                  j                  k(  r!| j                          |j                          y |j                         t        j
                  j                  j                  k(  r3| j                  d       | j                  d       |j                          y |j                         t        j
                  j                  j                  k(  rD| j                  | j                         dz
         | j                  d       |j                          y |j                         | j                  v rO|j                          |j!                         ry d| j"                  |j                         <   | j%                          y t        | 	  |       y )Nr   r   )hasTimeAxisr  keyPressEventkeyr   r   r   	Key_Spacer   acceptKey_HomesetCurrentIndexr   Key_Endr   r   isAutoRepeatrs   evalKeyStater!   evr  s     r"   r	  zImageView.keyPressEvent  s0   !G!"%668vyy}}...IIKVVX///  #IIaLIIKVVX...  !12IIaLIIKVVX***IIK )*DRVVX&G!"%r#   c                 l   | j                         st        | 	  |       y |j                         t        j
                  j                  j                  t        j
                  j                  j                  t        j
                  j                  j                  fv r|j                          y |j                         | j                  v rN|j                          |j                         ry 	 | j                  |j                         = | j                          y t        | 	  |       y #  i | _        Y ,xY wr   )r  r  keyReleaseEventr
  r   r   r   r  r  r  r  r   r  rs   r  r  s     r"   r  zImageView.keyReleaseEvent  s    !G#B'668		//1G1GI^I^__IIKVVX***IIK &$$RVVX. G#B'	&#% s   ,D( (	D3c                    t        | j                        dk(  rt        | j                  j                               d   }|t        j
                  j                  j                  k(  r5| j                  d       | j                  d       t               dz   | _        y |t        j
                  j                  j                  k(  r5| j                  d       | j                  d       t               dz   | _        y |t        j
                  j                  j                  k(  r| j                  d       y |t        j
                  j                  j                  k(  r| j                  d       y |t        j
                  j                  j                  k(  r| j                  d	       y |t        j
                  j                  j                   k(  r| j                  d
       y y | j                  d       y )Nr   r   r,   g?ir   id   ir   )r   rs   r   keysr   r   r   r   r   
jumpFramesr   ry   r   r   r   r   r   )r!   r
  s     r"   r  zImageView.evalKeyState0  sB   t A%t'',,./2Cfiimm---		""$0NS$8!		...		##$0NS$8!		,,,		$		...		#		000		% 		222		$ 3 IIaLr#   c                    t               }|| j                  z
  }|dk  ry t        | j                  |z        }|dk7  r| xj                  t	        |      | j                  z  z  c_        | j
                  |z   | j                  j                  | j                  d      kD  r| j                  d       | j                  |       y y )Nr   r   )r   ry   r   rv   floatrk   rK   r   rL   r   r  )r!   nowdtns       r"   r   zImageView.timeoutG  s    n4$$$6"#6%(4=="89  "TZZ%5%5diin%EE		!OOA	 r#   c                     t        j                  |d| j                         dz
        }|| _        | j	                          d| _        | j                  j                  | j                  |          d| _        y)z(Set the currently displayed frame index.r   r   TFN)	r   clip_scalarr   rk   r   rW   rd   r   r   )r!   indindexs      r"   r  zImageView.setCurrentIndexS  s^    sAt||~a'78!"tzz%01#r#   c                 `    | j                   d   | j                  | j                  |z          yy)z1Move video frame ahead n frames (may be negative)r   N)rL   r  rk   )r!   r  s     r"   r  zImageView.jumpFrames]  s.    99S>%  !2!2Q!67 &r#   c                     d | _         | j                          | j                          | j                          | j                  j                  |        y r   )rM   r   r6   r   sigProcessingChangedemitr   s    r"   r   zImageView.normRadioChangedb  s=    !!&&t,r#   c                 V   | j                   j                  j                         r| j                  j	                          n| j                  j                          | j                   j                  j                         r| j                  j	                          n| j                  j                          | j                   j                  j                         sSd | _	        | j                          | j                          | j                          | j                  j                  |        y y r   )rP   r   r   rz   showr^   r   ra   r   rM   r   r6   r   r%  r&  r   s    r"   r   zImageView.updateNormi  s    77%%//1LLLL77))+LLLLww##--/!DNOOOO%%**40 0r#   c                 R   | j                   j                  j                  |       | j                  j                  |xr$ | j                   j                  j                                | j                  j                  |xr$ | j                   j                  j                                y r   )rP   r]   
setVisiblera   r   r   rz   r   )r!   bs     r"   normToggledzImageView.normToggled{  sn    $$Q' Fdgg&:&:&D&D&FG Ldgg&@&@&J&J&LMr#   c                 D    d| j                   v xr | j                   d   d uS )Nr   )rL   r   s    r"   r  zImageView.hasTimeAxis  s#    dii>DIIcN$$>>r#   c                    d}| j                   j                  j                         r(d}| j                  j	                          | j                   j
                  j                  dd       | j                   j                  j                  t        | j                         dz        t        | j                         dz        g       | j                   j                  j                  d      j                  d       | j                          | j                  D ]  }|j	                           | j                   j
                  j                  d       n| j                  j!                          | j                   j
                  j                  dd       | j                  D ]  }|j!                           | j                   j
                  j#                  d       | j%                         r&d}| j&                  j)                         }| j&                  j+                         }| j                   j
                  j-                  ||d       | j.                  j	                          | j.                  j1                  ||g       | j                   j                  j                         s| j                   j                  j                  | j                         d	z
  d	g       | j                   j                  j                  d      j                  d       n| j.                  j!                          | j                   j
                  j3                  |       y )
NFTg333333?r9   r   r8   g{Gz?)paddingr4   )rP   r   r   r_   r(  re   setMouseEnabledrf   rg   r   rh   rm   rn   r   rc   showAxisr^   rq   r  r   r   r   r   rd   r   r*  )r!   showRoiPlotr   mnmxs        r"   r   zImageView.roiClicked  s2   77>>##%KHHMMOGGOO++D$7GG%%s4;;=+<'=s4;;=QTCT?U&VWGG##A&11$7OO^^ GGOO$$V,HHMMOGGOO++E59^^ GGOO$$V,K!B!BGGOO%%b"d%;MM MM##RH-77>>++-  ))4;;=+;R*@A  ''*55e<MM "";/r#   c                 ,   | j                   y | j                         }| j                  j                  dk(  }|r| j                  d   | j                  d   f}n| j                  d   | j                  d   f}| j
                  j                  |j                  t        j                        | j                  |d      \  }}|y | j                  d   m|j                  | j                  d         }|r|d d d d df   |d d dd	df   z
  }n|d d dd d f   |d d ddd	f   z
  }|d
z  j                  d      dz  }n|j                  |      }| j                  }|j                  d	k(  r||dfg}|j                  d
k(  rV|j                  d	   d	k(  rd}nd}g }t        |j                  d	         D ]"  }	|d d |	f   }
|j!                  ||
||	   f       $ t#              t#        | j$                        k  r[| j$                  j'                         }|j)                         j+                  |       t#        |      t#        | j$                        k  r[t#        |      t#        | j$                        kD  r_| j$                  j!                  | j,                  j.                  j1                                t#        |      t#        | j$                        kD  r_t        t#        |            D ],  }	||	   \  }}}| j$                  |	   j3                  |||       . y )Nr   r   r-   T)r   rL   returnMappedCoordsr   r   r   r   r   r   r0   rgbw)r;   )rK   r   ri   r   rL   r_   getArrayRegionrX   r   r   meansumr   r   r   r   appendr   rc   poprS   r>   rP   re   plotsetData)r!   rK   colmajrL   datacoordsr   plotscolorsr   dr   r   r-   ps                  r"   r   zImageView.roiChanged  s   ::&&(
 ))[8IIcNDIIcN3DIIcNDIIcN3Dxx..JJrzz"T# / %f < 99S>!99$))C.91D 1a6!QqS!)+<<1a6!Q!)+<<QYOOO+s2E 99$9'DJJE 99>T3'(E99>zz!}!E4::a=) 41IeQq	234
 %j3t~~..""$AGGI  # %j3t~~.. %j3t~~..NN!!$''//"6"6"89 %j3t~~..s5z" 	3AAhGAq!NN1%%a%2	3r#   c                    |j                   dkD  rft        j                  |j                        }t	        d      g|j
                  z  }t	        ddd      ||<   |t        |         }|j                   dkD  rf| j                  d   }|;|j                   dk(  rdgS t        t        |            t        t        |            fgS |j                   dk(  rdg|j                  d   z  S t        |j                  d         D cg c]L  }t        t        |j                  ||                  t        t        |j                  ||                  fN c}S c c}w )	z
        Estimate the min/max values of *data* by subsampling.
        Returns [(min, max), ...] with one item per channel
        g    .ANr   r   r   )r   r   r   r7  )r   r   argmaxr   slicer   r   rL   r  r   r   r   take)r!   rA  axslcaxr   s         r"   r   zImageView.quickMinMax  s/   
 ii#o4::&B+*B4q)BrFb	?D	 ii#o iin;yyA~x6$<(%t*=>??yyA~x$**R.00EJ4::VX>EZ\@A 6$))AC)"89:6$))AC)"89:< \ \ \s   >AEc                    | j                   j                  j                         r|S | j                   j                  j                         }|j	                  t
        j                        j                         }|r|j                  t
        j                        }| j                   j                  j                         r|j                  dk(  r| j                  | j                  j                  d         \  }}| j                  | j                  j                  d         \  }}|||dz    j                  d      }d|j                   z   |_        |r||z  }n||z  }| j                   j"                  j                         rR|j                  dk(  rC|j                  d      j                  d      }|j                   dz   |_        |r||z  }n||z  }| j                   j$                  j                         r|j                  dk(  r{| j&                  j)                  || j*                  d      j                  d      j                  d      }|ddt
        j,                  t
        j,                  f   }|r||z  }|S ||z  }|S )	z
        Process *image* using the normalization options configured in the
        control panel.
        
        This can be repurposed to process any data through the same filter.
        r   r   r   r7  )r   )r   r   )r   r   N)rP   r   r   r   rX   r   r   r   astypefloat32r   r   	timeIndexrz   linesr:  r   r   r   ra   r9  ri   newaxis)	r!   rK   divnormsindr   eindendr  s	            r"   r   zImageView.normalize  s    77))+Lgg%%//1zz"**%**,
 ;;rzz*D77%%//1ejjAo NN4<<+=+=a+@AMT5..););A)>?KT3d46"''Q'/AQWWnAG		77!!++-%**/


"''Q'/Agg&AG		77))+

a++D$..&INNTUNV[[ab[cA!BJJrzz)*A	  	r#   c                 H   | j                   s| j                  d       | j                  | j                        \  }}|| j                  k7  r|| _        | j                          | j                  rt        j                  | j                  j                  | j                        5  | j                  )| j                  j                  | j                  |          n| j                  j                  |       d d d        | j                  j                  ||       y # 1 sw Y   &xY wr   )rW   r   rQ  rd   rk   r   rT   r   SignalBlockr}   r   r   setPossigTimeChangedr&  )r!   r!  times      r"   r   zImageView.timeLineChanged*  s    ""IIaLnnT]]3d$### #D   @ @$BVBVW .::)MM((C9MM((-	. 	  d+. .s   "ADD!c                 8   | j                   y | j                         }|r:| j                  j                  j	                  | j
                  | j                         | j                  j                  dk(  rg d}ng d}|D cg c]!  }| j                  |   | j                  |   # }}|j                  |      }| j                  d   3| j                  j                  j                          || j                     }| j                  j                  |       y c c}w )Nr   r   )r   r-   r   r   r   )rK   r   rP   rU   r?   rH   rI   ri   r   rL   	transposere   r(  rk   r   )r!   r@   rK   axorderrK  s        r"   r   zImageView.updateImage;  s    ::&&(GG//t}}M >>##{2*G*G+2PRdiim6O499R=PP( 99S>%GGOO  "$++,E""5) Qs    DDc                    | j                         sy|j                         }| j                  }|t        |      }||fS t	        |      dk  ryt        j                  ||k        }t	        |      dk  rd|fS |d   }||fS )z
        Returns
        -------
        int
            The index of the frame closest to the timeline slider.
        float
            The time value of the slider.
        )r   g        r   r   r   )r   r   )r  valuer   r   r   r   argwhere)r!   sliderr   xvr!  indss         r"   rQ  zImageView.timeIndexS  s     !LLNZZ:a&C Av 2w{;;rQw'D4y1}!tu+CAvr#   c                     | j                   S )zLReturn the ViewBox (or other compatible object) which displays the ImageItem)rX   r   s    r"   getViewzImageView.getViewm  s    yyr#   c                     | j                   S )z(Return the ImageItem for this ImageView.)ri   r   s    r"   getImageItemzImageView.getImageItemq  s    ~~r#   c                 .    | j                   j                  S )z,Return the ROI PlotWidget for this ImageView)rP   re   r   s    r"   
getRoiPlotzImageView.getRoiPlotu  s    wwr#   c                 .    | j                   j                  S )z0Return the HistogramLUTWidget for this ImageView)rP   rU   r   s    r"   getHistogramWidgetzImageView.getHistogramWidgety  s    ww   r#   c                    | j                         }| j                         rt        j                  j	                  |      \  }}dt        t        |j                  d         dz         z  }t        |j                  d         D ]C  }| j                  j                  ||   d       | j                  j                  ||||fz         E | j                          y| j                  j                  |       y)a$  
        Export data from the ImageView to a file, or to a stack of files if
        the data is 3D. Saving an image stack will result in index numbers
        being added to the file name. Images are saved as they would appear
        onscreen, with levels and lookup table applied.
        z%%s%%0%dd%%sr   r   F)r6   N)r   r  ospathsplitextr   r   r   r   ri   rj   saver   )r!   fileNamer   baseextfmtr   s          r"   exportzImageView.export}  s     $$&((2ID# 3uSYYq\':1'<#==C399Q<( :''A5'A##C4C.$89: NN)r#   c                 n    t         j                  j                         \  }}|sy | j                  |       y r   )r   QFileDialoggetSaveFileNamerx  )r!   rt  _s      r"   exportClickedzImageView.exportClicked  s,    ++;;=!Hr#   c                 x   t        j                         | _        t        j                  t        dd      | j                        | _        | j                  j                  d       | j                  j                  j                  | j                         | j                  j                  | j                         t        j                  t        dd      | j                        | _        | j                  j                  j                  | j                         | j                  j                  | j                         y )Nr)   NormalizationTExport)r   QMenur\   r   QActionr   
normActionsetCheckabletoggledr~   r,  	addActionexportAction	triggeredr}  r   s    r"   	buildMenuzImageView.buildMenu  s    OO%	--	+(OQUQZQZ[$$T*''(8(89		DOO,!MM)K*JDIIV##++D,>,>?		D--.r#   c                     | j                   | j                          | j                   j                  t        j                  j                                y r   )r\   r  popupr   QCursorr   r   s    r"   r   zImageView.menuClicked  s3    99NN		))+,r#   c                 b    | j                   j                  j                  j                  |       y)zSet the color map. 

        Parameters
        ----------
        colormap : ColorMap
            The ColorMap to use for coloring images.
        N)rP   rU   gradientsetColorMap)r!   colormaps     r"   r  zImageView.setColorMap  s"     	""..x8r#   c                 b    | j                   j                  j                  j                  |       y)zwSet one of the gradients defined in :class:`GradientEditorItem`.
        Currently available gradients are:   
        N)rP   rU   r  
loadPreset)r!   rJ   s     r"   setPredefinedGradientzImageView.setPredefinedGradient  s"    
 	""--d3r#   )Nr)   NNmonoFNN)
TTNNNNNNTNr   )T)2r$   r%   r&   __doc__r   Signalobjectr\  r%  r   rj   r   r   r   r   r   r6   r   r5   r   r  r	  r  r  r   r  r  r   r   r,  r  r   r   r   r   r   r   rQ  rh  rj  rl  rn  rx  r}  r  r   r  r	   r  __classcell__)r  s   @r"   r)   r)   1   sE   < #V]]662N(6==0 "j^ #fP6"
%	//3

&2(&.
$8
-1$N
? 0D<3|\,/b,"*04!*$/-
9  !4 "4r#   r)   )+r  rp  mathr   r]  r   numpyr   r   r   r   r   r    graphicsItems.GradientEditorItemr	   graphicsItems.ImageItemr
   graphicsItems.InfiniteLiner   graphicsItems.LinearRegionItemr   graphicsItems.ROIr   graphicsItems.ViewBoxr   graphicsItems.VTickGroupr   r   r   r   r   r   r   rN   
bottleneckr   r   ImportErrorQCoreApplicationr   r   rF   r)   r'   r#   r"   <module>r     s    
       I / 5 = # + 1 ) ) % 6%) ##--	1c 1B4	!! B4  %$$%s   *B) )B98B9