Skip to content

Commit

Permalink
rename variables and add test
Browse files Browse the repository at this point in the history
  • Loading branch information
paulhfu committed Jun 14, 2019
1 parent 1ff05dc commit 094a9b5
Show file tree
Hide file tree
Showing 7 changed files with 373 additions and 146 deletions.
220 changes: 220 additions & 0 deletions tests/quadStatusBar_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
###############################################################################
# volumina: volume slicing and editing library
#
# Copyright (C) 2011-2019, the ilastik developers
# <[email protected]>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the Lesser GNU General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# See the files LICENSE.lgpl2 and LICENSE.lgpl3 for full text of the
# GNU Lesser General Public License version 2.1 and 3 respectively.
# This information is also available on the ilastik web site at:
# http://ilastik.org/license/
###############################################################################
import pytest
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtCore import QPointF, Qt
from PyQt5.QtGui import QColor

import numpy as np
import vigra
from ilastik.applets.layerViewer.layerViewerGui import LayerViewerGui
from lazyflow.operators.opReorderAxes import OpReorderAxes
from volumina.volumeEditor import VolumeEditor
from volumina.volumeEditorWidget import VolumeEditorWidget
from volumina.layerstack import LayerStackModel
from volumina.pixelpipeline.datasources import LazyflowSource
from volumina.layer import AlphaModulatedLayer
from lazyflow.graph import Operator, InputSlot, OutputSlot, Graph


class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.volumeEditorWidget = VolumeEditorWidget(parent=self)


class OpTestImgaeSlots(Operator):
"""test operator, containing 3-dim test data"""

GrayscaleImageIn = InputSlot()
Label1ImageIn = InputSlot()
Label2ImageIn = InputSlot()

GrayscaleImageOut = OutputSlot()
Label1ImageOut = OutputSlot()
Label2ImageOut = OutputSlot()

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

width, height, depth = 300, 200, 40

# create 2-dimensional images
grayscaleImageSource = np.random.randint(0, 255, (depth, height, width, 1))
label1ImageSource = np.zeros((depth, height, width, 3), dtype=np.int32)
label2ImageSource = np.zeros((depth, height, width, 3), dtype=np.int32)

for z, set1 in enumerate(grayscaleImageSource[:, :, :, 0]):
for y, set2 in enumerate(set1):
for x, set3 in enumerate(set2):
if z in range(5, 20) and y in range(20, 30) and x in range(80, 140):
label1ImageSource[z, y, x, :] = [255, 255, 255]
if z in range(25, 37) and y in range(100, 150) and x in range(10, 60):
label2ImageSource[z, y, x, :] = [255, 255, 255]

self.GrayscaleImageIn.setValue(grayscaleImageSource, notify=False, check_changed=False)
self.Label1ImageIn.setValue(label1ImageSource, notify=False, check_changed=False)
self.Label2ImageIn.setValue(label2ImageSource, notify=False, check_changed=False)

self.GrayscaleImageIn.meta.axistags = vigra.defaultAxistags("tzyxc"[5 - len(self.GrayscaleImageIn.meta.shape):])
self.Label1ImageIn.meta.axistags = vigra.defaultAxistags("tzyxc"[5 - len(self.Label1ImageIn.meta.shape):])
self.Label2ImageIn.meta.axistags = vigra.defaultAxistags("tzyxc"[5 - len(self.Label2ImageIn.meta.shape):])

self.GrayscaleImageOut.connect(self.GrayscaleImageIn)
self.Label1ImageOut.connect(self.Label1ImageIn)
self.Label2ImageOut.connect(self.Label2ImageIn)


class TestSpinBoxImageView(object):

def updateAllTiles(self, imageScenes):
for scene in imageScenes:
scene.joinRenderingAllTiles()

@pytest.fixture(autouse=True)
def setupClass(self, qtbot):

self.qtbot = qtbot
self.main = MainWindow()
self.layerStack = LayerStackModel()

g = Graph()
self.op = OpTestImgaeSlots(graph=g)

