Commit 87d91024 authored by Josef Brandt's avatar Josef Brandt

Fixes Zeiss import

parent a6aa8137
......@@ -345,7 +345,7 @@ class DataSet(object):
assert not self.readin
if mode not in ['df', 'bf']:
raise ValueError(f'mapToLength mode: {mode} not understood')
# pixelpos = [2110.3, 1917.5]
p0 = copy(self.lastpos)
pixelscale = self.pixelscale_df if mode == 'df' else self.pixelscale_bf
imgdim = self.imagedim_df if mode == 'df' else self.imagedim_bf
......
from PyQt5 import QtWidgets, QtGui, QtCore
from typing import Tuple, TYPE_CHECKING
from typing import Tuple, TYPE_CHECKING, List
from copy import deepcopy
from ..coordTransform import *
......@@ -156,8 +156,7 @@ class CoordTransformUI(QtWidgets.QWidget):
invertX, invertY, invertZ = self._invertGroup.getInvert()
if len(srcPoints) == len(dstPoints) and len(srcPoints) >= 3 and np.all(np.isfinite(dstPoints)):
# if not self._dataset.coordinateSystemConfigured:
if True:
if not self._dataset.coordinateSystemConfigured:
self._setOriginalCoordSystem()
srcPoints = self._setAndGetCreatedImgMarkerSourcePoints()
......
......@@ -32,20 +32,21 @@ except ImportError:
skimsave = None
from logging import Logger
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Union
if TYPE_CHECKING:
from .instrumentcom.instrumentComBase import InstrumentComBase
def cv2imread_fix(fname, flags=cv2.IMREAD_COLOR):
def cv2imread_fix(fname, flags=cv2.IMREAD_COLOR) -> Union[None, np.ndarray]:
if skimread is not None:
return skimread(fname, as_gray=(flags == cv2.IMREAD_GRAYSCALE))
with open(fname, "rb") as fp:
cont = fp.read()
img = cv2.imdecode(np.fromstring(cont, dtype=np.uint8), flags)
return img
return None
img = skimread(fname, as_gray=(flags == cv2.IMREAD_GRAYSCALE))
else:
img: Union[None, np.ndarray] = None
with open(fname, "rb") as fp:
cont = fp.read()
img = cv2.imdecode(np.fromstring(cont, dtype=np.uint8), flags)
return img
def cv2imwrite_fix(fname, img, params=None):
......
......@@ -35,7 +35,7 @@ from ..scenePyramid import ScenePyramid
from ..coordTransform import CoordTransfer
if TYPE_CHECKING:
from zeissxml import Region, ZRange, Marker
from .zeissxml import Region, ZRange, Marker
class ImageImporter(QtWidgets.QDialog):
......@@ -55,7 +55,10 @@ class ImageImporter(QtWidgets.QDialog):
self.zImg: Union[np.ndarray, None] = None
self.xmlPath: str = ''
vbox = QtWidgets.QVBoxLayout()
self.optnLayout = QtWidgets.QVBoxLayout()
self.ignoreMarkersCheckbox: QtWidgets.QCheckBox = QtWidgets.QCheckBox("Ignore Markers")
self.ignoreMarkersCheckbox.setChecked(False)
self.ignoreMarkersCheckbox.toggled.connect(self._toggleMarkers)
self.fileSelector: FileSelector = FileSelector(self)
self.pointgroup = QtWidgets.QGroupBox('Marker coordinates at Raman spot [µm]', self)
......@@ -119,17 +122,17 @@ class ImageImporter(QtWidgets.QDialog):
statusLayout.addWidget(self.lblStatusZImage)
statusLayout.addWidget(self.lblStatusMeta)
vbox.addWidget(self.fileSelector)
vbox.addWidget(self.pxScaleGroup)
vbox.addWidget(self.pointgroup)
vbox.addWidget(self.blurGroup)
vbox.addWidget(self.invertGroup)
vbox.addLayout(statusLayout)
vbox.addLayout(btnLayout)
self.optnLayout.addWidget(self.fileSelector)
self.optnLayout.addWidget(self.pxScaleGroup)
self.optnLayout.addWidget(self.pointgroup)
self.optnLayout.addWidget(self.blurGroup)
self.optnLayout.addWidget(self.invertGroup)
self.optnLayout.addLayout(statusLayout)
self.optnLayout.addLayout(btnLayout)
self._imgPreview: ImagePreview = ImagePreview()
hbox = QtWidgets.QHBoxLayout()
hbox.addLayout(vbox)
hbox.addLayout(self.optnLayout)
hbox.addWidget(self._imgPreview)
self.setLayout(hbox)
......@@ -147,7 +150,7 @@ class ImageImporter(QtWidgets.QDialog):
self._updateStatusLabels()
self._enableDisableWidgets()
def setXMLPath(self, xmlPath: str) -> None:
def readXML(self, xmlPath: str) -> None:
self.xmlPath = xmlPath
parser = make_parser()
......@@ -175,14 +178,24 @@ class ImageImporter(QtWidgets.QDialog):
self.markers = z.markers
self._updateStatusLabels()
self._enableDisableWidgets()
self._createPointGroup()
def _createPointGroup(self) -> None:
self._clearLayout(self.pointgroup.layout())
pointGroupInd: int = self.optnLayout.indexOf(self.pointgroup)
self.optnLayout.removeWidget(self.pointgroup)
self.pointgroup.setParent(None)
self.pointgroup = QtWidgets.QGroupBox('Marker coordinates at Raman spot [µm]', self)
self.points = PointCoordinates(len(self.markers), self.instrctrl, self,
names=[m.name for m in self.markers])
self.points.pimageOnly.setVisible(False)
self.pointgroup.setLayout(self.points)
self.points.readPoint.connect(self.takePoint)
self.pointgroup.setLayout(self.points)
self.optnLayout.insertWidget(pointGroupInd, self.ignoreMarkersCheckbox)
self.optnLayout.insertWidget(pointGroupInd+1, self.pointgroup)
@QtCore.pyqtSlot(float, float, float)
def takePoint(self, x, y, z):
points = self.points.getPoints()
......@@ -193,14 +206,12 @@ class ImageImporter(QtWidgets.QDialog):
fname = QtWidgets.QFileDialog.getSaveFileName(self, 'Create New GEPARD Project', defaultPath, '*.pkl')[0]
colorImg: np.ndarray = self._imgPreview.getImage()
if fname != '':
abort: bool = True
dataset = DataSet(fname, newProject=True)
requiresCoordTransfer = False
if None not in [self.zImg, self.markers, self.zrange]:
T, pc, zpc, accept = self.getTransform()
if accept:
self.convertZimg(dataset, T, pc, zpc)
abort = False
if self.zImg is not None and self.markers is not None and self.zrange is not None:
abort = self.convertZimg(dataset)
if self.ignoreMarkersCheckbox.isChecked():
requiresCoordTransfer = True
else:
self._set_ZValImageToDataset(dataset, np.zeros(colorImg.shape[:2]))
dataset.importedWithPlaceholderZValImg = True
......@@ -220,7 +231,27 @@ class ImageImporter(QtWidgets.QDialog):
else:
QtWidgets.QMessageBox.critical(self, "Error", "Failed importing project...")
def convertZimg(self, dataset, T, pc, zpc):
def convertZimg(self, dataset) -> bool:
"""
Converts the zvalImage and sets coordinate system, if marker shall be used.
Returns whether or not to abort the import process. Can be True, if transform residues are too large..
"""
if self.ignoreMarkersCheckbox.isChecked():
T, pc, zpc, accept = None, None, np.array([0, 0, 0]), True
else:
T, pc, zpc, accept = self.getTransform()
newTransform: CoordTransfer = CoordTransfer()
newTransform.rotMatrix = T
newTransform.offset = pc
dataset.coordinatetransform = newTransform
# set image center as reference point (assume just one tile)
# in data set (use Zeiss coordinates)
p0center = np.array([self.region.centerx, self.region.centery]) - zpc[:2]
dataset.lastpos = p0center
dataset.readin = False
N = int(round(abs(self.zrange.zn - self.zrange.z0) / self.zrange.dz))
z0, zn = self.zrange.z0, self.zrange.zn
if zn < z0:
......@@ -232,9 +263,11 @@ class ImageImporter(QtWidgets.QDialog):
dataset.heightmapParams = np.zeros(3)
dataset.signy = 1.
zimg = self.zImg
print("zimg shape:", zimg.shape, flush=True)
radius = self.blurspinbox.value()
blur = cv2.GaussianBlur(zimg, (radius, radius), 0)
blur = np.clip(blur * 255.0, 0, 255.0)
blur[np.isnan(blur)] = 0.
blur = np.uint8(blur)
pshift = self.instrctrl.getSpectrumPositionShift()
dataset.pshift = pshift
......@@ -242,29 +275,14 @@ class ImageImporter(QtWidgets.QDialog):
# use input image as single image aquired in one shot
dataset.pixelscale_df = dataset.pixelscale_bf = pixelscale
dataset.zvalimg = blur
dataset.calculateImageDimsFromZImg()
print('scale:', pixelscale)
print('dim df:', dataset.imagedim_df)
print('dim bf:', dataset.imagedim_bf)
newTransform: CoordTransfer = CoordTransfer()
newTransform.rotMatrix = T
newTransform.offset = pc
dataset.coordinatetransform = newTransform
# set image center as reference point (assume just one tile)
# in data set (use Zeiss coordinates)
p0center = np.array([self.region.centerx, self.region.centery]) - zpc[:2]
dataset.readin = False
dataset.lastpos = p0center
# Originally, here was also a line to set dataset.maxdim = p0center. maxdim is not needed here, though (optical
# scan is not done anymore... Also, maxdim should contain x and y coordinates of TWO points...???
blur = np.clip(blur * 255.0, 0, 255.0)
blur[np.isnan(blur)] = 0.
blur = np.uint8(blur)
self._set_ZValImageToDataset(dataset, blur)
abort: bool = not accept
return abort
def _set_ZValImageToDataset(self, dataset: 'DataSet', zvalImg: np.ndarray) -> None:
zimgname = dataset.getZvalImageName()
cv2imwrite_fix(zimgname, zvalImg)
......@@ -330,17 +348,28 @@ class ImageImporter(QtWidgets.QDialog):
return T, pc - shift, zpc, accept
def enableDisablePxScaleGroup(self, enabled: bool) -> None:
self._clearLayout(self.pxScaleGroup.layout())
pxScaleGroupInd: int = self.optnLayout.indexOf(self.pxScaleGroup)
self.optnLayout.removeWidget(self.pxScaleGroup)
self.pxScaleGroup.setParent(None)
layout: QtWidgets.QHBoxLayout = QtWidgets.QHBoxLayout()
if enabled:
layout.addWidget(self.pxScaleSpinbox)
else:
layout.addWidget(QtWidgets.QLabel("Will be read from MetaFile"))
layout.addStretch()
self.pxScaleGroup: QtWidgets.QGroupBox = QtWidgets.QGroupBox("Pixelscale (µm/px)")
self.pxScaleGroup.setLayout(layout)
self.pxScaleGroup.setEnabled(enabled)
self.optnLayout.insertWidget(pxScaleGroupInd, self.pxScaleGroup)
def _enableDisableWidgets(self) -> None:
self.pconvert.setEnabled(self.colorImg is not None)
enabled: bool = self.colorImg is not None
self.pconvert.setEnabled(enabled)
self.invertGroup.setEnabled(enabled)
self.blurGroup.setEnabled(enabled)
def _updateStatusLabels(self) -> None:
if self.colorImg is None:
......@@ -364,6 +393,24 @@ class ImageImporter(QtWidgets.QDialog):
self.lblStatusMeta.setStyleSheet("color: green")
self.lblStatusMeta.setText("Metadata loaded.")
def _toggleMarkers(self) -> None:
"""
Sets Marker group enabled or disabled, according to the checkbox.
"""
self.pointgroup.setDisabled(self.ignoreMarkersCheckbox.isChecked())
def _clearLayout(self, layout) -> None:
"""
Deletes all contents of the given layout.
"""
for i in reversed(range(layout.count())):
item = layout.itemAt(i)
if item is not None:
widget = item.widget()
layout.removeWidget(widget)
else:
layout.removeItem(item)
class FileSelector(QtWidgets.QGroupBox):
def __init__(self, parent: 'ImageImporter'):
......@@ -419,6 +466,7 @@ class FileSelector(QtWidgets.QGroupBox):
if fname:
try:
image: np.ndarray = cv2imread_fix(fname)
print('loaded colorImg with shape:', image.shape)
self._LineEditImage.setText(os.path.basename(fname))
self._parent.setColorImage(image)
except Exception as e:
......@@ -429,9 +477,12 @@ class FileSelector(QtWidgets.QGroupBox):
filter="Images (*.tiff *tif)")
if fname:
try:
zImage: np.ndarray = cv2imread_fix(fname)
zImage: np.ndarray = cv2imread_fix(fname, cv2.IMREAD_GRAYSCALE)
print('loaded zImg with shape:', zImage.shape)
self._LineEditZImage.setText(os.path.basename(fname))
print('set Text')
self._parent.setZValImage(zImage)
print('set zvalImage to Parent')
except Exception as e:
QtWidgets.QMessageBox.warning(self, "Error", f"ZImage {fname} could not be loaded:/n{e}")
......@@ -440,10 +491,12 @@ class FileSelector(QtWidgets.QGroupBox):
filter="XML File (*.xml)")
if fname:
self._LineEditMeta.setText(os.path.basename(fname))
self._parent.setXMLPath(fname)
self._parent.enableDisablePxScaleGroup(True)
else:
self._parent.readXML(fname)
print('finished reading XML')
self._parent.enableDisablePxScaleGroup(False)
else:
self._parent.enableDisablePxScaleGroup(True)
class ImagePreview(QtWidgets.QWidget):
......
......@@ -149,7 +149,10 @@ class FTIRCom(InstrumentComBase):
self.dde.set_stage_z(z)
x_set, y_set, z_set = self.dde.get_stage_coords()
diffz: float = abs(z_set - z)
assert diffz <= epsz, f'diff z is {diffz}, max allowed: {epsz}'
if diffz > epsz:
self.logger.critical(f"Warning, z difference is large! z-target: {z}, z_actul: {z_set}, diff: {diffz} (max. allowed: {epsz}).")
breakpoint()
# assert diffz <= epsz, f'diff z is {diffz}, max allowed: {epsz}'
def setAperture(self, widthMicrons: float, heightMicrons: float, angleDegree: float) -> None:
self.dde.set_aperture(widthMicrons, heightMicrons, angleDegree)
......
......@@ -16,7 +16,8 @@ pyparsing==2.4.7
python-dateutil==2.8.1
pytz==2020.1
pywavelets==1.1.1
pywin32~=2.2.7
PyQt5
jcamp
scikit-fuzzy==0.4.2
scikit-image==0.17.2
scipy==1.5.2
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment