1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
|
"""
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
"""
import os
from math import log10
from time import perf_counter
import numpy as np
from .. import debug as debug
from .. import functions as fn
from .. import getConfigOption
from ..graphicsItems.GradientEditorItem import addGradientListToDocstring
from ..graphicsItems.ImageItem import ImageItem
from ..graphicsItems.InfiniteLine import InfiniteLine
from ..graphicsItems.LinearRegionItem import LinearRegionItem
from ..graphicsItems.ROI import ROI
from ..graphicsItems.ViewBox import ViewBox
from ..graphicsItems.VTickGroup import VTickGroup
from ..Qt import QtCore, QtGui, QtWidgets
from ..SignalProxy import SignalProxy
from . import ImageViewTemplate_generic as ui_template
try:
from bottleneck import nanmax, nanmin
except ImportError:
from numpy import nanmax, nanmin
translate = QtCore.QCoreApplication.translate
class PlotROI(ROI):
def __init__(self, size):
ROI.__init__(self, pos=[0,0], size=size) #, scaleSnap=True, translateSnap=True)
self.addScaleHandle([1, 1], [0, 0])
self.addRotateHandle([0, 0], [0.5, 0.5])
class ImageView(QtWidgets.QWidget):
"""
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.
"""
sigTimeChanged = QtCore.Signal(object, object)
sigProcessingChanged = QtCore.Signal(object)
def __init__(
self,
parent=None,
name="ImageView",
view=None,
imageItem=None,
levelMode='mono',
discreteTimeLine=False,
roi=None,
normRoi=None,
*args,
):
"""
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.
"""
QtWidgets.QWidget.__init__(self, parent, *args)
self._imageLevels = None # [(min, max), ...] per channel image metrics
self.levelMin = None # min / max levels across all channels
self.levelMax = None
self.name = name
self.image = None
self.axes = {}
self.imageDisp = None
self.ui = ui_template.Ui_Form()
self.ui.setupUi(self)
self.scene = self.ui.graphicsView.scene()
self.discreteTimeLine = discreteTimeLine
self.ui.histogram.setLevelMode(levelMode)
self.ignoreTimeLine = False
if view is None:
self.view = ViewBox()
else:
self.view = view
self.ui.graphicsView.setCentralItem(self.view)
self.view.setAspectLocked(True)
self.view.invertY()
self.menu = None
self.ui.normGroup.hide()
if roi is None:
self.roi = PlotROI(10)
else:
self.roi = roi
self.roi.setZValue(20)
self.view.addItem(self.roi)
self.roi.hide()
if normRoi is None:
self.normRoi = PlotROI(10)
self.normRoi.setPen('y')
else:
self.normRoi = normRoi
self.normRoi.setZValue(20)
self.view.addItem(self.normRoi)
self.normRoi.hide()
self.roiCurves = []
self.timeLine = InfiniteLine(0, movable=True)
if getConfigOption('background')=='w':
self.timeLine.setPen((20, 80,80, 200))
else:
self.timeLine.setPen((255, 255, 0, 200))
self.timeLine.setZValue(1)
self.ui.roiPlot.addItem(self.timeLine)
self.ui.splitter.setSizes([self.height()-35, 35])
# init imageItem and histogram
if imageItem is None:
self.imageItem = ImageItem()
else:
self.imageItem = imageItem
self.setImage(imageItem.image, autoRange=False, autoLevels=False, transform=imageItem.transform())
self.view.addItem(self.imageItem)
self.currentIndex = 0
self.ui.histogram.setImageItem(self.imageItem)
self.ui.histogram.setLevelMode(levelMode)
# make splitter an unchangeable small grey line:
s = self.ui.splitter
s.handle(1).setEnabled(False)
s.setStyleSheet("QSplitter::handle{background-color: grey}")
s.setHandleWidth(2)
self.ui.roiPlot.hideAxis('left')
self.frameTicks = VTickGroup(yrange=[0.8, 1], pen=0.4)
self.ui.roiPlot.addItem(self.frameTicks, ignoreBounds=True)
self.keysPressed = {}
self.playTimer = QtCore.QTimer()
self.playRate = 0
self._pausedPlayRate = None
self.fps = 1 # 1 Hz by default
self.lastPlayTime = 0
self.normRgn = LinearRegionItem()
self.normRgn.setZValue(0)
self.ui.roiPlot.addItem(self.normRgn)
self.normRgn.hide()
## wrap functions from view box
for fn in ['addItem', 'removeItem']:
setattr(self, fn, getattr(self.view, fn))
## wrap functions from histogram
for fn in ['setHistogramRange', 'autoHistogramRange', 'getLookupTable', 'getLevels']:
setattr(self, fn, getattr(self.ui.histogram, fn))
self.timeLine.sigPositionChanged.connect(self.timeLineChanged)
self.ui.roiBtn.clicked.connect(self.roiClicked)
self.roi.sigRegionChanged.connect(self.roiChanged)
#self.ui.normBtn.toggled.connect(self.normToggled)
self.ui.menuBtn.clicked.connect(self.menuClicked)
self.ui.normDivideRadio.clicked.connect(self.normRadioChanged)
self.ui.normSubtractRadio.clicked.connect(self.normRadioChanged)
self.ui.normOffRadio.clicked.connect(self.normRadioChanged)
self.ui.normROICheck.clicked.connect(self.updateNorm)
self.ui.normFrameCheck.clicked.connect(self.updateNorm)
self.ui.normTimeRangeCheck.clicked.connect(self.updateNorm)
self.playTimer.timeout.connect(self.timeout)
self.normProxy = SignalProxy(
self.normRgn.sigRegionChanged,
slot=self.updateNorm,
threadSafe=False,
)
self.normRoi.sigRegionChangeFinished.connect(self.updateNorm)
self.ui.roiPlot.registerPlot(self.name + '_ROI')
self.view.register(self.name)
self.noRepeatKeys = [
QtCore.Qt.Key.Key_Right,
QtCore.Qt.Key.Key_Left,
QtCore.Qt.Key.Key_Up,
QtCore.Qt.Key.Key_Down,
QtCore.Qt.Key.Key_PageUp,
QtCore.Qt.Key.Key_PageDown,
]
self.roiClicked() ## initialize roi plot to correct shape / visibility
def setImage(
self,
img,
autoRange=True,
autoLevels=True,
levels=None,
axes=None,
xvals=None,
pos=None,
scale=None,
transform=None,
autoHistogramRange=True,
levelMode=None,
):
"""
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>`.
"""
profiler = debug.Profiler()
if hasattr(img, 'implements') and img.implements('MetaArray'):
img = img.asarray()
if not isinstance(img, np.ndarray):
required = ['dtype', 'max', 'min', 'ndim', 'shape', 'size']
if not all(hasattr(img, attr) for attr in required):
raise TypeError("Image must be NumPy array or any object "
"that provides compatible attributes/methods:\n"
" %s" % str(required))
self.image = img
self.imageDisp = None
if levelMode is not None:
self.ui.histogram.setLevelMode(levelMode)
profiler()
if axes is None:
x,y = (0, 1) if self.imageItem.axisOrder == 'col-major' else (1, 0)
if img.ndim == 2:
self.axes = {'t': None, 'x': x, 'y': y, 'c': None}
elif img.ndim == 3:
# Ambiguous case; make a guess
if img.shape[2] <= 4:
self.axes = {'t': None, 'x': x, 'y': y, 'c': 2}
else:
self.axes = {'t': 0, 'x': x+1, 'y': y+1, 'c': None}
elif img.ndim == 4:
# Even more ambiguous; just assume the default
self.axes = {'t': 0, 'x': x+1, 'y': y+1, 'c': 3}
else:
raise Exception("Can not interpret image with dimensions %s" % (str(img.shape)))
elif isinstance(axes, dict):
self.axes = axes.copy()
elif isinstance(axes, list) or isinstance(axes, tuple):
self.axes = {}
for i in range(len(axes)):
self.axes[axes[i]] = i
else:
raise Exception("Can not interpret axis specification %s. Must be like {'t': 2, 'x': 0, 'y': 1} or ('t', 'x', 'y', 'c')" % (str(axes)))
for x in ['t', 'x', 'y', 'c']:
self.axes[x] = self.axes.get(x, None)
axes = self.axes
if xvals is not None:
self.tVals = xvals
elif axes['t'] is not None:
if hasattr(img, 'xvals'):
try:
self.tVals = img.xvals(axes['t'])
except:
self.tVals = np.arange(img.shape[axes['t']])
else:
self.tVals = np.arange(img.shape[axes['t']])
profiler()
self.currentIndex = 0
self.updateImage(autoHistogramRange=autoHistogramRange)
if levels is None and autoLevels:
self.autoLevels()
if levels is not None: ## this does nothing since getProcessedImage sets these values again.
self.setLevels(*levels)
if self.ui.roiBtn.isChecked():
self.roiChanged()
profiler()
if self.axes['t'] is not None:
self.ui.roiPlot.setXRange(self.tVals.min(), self.tVals.max())
self.frameTicks.setXVals(self.tVals)
self.timeLine.setValue(0)
if len(self.tVals) > 1:
start = self.tVals.min()
stop = self.tVals.max() + abs(self.tVals[-1] - self.tVals[0]) * 0.02
elif len(self.tVals) == 1:
start = self.tVals[0] - 0.5
stop = self.tVals[0] + 0.5
else:
start = 0
stop = 1
for s in [self.timeLine, self.normRgn]:
s.setBounds([start, stop])
profiler()
if transform is None:
transform = QtGui.QTransform()
# note that the order of transform is
# scale followed by translate
if pos is not None:
transform.translate(*pos)
if scale is not None:
transform.scale(*scale)
self.imageItem.setTransform(transform)
profiler()
if autoRange:
self.autoRange()
self.roiClicked()
profiler()
def clear(self):
self.image = None
self.imageItem.clear()
def play(self, rate=None):
"""Begin automatically stepping frames forward at the given rate (in fps).
This can also be accessed by pressing the spacebar."""
if rate is None:
rate = self._pausedPlayRate or self.fps
if rate == 0 and self.playRate not in (None, 0):
self._pausedPlayRate = self.playRate
self.playRate = rate
if rate == 0:
self.playTimer.stop()
return
self.lastPlayTime = perf_counter()
if not self.playTimer.isActive():
self.playTimer.start(abs(int(1000/rate)))
def togglePause(self):
if self.playTimer.isActive():
self.play(0)
elif self.playRate == 0:
if self._pausedPlayRate is not None:
fps = self._pausedPlayRate
else:
fps = (self.nframes() - 1) / (self.tVals[-1] - self.tVals[0])
self.play(fps)
else:
self.play(self.playRate)
def setHistogramLabel(self, text=None, **kwargs):
"""
Set the label text of the histogram axis similar to
:func:`AxisItem.setLabel() <pyqtgraph.AxisItem.setLabel>`
"""
a = self.ui.histogram.axis
a.setLabel(text, **kwargs)
if text == '':
a.showLabel(False)
self.ui.histogram.setMinimumWidth(135)
def nframes(self):
"""
Returns
-------
int
The number of frames in the image data.
"""
if self.image is None:
return 0
elif self.axes['t'] is not None:
return self.image.shape[self.axes['t']]
return 1
def autoLevels(self):
"""Set the min/max intensity levels automatically to match the image data."""
self.setLevels(rgba=self._imageLevels)
def setLevels(self, *args, **kwds):
"""Set the min/max (bright and dark) levels.
See :func:`HistogramLUTItem.setLevels <pyqtgraph.HistogramLUTItem.setLevels>`.
"""
self.ui.histogram.setLevels(*args, **kwds)
def autoRange(self):
"""Auto scale and pan the view around the image such that the image fills the view."""
self.getProcessedImage()
self.view.autoRange()
def getProcessedImage(self):
"""Returns the image data after it has been processed by any normalization options in use.
"""
if self.imageDisp is None:
image = self.normalize(self.image)
self.imageDisp = image
self._imageLevels = self.quickMinMax(self.imageDisp)
self.levelMin = min([level[0] for level in self._imageLevels])
self.levelMax = max([level[1] for level in self._imageLevels])
return self.imageDisp
def close(self):
"""Closes the widget nicely, making sure to clear the graphics scene and release memory."""
self.clear()
self.imageDisp = None
self.imageItem.setParent(None)
super(ImageView, self).close()
self.setParent(None)
def keyPressEvent(self, ev):
if not self.hasTimeAxis():
super().keyPressEvent(ev)
return
if ev.key() == QtCore.Qt.Key.Key_Space:
self.togglePause()
ev.accept()
elif ev.key() == QtCore.Qt.Key.Key_Home:
self.setCurrentIndex(0)
self.play(0)
ev.accept()
elif ev.key() == QtCore.Qt.Key.Key_End:
self.setCurrentIndex(self.nframes()-1)
self.play(0)
ev.accept()
elif ev.key() in self.noRepeatKeys:
ev.accept()
if ev.isAutoRepeat():
return
self.keysPressed[ev.key()] = 1
self.evalKeyState()
else:
super().keyPressEvent(ev)
def keyReleaseEvent(self, ev):
if not self.hasTimeAxis():
super().keyReleaseEvent(ev)
return
if ev.key() in [QtCore.Qt.Key.Key_Space, QtCore.Qt.Key.Key_Home, QtCore.Qt.Key.Key_End]:
ev.accept()
elif ev.key() in self.noRepeatKeys:
ev.accept()
if ev.isAutoRepeat():
return
try:
del self.keysPressed[ev.key()]
except:
self.keysPressed = {}
self.evalKeyState()
else:
super().keyReleaseEvent(ev)
def evalKeyState(self):
if len(self.keysPressed) == 1:
key = list(self.keysPressed.keys())[0]
if key == QtCore.Qt.Key.Key_Right:
self.play(20)
self.jumpFrames(1)
# effectively pause playback for 0.2 s
self.lastPlayTime = perf_counter() + 0.2
elif key == QtCore.Qt.Key.Key_Left:
self.play(-20)
self.jumpFrames(-1)
self.lastPlayTime = perf_counter() + 0.2
elif key == QtCore.Qt.Key.Key_Up:
self.play(-100)
elif key == QtCore.Qt.Key.Key_Down:
self.play(100)
elif key == QtCore.Qt.Key.Key_PageUp:
self.play(-1000)
elif key == QtCore.Qt.Key.Key_PageDown:
self.play(1000)
else:
self.play(0)
def timeout(self):
now = perf_counter()
dt = now - self.lastPlayTime
if dt < 0:
return
n = int(self.playRate * dt)
if n != 0:
self.lastPlayTime += (float(n)/self.playRate)
if self.currentIndex+n > self.image.shape[self.axes['t']]:
self.play(0)
self.jumpFrames(n)
def setCurrentIndex(self, ind):
"""Set the currently displayed frame index."""
index = fn.clip_scalar(ind, 0, self.nframes()-1)
self.currentIndex = index
self.updateImage()
self.ignoreTimeLine = True
# Implicitly call timeLineChanged
self.timeLine.setValue(self.tVals[index])
self.ignoreTimeLine = False
def jumpFrames(self, n):
"""Move video frame ahead n frames (may be negative)"""
if self.axes['t'] is not None:
self.setCurrentIndex(self.currentIndex + n)
def normRadioChanged(self):
self.imageDisp = None
self.updateImage()
self.autoLevels()
self.roiChanged()
self.sigProcessingChanged.emit(self)
def updateNorm(self):
if self.ui.normTimeRangeCheck.isChecked():
self.normRgn.show()
else:
self.normRgn.hide()
if self.ui.normROICheck.isChecked():
self.normRoi.show()
else:
self.normRoi.hide()
if not self.ui.normOffRadio.isChecked():
self.imageDisp = None
self.updateImage()
self.autoLevels()
self.roiChanged()
self.sigProcessingChanged.emit(self)
def normToggled(self, b):
self.ui.normGroup.setVisible(b)
self.normRoi.setVisible(b and self.ui.normROICheck.isChecked())
self.normRgn.setVisible(b and self.ui.normTimeRangeCheck.isChecked())
def hasTimeAxis(self):
return 't' in self.axes and self.axes['t'] is not None
def roiClicked(self):
showRoiPlot = False
if self.ui.roiBtn.isChecked():
showRoiPlot = True
self.roi.show()
self.ui.roiPlot.setMouseEnabled(True, True)
self.ui.splitter.setSizes([int(self.height()*0.6), int(self.height()*0.4)])
self.ui.splitter.handle(1).setEnabled(True)
self.roiChanged()
for c in self.roiCurves:
c.show()
self.ui.roiPlot.showAxis('left')
else:
self.roi.hide()
self.ui.roiPlot.setMouseEnabled(False, False)
for c in self.roiCurves:
c.hide()
self.ui.roiPlot.hideAxis('left')
if self.hasTimeAxis():
showRoiPlot = True
mn = self.tVals.min()
mx = self.tVals.max()
self.ui.roiPlot.setXRange(mn, mx, padding=0.01)
self.timeLine.show()
self.timeLine.setBounds([mn, mx])
if not self.ui.roiBtn.isChecked():
self.ui.splitter.setSizes([self.height()-35, 35])
self.ui.splitter.handle(1).setEnabled(False)
else:
self.timeLine.hide()
self.ui.roiPlot.setVisible(showRoiPlot)
def roiChanged(self):
# Extract image data from ROI
if self.image is None:
return
image = self.getProcessedImage()
# getArrayRegion axes should be (x, y) of data array for col-major,
# (y, x) for row-major
# can't just transpose input because ROI is axisOrder aware
colmaj = self.imageItem.axisOrder == 'col-major'
if colmaj:
axes = (self.axes['x'], self.axes['y'])
else:
axes = (self.axes['y'], self.axes['x'])
data, coords = self.roi.getArrayRegion(
image.view(np.ndarray), img=self.imageItem, axes=axes,
returnMappedCoords=True)
if data is None:
return
# Convert extracted data into 1D plot data
if self.axes['t'] is None:
# Average across y-axis of ROI
data = data.mean(axis=self.axes['y'])
# get coordinates along x axis of ROI mapped to range (0, roiwidth)
if colmaj:
coords = coords[:, :, 0] - coords[:, 0:1, 0]
else:
coords = coords[:, 0, :] - coords[:, 0, 0:1]
xvals = (coords**2).sum(axis=0) ** 0.5
else:
# Average data within entire ROI for each frame
data = data.mean(axis=axes)
xvals = self.tVals
# Handle multi-channel data
if data.ndim == 1:
plots = [(xvals, data, 'w')]
if data.ndim == 2:
if data.shape[1] == 1:
colors = 'w'
else:
colors = 'rgbw'
plots = []
for i in range(data.shape[1]):
d = data[:,i]
plots.append((xvals, d, colors[i]))
# Update plot line(s)
while len(plots) < len(self.roiCurves):
c = self.roiCurves.pop()
c.scene().removeItem(c)
while len(plots) > len(self.roiCurves):
self.roiCurves.append(self.ui.roiPlot.plot())
for i in range(len(plots)):
x, y, p = plots[i]
self.roiCurves[i].setData(x, y, pen=p)
def quickMinMax(self, data):
"""
Estimate the min/max values of *data* by subsampling.
Returns [(min, max), ...] with one item per channel
"""
while data.size > 1e6:
ax = np.argmax(data.shape)
sl = [slice(None)] * data.ndim
sl[ax] = slice(None, None, 2)
data = data[tuple(sl)]
cax = self.axes['c']
if cax is None:
if data.size == 0:
return [(0, 0)]
return [(float(nanmin(data)), float(nanmax(data)))]
else:
if data.size == 0:
return [(0, 0)] * data.shape[-1]
return [(float(nanmin(data.take(i, axis=cax))),
float(nanmax(data.take(i, axis=cax)))) for i in range(data.shape[-1])]
def normalize(self, image):
"""
Process *image* using the normalization options configured in the
control panel.
This can be repurposed to process any data through the same filter.
"""
if self.ui.normOffRadio.isChecked():
return image
div = self.ui.normDivideRadio.isChecked()
norm = image.view(np.ndarray).copy()
#if div:
#norm = ones(image.shape)
#else:
#norm = zeros(image.shape)
if div:
norm = norm.astype(np.float32)
if self.ui.normTimeRangeCheck.isChecked() and image.ndim == 3:
(sind, start) = self.timeIndex(self.normRgn.lines[0])
(eind, end) = self.timeIndex(self.normRgn.lines[1])
#print start, end, sind, eind
n = image[sind:eind+1].mean(axis=0)
n.shape = (1,) + n.shape
if div:
norm /= n
else:
norm -= n
if self.ui.normFrameCheck.isChecked() and image.ndim == 3:
n = image.mean(axis=1).mean(axis=1)
n.shape = n.shape + (1, 1)
if div:
norm /= n
else:
norm -= n
if self.ui.normROICheck.isChecked() and image.ndim == 3:
n = self.normRoi.getArrayRegion(norm, self.imageItem, (1, 2)).mean(axis=1).mean(axis=1)
n = n[:,np.newaxis,np.newaxis]
#print start, end, sind, eind
if div:
norm /= n
else:
norm -= n
return norm
def timeLineChanged(self):
if not self.ignoreTimeLine:
self.play(0)
(ind, time) = self.timeIndex(self.timeLine)
if ind != self.currentIndex:
self.currentIndex = ind
self.updateImage()
if self.discreteTimeLine:
with fn.SignalBlock(self.timeLine.sigPositionChanged, self.timeLineChanged):
if self.tVals is not None:
self.timeLine.setPos(self.tVals[ind])
else:
self.timeLine.setPos(ind)
self.sigTimeChanged.emit(ind, time)
def updateImage(self, autoHistogramRange=True):
## Redraw image on screen
if self.image is None:
return
image = self.getProcessedImage()
if autoHistogramRange:
self.ui.histogram.setHistogramRange(self.levelMin, self.levelMax)
# Transpose image into order expected by ImageItem
if self.imageItem.axisOrder == 'col-major':
axorder = ['t', 'x', 'y', 'c']
else:
axorder = ['t', 'y', 'x', 'c']
axorder = [self.axes[ax] for ax in axorder if self.axes[ax] is not None]
image = image.transpose(axorder)
# Select time index
if self.axes['t'] is not None:
self.ui.roiPlot.show()
image = image[self.currentIndex]
self.imageItem.updateImage(image)
def timeIndex(self, slider):
"""
Returns
-------
int
The index of the frame closest to the timeline slider.
float
The time value of the slider.
"""
if not self.hasTimeAxis():
return 0, 0.0
t = slider.value()
xv = self.tVals
if xv is None:
ind = int(t)
else:
if len(xv) < 2:
return 0, 0.0
inds = np.argwhere(xv <= t)
if len(inds) < 1:
return 0, t
ind = inds[-1, 0]
return ind, t
def getView(self):
"""Return the ViewBox (or other compatible object) which displays the ImageItem"""
return self.view
def getImageItem(self):
"""Return the ImageItem for this ImageView."""
return self.imageItem
def getRoiPlot(self):
"""Return the ROI PlotWidget for this ImageView"""
return self.ui.roiPlot
def getHistogramWidget(self):
"""Return the HistogramLUTWidget for this ImageView"""
return self.ui.histogram
def export(self, fileName):
"""
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.
"""
img = self.getProcessedImage()
if self.hasTimeAxis():
base, ext = os.path.splitext(fileName)
fmt = "%%s%%0%dd%%s" % int(log10(img.shape[0])+1)
for i in range(img.shape[0]):
self.imageItem.setImage(img[i], autoLevels=False)
self.imageItem.save(fmt % (base, i, ext))
self.updateImage()
else:
self.imageItem.save(fileName)
def exportClicked(self):
fileName, _ = QtWidgets.QFileDialog.getSaveFileName()
if not fileName:
return
self.export(fileName)
def buildMenu(self):
self.menu = QtWidgets.QMenu()
self.normAction = QtGui.QAction(translate("ImageView", "Normalization"), self.menu)
self.normAction.setCheckable(True)
self.normAction.toggled.connect(self.normToggled)
self.menu.addAction(self.normAction)
self.exportAction = QtGui.QAction(translate("ImageView", "Export"), self.menu)
self.exportAction.triggered.connect(self.exportClicked)
self.menu.addAction(self.exportAction)
def menuClicked(self):
if self.menu is None:
self.buildMenu()
self.menu.popup(QtGui.QCursor.pos())
def setColorMap(self, colormap):
"""Set the color map.
Parameters
----------
colormap : ColorMap
The ColorMap to use for coloring images.
"""
self.ui.histogram.gradient.setColorMap(colormap)
@addGradientListToDocstring()
def setPredefinedGradient(self, name):
"""Set one of the gradients defined in :class:`GradientEditorItem`.
Currently available gradients are:
"""
self.ui.histogram.gradient.loadPreset(name)
|