self.grayscaleLayer = LayerViewerGui._create_grayscale_layer_from_slot(self.op.GrayscaleImageOut, 1)
self.labelLayer1 = AlphaModulatedLayer(LazyflowSource(self.op.Label1ImageOut), tintColor=QColor(Qt.cyan),
range=(0, 255), normalize=(0, 255))
self.labelLayer2 = AlphaModulatedLayer(LazyflowSource(self.op.Label2ImageOut), tintColor=QColor(Qt.yellow),
range=(0, 255), normalize=(0, 255))

self.labelLayer1.name = "Segmentation (Label 1)"
self.labelLayer2.name = "Segmentation (Label 2)"

self.layerStack.append(self.grayscaleLayer)
self.layerStack.append(self.labelLayer1)
self.layerStack.append(self.labelLayer2)

activeOutSlot = self.op.GrayscaleImageOut # take any out slot here
if activeOutSlot.ready() and activeOutSlot.meta.axistags is not None:
# Use an OpReorderAxes adapter to transpose the shape for us.
op5 = OpReorderAxes(graph=g)
op5.Input.connect(activeOutSlot)
op5.AxisOrder.setValue('txyzc')
shape = op5.Output.meta.shape

# We just needed the op to determine the transposed shape.
# Disconnect it so it can be garbage collected.
op5.Input.disconnect()
op5.cleanUp()

self.editor = VolumeEditor(self.layerStack, self.main)
self.editorWidget = self.main.volumeEditorWidget
self.editorWidget.init(self.editor)

self.editor.dataShape = shape

