Skip to content

Commit

Permalink
Merge pull request #3944 from vallsv/fix-compare-typo
Browse files Browse the repository at this point in the history
compare: Few improvements
  • Loading branch information
t20100 authored Nov 27, 2023
2 parents 7065a3a + c1fb910 commit 32716b4
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 8 deletions.
42 changes: 36 additions & 6 deletions src/silx/app/compare/CompareImagesWindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,37 @@

import logging
import numpy
import typing
import os.path

import silx.io
from silx.gui import icons
from silx.gui import qt
from silx.io.url import DataUrl
from silx.gui.plot.CompareImages import CompareImages
from silx.gui.widgets.UrlSelectionTable import UrlSelectionTable
from ..utils import parseutils
from silx.gui.plot.tools.profile.manager import ProfileManager
from silx.gui.plot.tools.compare.profile import ProfileImageDirectedLineROI

try:
import PIL
except ImportError:
PIL = None


_logger = logging.getLogger(__name__)


def _get_image_from_file(urlPath: str) -> typing.Optional[numpy.ndarray]:
"""Returns a dataset from an image file.
The returned layout shape is supposed to be `rows, columns, channels (rgb[a])`.
"""
if PIL is None:
return None
return numpy.asarray(PIL.Image.open(urlPath))


class CompareImagesWindow(qt.QMainWindow):
def __init__(self, backend=None, settings=None):
qt.QMainWindow.__init__(self, parent=None)
Expand Down Expand Up @@ -126,10 +142,19 @@ def readData(self, urlPath: str):
if urlPath in ("", None):
return None

try:
data = silx.io.utils.get_data(urlPath)
except Exception:
raise ValueError(f"Data from '{urlPath}' is not readable")
data = None
_, ext = os.path.splitext(urlPath)
if ext in {".jpg", ".jpeg", ".png"}:
try:
data = _get_image_from_file(urlPath)
except Exception:
_logger.debug("Error while loading image with PIL", exc_info=True)

if data is None:
try:
data = silx.io.utils.get_data(urlPath)
except Exception:
raise ValueError(f"Data from '{urlPath}' is not readable")

if not isinstance(data, numpy.ndarray):
raise ValueError(f"URL '{urlPath}' does not link to a numpy array")
Expand All @@ -138,7 +163,7 @@ def readData(self, urlPath: str):

if data.ndim == 2:
return data
if data.ndim == 3 and data.shape[0] in set([3, 4]):
if data.ndim == 3 and data.shape[2] in {3, 4}:
return data

raise ValueError(f"URL '{urlPath}' does not link to an numpy image")
Expand All @@ -163,6 +188,8 @@ def saveSettings(self, settings):
settings.setValue("pos", self.pos())
settings.setValue("full-screen", isFullScreen)
settings.setValue("spliter", self.__splitter.sizes())
# NOTE: isInverted returns a numpy bool
settings.setValue("y-axis-inverted", bool(self._plot.getPlot().getYAxis().isInverted()))

settings.setValue("visualization-mode", self._plot.getVisualizationMode().name)
settings.setValue("alignment-mode", self._plot.getAlignmentMode().name)
Expand All @@ -189,6 +216,8 @@ def restoreSettings(self, settings):
pos = settings.value("pos", qt.QPoint())
isFullScreen = settings.value("full-screen", False)
isFullScreen = parseutils.to_bool(isFullScreen, False)
yAxisInverted = settings.value("y-axis-inverted", False)
yAxisInverted = parseutils.to_bool(yAxisInverted, False)

visualizationMode = settings.value("visualization-mode", "")
visualizationMode = parseutils.to_enum(
Expand Down Expand Up @@ -220,3 +249,4 @@ def restoreSettings(self, settings):
self._plot.setVisualizationMode(visualizationMode)
self._plot.setAlignmentMode(alignmentMode)
self._plot.setKeypointsVisible(displayKeypoints)
self._plot.getPlot().getYAxis().setInverted(yAxisInverted)
3 changes: 2 additions & 1 deletion src/silx/app/compare/test/test_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def test_wrong_option(qapp):
try:
parser = main.createParser()
parser.parse_args(["compare", "--foo"])
self.fail()
assert False
except SystemExit as e:
result = e.args[0]
assert result != 0
Expand Down Expand Up @@ -124,6 +124,7 @@ def execute_as_script(filename, *args):
assert p.returncode == 0
return execute_as_script


def test_execute_compare_help(qapp, execute_as_script):
"""Test if the main module is well connected.
Expand Down
3 changes: 2 additions & 1 deletion src/silx/gui/widgets/UrlSelectionTable.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,8 @@ def dropMimeData(self, row: int, column: int, mimedata: qt.QMimeType, action: qt
if action == qt.Qt.IgnoreAction:
return True
if mimedata.hasFormat(constants.SILX_URI_MIMETYPE):
url = DataUrl(mimedata.text())
urlText = str(mimedata.data(constants.SILX_URI_MIMETYPE), "utf-8")
url = DataUrl(urlText)
self.addUrl(url)
return True
return False
25 changes: 25 additions & 0 deletions tools/create_h5_sample.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,30 @@ def create_links(h5):
main_group["external_link_to_soft_recursive"] = h5py.ExternalLink(h5.file.filename, main_group.name + "/soft_link_to_itself")


def create_image_types(h5):
print("- Creating images...")
raw = numpy.arange(10*10).reshape((10,10))
u8 = (raw * 255 / raw.max()).astype(numpy.uint8)
f32 = (raw / raw.max()).astype(numpy.float32)
f64 = (raw / raw.max()).astype(numpy.float64)

u8_t = numpy.swapaxes(u8, 0, 1)
f32_t = numpy.swapaxes(f32, 0, 1)
f64_t = numpy.swapaxes(f64, 0, 1)

main_group = h5.create_group("images")

main_group["intensity_uint8"] = u8
main_group["intensity_float32"] = f32
main_group["intensity_float64"] = f64
main_group["rgb_uint8"] = numpy.stack((u8, u8_t, numpy.flip(u8, 0))).T
main_group["rgb_float32"] = numpy.stack((f32, f32_t, numpy.flip(f32, 0))).T
main_group["rgb_float64"] = numpy.stack((f64, f64_t, numpy.flip(f64, 0))).T
main_group["rgba_uint8"] = numpy.stack((u8, u8_t, numpy.flip(u8, 0), numpy.flip(u8_t))).T
main_group["rgba_float32"] = numpy.stack((f32, f32_t, numpy.flip(f32, 0), numpy.flip(f32_t))).T
main_group["rgba_float64"] = numpy.stack((f64, f64_t, numpy.flip(f64, 0), numpy.flip(f64_t))).T


def create_file():
filename = "all_types.h5"
print("Creating file '%s'..." % filename)
Expand All @@ -623,6 +647,7 @@ def create_file():
create_nxdata_group(h5)
create_encoded_data(h5)
create_links(h5)
create_image_types(h5)


def main():
Expand Down

0 comments on commit 32716b4

Please sign in to comment.