# Find the xyz midpoint
midpos5d = [x // 2 for x in shape]
# center viewer there
# set xyz position
midpos3d = midpos5d[1:4]
self.editor.posModel.slicingPos = midpos3d
self.editor.navCtrl.panSlicingViews(midpos3d, [0, 1, 2])
for i in range(3):
self.editor.navCtrl.changeSliceAbsolute(midpos3d[i], i)

self.main.setCentralWidget(self.editorWidget)
self.main.show()
self.qtbot.addWidget(self.main)

def testAddingAndRemovingPosVal(self):
assert 0 == len(self.editorWidget.quadViewStatusBar.layerValueWidgets)

for layer in self.layerStack:
if not layer.showPosValue:
layer.showPosValue = True
if not layer.visible:
layer.visible = True

for layer in self.layerStack:
assert layer in self.editorWidget.quadViewStatusBar.layerValueWidgets

self.layerStack[0].showPosValue = False
assert self.layerStack[0] not in self.editorWidget.quadViewStatusBar.layerValueWidgets
self.layerStack[2].showPosValue = False
assert self.layerStack[2] not in self.editorWidget.quadViewStatusBar.layerValueWidgets
self.layerStack[1].showPosValue = False
assert self.layerStack[1] not in self.editorWidget.quadViewStatusBar.layerValueWidgets
self.layerStack[2].showPosValue = True
assert self.layerStack[2] in self.editorWidget.quadViewStatusBar.layerValueWidgets

def testLayerPositionValueStrings(self):
for layer in self.layerStack:
if not layer.showPosValue:
layer.showPosValue = True
if not layer.visible:
layer.visible = True

x, y, z = 90, 25, 10

posVal = 255-int(self.op.GrayscaleImageIn.value[z, y, x, 0])
grayValidationStrings = ["Gray:" + str(posVal), "Gray:" + str(posVal+1), "Gray:" + str(posVal-1)]
label1ValidationString = "Label 1"
label2ValidationString = "Label 2"

signal = self.editor.posModel.cursorPositionChanged
with self.qtbot.waitSignal(signal, timeout=1000):
self.editor.navCtrl.changeSliceAbsolute(z, 2)

# After change of crosshair positions tiles are marked dirty.
self.updateAllTiles(self.editor.imageScenes) # Wait for all tiles being refreshed

signals = [self.editorWidget.quadViewStatusBar.layerValueWidgets[self.grayscaleLayer].textChanged,
self.editorWidget.quadViewStatusBar.layerValueWidgets[self.labelLayer1].textChanged]
with self.qtbot.waitSignals(signals, timeout=1000):
self.editor.navCtrl.positionDataCursor(QPointF(x, y), 2)

self.updateAllTiles(self.editor.imageScenes) # Wait for all tiles being refreshed

assert self.editorWidget.quadViewStatusBar.layerValueWidgets[
self.grayscaleLayer].text() in grayValidationStrings
assert self.editorWidget.quadViewStatusBar.layerValueWidgets[self.labelLayer1].text() == label1ValidationString

x, y, z = 39, 130, 30

posVal = 255-int(self.op.GrayscaleImageIn.value[z, y, x, 0])
grayValidationStrings = ["Gray:" + str(posVal), "Gray:" + str(posVal+1), "Gray:" + str(posVal-1)]

with self.qtbot.waitSignal(signal, timeout=1000):
self.editor.navCtrl.changeSliceAbsolute(y, 1)

self.updateAllTiles(self.editor.imageScenes) # Wait for all tiles being refreshed

with self.qtbot.waitSignals(signals, timeout=1000):
self.editor.navCtrl.positionDataCursor(QPointF(x, z), 1)

self.updateAllTiles(self.editor.imageScenes) # Wait for all tiles being refreshed

assert self.editorWidget.quadViewStatusBar.layerValueWidgets[
self.grayscaleLayer].text() in grayValidationStrings
assert self.editorWidget.quadViewStatusBar.layerValueWidgets[self.labelLayer2].text() == label2ValidationString

47 changes: 27 additions & 20 deletions volumina/layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class Layer(QObject):
somethingChanged signals is emitted."""
changed = pyqtSignal()

showValueChanged = pyqtSignal(object, bool)
showPosValueChanged = pyqtSignal(object, bool)
visibleChanged = pyqtSignal(bool)
opacityChanged = pyqtSignal(float)
nameChanged = pyqtSignal(object) # sends a python str object, not unicode!
Expand All @@ -82,13 +82,13 @@ def visible(self, value):
self.visibleChanged.emit(value)

@property
def showValue(self):
return self._showValue
def showPosValue(self):
return self._showPosValue

@showValue.setter
def showValue(self, value):
self._showValue = value
self.showValueChanged.emit(self, value)
@showPosValue.setter
def showPosValue(self, value):
self._showPosValue = value
self.showPosValueChanged.emit(self, value)

def toggleVisible(self):
"""Convenience function."""
Expand Down Expand Up @@ -175,17 +175,17 @@ def toolTip(self):
def setToolTip(self, tip):
self._toolTip = tip

def setValueWidget(self, value):
def getPosInfo(self, value):
"""
This function needs to be overwritten by every layer.
This function is called by QuadStatusBar.setMouseCoords. It is expected to return a tuple of information for
the position widgets, showing current pixelvalues of respective layer.
It is called by QuadStatusBar.setLayerPosIfos and is expected to return a tuple of information for
the position widgets, showing current pixelvalues at cursor position of respective layer.
:param val: layer value at current cursor position
:return: ((String)text, (QColor)foregroundcolor, (QColor)backgroundcolor) for respective widget
"""
if value is not None:
return self.name + str(value), QColor(255, 255, 255), QColor(0, 0, 0)
return None, QColor(255, 255, 255), QColor(0, 0, 0)
return self.name + str(value), QColor(0, 0, 0), QColor(255, 255, 255)
return None, QColor(0, 0, 0), QColor(255, 255, 255)

def isDifferentEnough(self, other_layer):
"""This ugly function is here to support the updateAllLayers function in the layerViewerGui in ilastik"""
Expand All @@ -201,7 +201,7 @@ def __init__(self, datasources, direct=False):
super(Layer, self).__init__()
self._name = u"Unnamed Layer"
self._visible = True
self._showValue = False
self._showPosValue = False
self._opacity = 1.0
self._datasources = datasources
self._layerId = None
Expand Down Expand Up @@ -429,10 +429,16 @@ def isDifferentEnough(self, other_layer):
return True
return self._window_leveling != other_layer._window_leveling

def setValueWidget(self, value):
def getPosInfo(self, value):
"""overwrites Layer.getPosInfo"""
if value is not None:
return 'Gray:' + str(value.black()), QColor(value.black(), value.black(), value.black()), value
return None, QColor(255, 255, 255), QColor(0, 0, 0)
gray_val = 255
if value.value() in range(int(gray_val/2-10), int(gray_val/2+10)):
gray_val = value.black() + 20 * numpy.sign(value.black() - value.value())
else:
gray_val = value.black()
return 'Gray:' + str(value.black()), QColor(gray_val, gray_val, gray_val), value
return None, QColor(0, 0, 0), QColor(255, 255, 255)

def __init__(self, datasource, range=None, normalize=None, direct=False, window_leveling=False):
assert isinstance(datasource, SourceABC)
Expand All @@ -458,15 +464,16 @@ def tintColor(self, c):
self._tintColor = c
self.tintColorChanged.emit()

def setValueWidget(self, value):
def getPosInfo(self, value):
"""overwrites Layer.getPosInfo"""
if value is None:
return None, QColor(255, 255, 255), QColor(0, 0, 0)
return None, QColor(0, 0, 0), QColor(255, 255, 255)
elif "Segmentation (Label " in self.name:
if value.getRgb() == (0,0,0,0):
return None, QColor(255, 255, 255), QColor(0, 0, 0)
return None, QColor(0, 0, 0), QColor(255, 255, 255)
return self.name[self.name.find("(") + 1:self.name.find(")")], QColor(255, 255, 255), self.tintColor
else:
return self.name + str(value.getRgb()), QColor(255, 255, 255), QColor(0, 0, 0)
return self.name + str(value.getRgb()), QColor(0, 0, 0), QColor(255, 255, 255)

def __init__(self, datasource, tintColor=QColor(255, 0, 0), range=(0, 255), normalize=None):
assert isinstance(datasource, SourceABC)
Expand Down
34 changes: 13 additions & 21 deletions volumina/patchAccessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,36 +94,28 @@ def patchRectF(self, blockNum, overlap=0):
return QRectF(QPointF(startx, starty), QPointF(endx, endy))

def getPatchesForRect(self, startx, starty, endx, endy):
"""returns patchnumbers for patches that are intersecting with the normalized rectangle defined by upper left
corner (staŕtx/y) and lower right corner (endx/y)
"""
if endy < 0 or endx < 0:
# allowing no inverted start/end -positions, there should be no negative end-positions
return []
Looks up patches for specified block
x in [startx, endx)
y in [starty, endy)
:returns: list of patch ids
"""
assert startx < endx
assert starty < endy

sx = int(numpy.floor(1.0 * startx / self._blockSize))
ex = int(numpy.ceil(1.0 * endx / self._blockSize))
sy = int(numpy.floor(1.0 * starty / self._blockSize))
ey = int(numpy.ceil(1.0 * endy / self._blockSize))

# Clip to rect to upper bounds
# Clip to rect bounds
sx = max(sx, 0)
sy = max(sy, 0)
ex = min(ex, self._cX)
ey = min(ey, self._cY)

# return an index also, when start and end are equal
if sx == ex:
if ex >= self._cX:
sx = sx - 1
else:
ex = ex + 1
if sy == ey:
if ey >= self._cY:
sy = sy - 1
else:
ey = ey + 1

# Clip to rect to lower bounds
sx = max(sx, 0)
sy = max(sy, 0)
sx = max(min(sx, ex - 1), 0)
sy = max(min(sy, ey - 1), 0)

nums = []
for y in range(sy, ey):
Expand Down
4 changes: 2 additions & 2 deletions volumina/quadsplitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,8 +270,8 @@ def addStatusBar(self, bar):
def setGrayScaleToQuadStatusBar(self, gray):
self.quadViewStatusBar.setGrayScale(gray)

def setMouseCoordsToQuadStatusBar(self, x, y, z):
self.quadViewStatusBar.setMouseCoords(x, y, z)
def setLayerPosIfosToQuadStatusBar(self, x, y, z):
self.quadViewStatusBar.setMousePosInfos(x, y, z)

def ensureMaximized(self, axis):
"""
Expand Down
Loading

0 comments on commit 094a9b5

Please sign in to comment.