GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — PlotPy/plotpy/items/image/base.py at master · PlotPyStack/PlotPy

Expand file tree

/

base.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
1770 lines (1495 loc) · 59.3 KB
/

base.py

Copy path

File metadata and controls

1770 lines (1495 loc) · 59.3 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the BSD 3-Clause
# (see plotpy/LICENSE for details)
from __future__ import annotations
import math
import os
import os.path as osp
import weakref
from collections import OrderedDict
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
import numpy as np
from guidata.dataset import update_dataset
from guidata.utils.misc import assert_interfaces_valid
from qtpy import QtCore as QC
from qtpy import QtGui as QG
from qwt import QwtLinearScaleEngine, QwtPlotItem
from plotpy import io
from plotpy._scaler import (
INTERP_AA,
INTERP_LINEAR,
INTERP_NEAREST,
_histogram,
_scale_rect,
)
from plotpy.config import CONF, _
from plotpy.constants import LUT_MAX, LUT_SIZE, LUTAlpha
from plotpy.coords import pixelround
from plotpy.interfaces import (
IBaseImageItem,
IBasePlotItem,
IColormapImageItemType,
ICSImageItemType,
IExportROIImageItemType,
IHistDataSource,
IImageItemType,
ISerializableType,
ITrackableItemType,
IVoiImageItemType,
)
# do not import rectangleshape from plotpy.items directly
from plotpy.items.shape.rectangle import RectangleShape
from plotpy.lutrange import lut_range_threshold
from plotpy.mathutils.arrayfuncs import get_nan_range
from plotpy.mathutils.colormap import FULLRANGE, get_cmap
from plotpy.styles.image import RawImageParam
from plotpy.widgets.colormap.widget import EditableColormap
if TYPE_CHECKING:
import guidata.io
import qwt.color_map
import qwt.scale_map
from qtpy.QtCore import QPointF, QRectF
from qtpy.QtGui import QColor, QPainter
from plotpy.interfaces import IItemType
from plotpy.plot import BasePlot
from plotpy.styles.base import ItemParameters
#: Lookup tables already computed by :func:`_get_colormap_lut`, most recent last
_LUT_CACHE: OrderedDict[tuple, tuple[tuple[int, ...], np.ndarray]] = OrderedDict()
_LUT_CACHE_SIZE = 32
def _lut_cache_key(
table: EditableColormap, alpha: float, alpha_function: int
) -> tuple | None:
"""Return the key identifying the lookup table of a colormap, if cacheable.
The key is built from the colormap content (not its identity), so that an
edited colormap gets a new lookup table.
Args:
table: Colormap
alpha: Global alpha value
alpha_function: Alpha function (see :class:`plotpy.constants.LUTAlpha`)
Returns:
Cache key, or None if the lookup table must be computed: colormap
subclasses may compute colors differently, and the colors of translucent
stops depend on the order in which the stops were inserted.
"""
if type(table) is not EditableColormap:
return None
stops = tuple((stop.pos, stop.rgb) for stop in table.colorStops())
if any(stop.a != 255 for stop in table.colorStops()):
return None
return (stops, table.mode(), table.invert, alpha, alpha_function)
def _compute_colormap_lut(
table: EditableColormap, alpha: float, alpha_function: int
) -> tuple[tuple[int, ...], np.ndarray]:
"""Compute the color table and the lookup table of a colormap.
Args:
table: Colormap
alpha: Global alpha value
alpha_function: Alpha function (see :class:`plotpy.constants.LUTAlpha`)
Returns:
Color table (256 colors) and lookup table (``LUT_SIZE`` ARGB values)
"""
colors = tuple(table.colorTable(FULLRANGE))
lut = np.zeros((LUT_SIZE,), np.uint32)
for i in range(LUT_SIZE):
if alpha_function == LUTAlpha.NONE.value:
pix_alpha = 1.0
elif alpha_function == LUTAlpha.CONSTANT.value:
pix_alpha = alpha
else:
x = i / float(LUT_SIZE - 1)
if alpha_function == LUTAlpha.LINEAR.value:
# Linear alpha function
pix_alpha = alpha * x
elif alpha_function == LUTAlpha.SIGMOID.value:
# Sigmoid alpha function
pix_alpha = alpha / (1 + np.exp(-10 * x))
elif alpha_function == LUTAlpha.TANH.value:
# Hyperbolic tangent alpha function
pix_alpha = alpha * np.tanh(5 * x)
elif alpha_function == LUTAlpha.STEP.value:
# Fully transparent lowest value and `alpha` transparent elsewhere
pix_alpha = alpha if x > 0 else 0
else:
raise ValueError(f"Invalid alpha function {alpha_function}")
# pylint: disable=too-many-function-args
alpha_channel = max(min(np.uint32(255 * pix_alpha + 0.5), 255), 0) << 24
lut[i] = (
np.uint32((table.rgb(FULLRANGE, i / LUT_MAX)) & 0xFFFFFF) | alpha_channel
)
return colors, lut
def _get_colormap_lut(
table: EditableColormap, alpha: float, alpha_function: int
) -> tuple[tuple[int, ...], np.ndarray]:
"""Return the color table and the lookup table of a colormap.
Computing them takes more than 1000 calls to the colormap: they are cached,
since every new image item usually shows the same colormap.
Args:
table: Colormap
alpha: Global alpha value
alpha_function: Alpha function (see :class:`plotpy.constants.LUTAlpha`)
Returns:
Color table (256 colors) and lookup table (``LUT_SIZE`` ARGB values),
the latter being read-only
"""
key = _lut_cache_key(table, alpha, alpha_function)
if key is not None and key in _LUT_CACHE:
_LUT_CACHE.move_to_end(key)
return _LUT_CACHE[key]
colors, lut = _compute_colormap_lut(table, alpha, alpha_function)
lut.flags.writeable = False
if key is not None:
_LUT_CACHE[key] = (colors, lut)
if len(_LUT_CACHE) > _LUT_CACHE_SIZE:
_LUT_CACHE.popitem(last=False)
return colors, lut
def get_offscreen_ratio(painter: QPainter) -> float:
"""Return the resolution at which image items are rendered before being
drawn with the given painter, in pixels per canvas pixel.
Images are rendered at the resolution of the paint device, e.g. 1.25 or 2
pixels per canvas pixel with a 125% or 200% screen scaling, instead of being
upscaled from the canvas resolution, which takes more time (up to about 4
times with a 200% screen scaling). Images are rendered at the canvas
resolution when printing or exporting with a scaling (or rotating) painter
transform, or when the ``image/device_resolution`` option of the ``plot``
configuration section is disabled.
Args:
painter: Painter
Returns:
Resolution, in pixels per canvas pixel
"""
world = painter.worldTransform()
if (
world.isScaling()
or world.isRotating()
or not CONF.get("plot", "image/device_resolution", True)
):
return 1.0
ratio = abs(painter.deviceTransform().m11())
return ratio if ratio > 0.0 else 1.0
def reusable_rendering(draw_image: Callable) -> Callable:
"""Decorator marking a ``draw_image`` method whose rendering may be reused
The decorated method must only draw with :meth:`BaseImageItem._draw_offscreen`,
from offscreen images which are only modified when the item is rendered. The
rendering may then be drawn again without being computed when the plot is
redrawn with :meth:`.BasePlot.replot_overlays` (e.g. while moving a shape over
the image).
Args:
draw_image: ``draw_image`` method
Returns:
The same method
"""
draw_image.reusable_rendering = True
return draw_image
class _RenderKey:
"""Key of the rendering of an image item (see :func:`reusable_rendering`)
The key is made of values, compared by equality, and of objects (e.g. data
arrays), compared by identity. The objects are referenced weakly, so that they
are not kept alive by the key: an object which does not exist anymore does not
match any object, even another one with the same ``id``.
Args:
values: Values
objects: Objects (arrays or None)
"""
__slots__ = ("values", "refs")
def __init__(self, values: tuple, objects: tuple[np.ndarray | None, ...]) -> None:
self.values = values
self.refs = tuple(None if obj is None else weakref.ref(obj) for obj in objects)
def __eq__(self, other: object) -> bool:
if not isinstance(other, _RenderKey) or self.values != other.values:
return False
if len(self.refs) != len(other.refs):
return False
for ref, other_ref in zip(self.refs, other.refs):
if ref is None or other_ref is None:
if ref is not other_ref:
return False
elif ref() is None or ref() is not other_ref():
return False
return True
__hash__ = None
class BaseImageItem(QwtPlotItem):
"""Base class for image items
Args:
data: Image data
param: Image parameters
"""
__implements__ = (
IBasePlotItem,
IBaseImageItem,
IHistDataSource,
IVoiImageItemType,
ICSImageItemType,
IExportROIImageItemType,
)
_can_select = True
_can_resize = False
_can_move = False
_can_rotate = False
_readonly = False
_private = False
_icon_name = "plotpy:image.svg"
#: True if the item supports the Z-axis logarithmic scale, i.e. if it draws
#: its data through :meth:`_get_display_data` (see :meth:`supports_zaxis_log`)
_ZAXIS_LOG_SUPPORTED = False
def __init__(
self, data: np.ndarray | None = None, param: Any | None = None
) -> None:
super().__init__()
self.bg_qcolor = QG.QColor()
self.bounds = QC.QRectF()
# BaseImageItem needs:
# param.background
# param.alpha_function
# param.alpha
# param.colormap
if param is None:
param = self.get_default_param()
self.param = param
self.selected = False
self.data: np.ndarray | None = None
# Z-axis logarithmic scale support: the LUT range (`min`, `max`) is always
# expressed in data units, only the color mapping is logarithmic
self._log_data: np.ndarray | None = None
self._log_floor = 1.0
self._lin_lut_range: tuple[float, float] | None = None
self._is_zaxis_log = False
self.min = 0.0
self.max = 1.0
self.cmap_table = None
self.cmap = None
self.colormap_axis = None
self._image: QG.QImage | None = None
self._offscreen = np.array((1, 1), np.uint32)
#: Resolution of the offscreen image, in pixels per canvas pixel
self._offscreen_ratio = 1.0
#: Offscreen images and rectangles drawn by the last rendering of the item
self._offscreen_draws: list[tuple[QG.QImage, tuple[int, int, int, int]]] = []
#: Key of the last rendering of the item (see `_get_render_key`)
self._render_key: _RenderKey | None = None
# Linear interpolation is the default interpolation algorithm:
# it's almost as fast as 'nearest pixel' method but far smoother
self.interpolate = None
self.set_interpolation(INTERP_LINEAR)
x1, y1 = self.bounds.left(), self.bounds.top()
x2, y2 = self.bounds.right(), self.bounds.bottom()
self.border_rect = RectangleShape(x1, y1, x2, y2)
self.border_rect.set_style("plot", "shape/imageborder")
# A, B, Background, Colormap
self.lut = (1.0, 0.0, None, np.zeros((LUT_SIZE,), np.uint32))
self.set_lut_range((0.0, 255.0))
self.setItemAttribute(QwtPlotItem.AutoScale)
self.setItemAttribute(QwtPlotItem.Legend, True)
self._filename = None # The file this image comes from
self.histogram_cache = None
if data is not None:
self.set_data(data)
self.param.update_item(self)
# ---- Public API ----------------------------------------------------------
def get_default_param(self) -> Any:
"""Return instance of the default image param DataSet"""
raise NotImplementedError
def set_filename(self, fname: str) -> None:
"""Set the filename of the image
Args:
fname: Filename
"""
self._filename = fname
def get_filename(self) -> str | None:
"""Get the filename of the image
Returns:
Filename
"""
fname = self._filename
if fname is not None and not osp.isfile(fname):
other_try = osp.join(os.getcwd(), osp.basename(fname))
if osp.isfile(other_try):
self.set_filename(other_try)
fname = other_try
return fname
def get_filter(self, filterobj, filterparam):
"""Provides a filter object over this image's content"""
raise NotImplementedError
def get_pixel_coordinates(self, xplot: float, yplot: float) -> tuple[float, float]:
"""Get pixel coordinates from plot coordinates
Args:
xplot: X plot coordinate
yplot: Y plot coordinate
Returns:
Pixel coordinates
"""
return xplot, yplot
def get_plot_coordinates(self, xpixel: float, ypixel: float) -> tuple[float, float]:
"""Get plot coordinates from pixel coordinates
Args:
xpixel: X pixel coordinate
ypixel: Y pixel coordinate
Returns:
Plot coordinates
"""
return xpixel, ypixel
def get_closest_indexes(
self, x: float, y: float, corner: str | None = None
) -> tuple[int, int]:
"""Get closest image pixel indexes to the given coordinates
Args:
x: X coordinate
y: Y coordinate
corner: None (not a corner), 'TL' (top-left corner),
'BR' (bottom-right corner)
Returns:
Closest image pixel indexes
"""
x, y = self.get_pixel_coordinates(x, y)
i_max = self.data.shape[1] - 1
j_max = self.data.shape[0] - 1
if corner == "BR":
i_max += 1
j_max += 1
i = max([0, min([i_max, int(pixelround(x, corner))])])
j = max([0, min([j_max, int(pixelround(y, corner))])])
return i, j
def get_closest_index_rect(
self, x0: float, y0: float, x1: float, y1: float, avoid_empty: bool = True
) -> tuple[int, int, int, int]:
"""Get closest image rectangular pixel area index bounds, optionally
avoid returning an empty rectangular area (return at least 1x1 pixel area)
Args:
x0: X coordinate of first point
y0: Y coordinate of first point
x1: X coordinate of second point
y1: Y coordinate of second point
avoid_empty: True to avoid returning an empty rectangular area.
Defaults to True.
Returns:
Closest image rectangular pixel area index bounds compatible with
direct array slicing (e.g., data[iy0:iy1, ix0:ix1])
.. note::
Avoid returning empty rectangular area (return 1x1 pixel area instead).
Handle reversed/not-reversed Y-axis orientation.
Indices are compatible with direct array slicing and match get_data
behavior.
"""
ix0, iy0 = self.get_closest_indexes(x0, y0, corner="TL")
# Use TL to avoid double +1 addition
ix1, iy1 = self.get_closest_indexes(x1, y1, corner="TL")
if ix0 > ix1:
ix1, ix0 = ix0, ix1
if iy0 > iy1:
iy1, iy0 = iy0, iy1
# Add +1 to bottom-right indices for slice compatibility (matches get_data)
ix1 = min(ix1 + 1, self.data.shape[1])
iy1 = min(iy1 + 1, self.data.shape[0])
if ix0 == ix1 and avoid_empty:
ix1 = min(ix1 + 1, self.data.shape[1])
if iy0 == iy1 and avoid_empty:
iy1 = min(iy1 + 1, self.data.shape[0])
return ix0, iy0, ix1, iy1
def align_rectangular_shape(self, shape: RectangleShape) -> None:
"""Align rectangular shape to image pixels
Args:
shape: Shape to align
"""
ix0, iy0, ix1, iy1 = self.get_closest_index_rect(*shape.get_rect())
x0, y0 = self.get_plot_coordinates(ix0, iy0)
x1, y1 = self.get_plot_coordinates(ix1, iy1)
shape.set_rect(x0, y0, x1, y1)
def get_closest_pixel_indexes(self, x: float, y: float) -> tuple[int, int]:
"""Get closest pixel indexes
Args:
x: X coordinate
y: Y coordinate
Returns:
Closest pixel indexes
.. note::
Instead of returning indexes of an image pixel like the method
'get_closest_indexes', this method returns the indexes of the
closest pixel which is not necessarily on the image itself
(i.e. indexes may be outside image index bounds: negative or
superior than the image dimension)
.. note::
This is *not* the same as retrieving the canvas pixel coordinates
(which depends on the zoom level)
"""
x, y = self.get_pixel_coordinates(x, y)
i = int(pixelround(x))
j = int(pixelround(y))
return i, j
def get_x_values(self, i0: int, i1: int) -> np.ndarray:
"""Get X values from pixel indexes
Args:
i0: First index
i1: Second index
Returns:
X values corresponding to the given pixel indexes
"""
return np.arange(i0, i1)
def get_y_values(self, j0: int, j1: int) -> np.ndarray:
"""Get Y values from pixel indexes
Args:
j0: First index
j1: Second index
Returns:
Y values corresponding to the given pixel indexes
"""
return np.arange(j0, j1)
def get_r_values(self, i0, i1, j0, j1, flag_circle=False):
"""Get radial values from pixel indexes
Args:
i0: First index
i1: Second index
j0: Third index
j1: Fourth index
flag_circle: Flag circle (Default value = False)
Returns:
Radial values corresponding to the given pixel indexes
"""
return self.get_x_values(i0, i1)
def _recompute_log_data(self) -> None:
"""Refresh the cached log10 data from the current ``self.data``.
Used both when toggling the Z-axis log scale on and when the underlying
data is replaced (e.g. via :meth:`set_data`) while the log scale is
already active.
Values lower than or equal to zero have no logarithm: they are replaced
by the smallest positive value of the data (the "log floor", or 1.0 if
there is no positive value), so that they are shown with the lowest
color of the colormap. NaN values are kept.
"""
data = np.asarray(self.data)
with np.errstate(invalid="ignore"):
positive = data[data > 0]
self._log_floor = float(positive.min()) if positive.size else 1.0
with np.errstate(invalid="ignore", divide="ignore"):
self._log_data = np.log10(
np.maximum(data, self._log_floor, dtype=np.float64)
)
def _get_display_data(self) -> np.ndarray:
"""Return the data to which the LUT is applied when drawing the image
Returns:
Base-10 logarithm of the data if the Z-axis log scale is enabled,
the data itself otherwise
"""
if self._is_zaxis_log:
return self._log_data
return self.data
def _to_lut_space(self, values: np.ndarray) -> np.ndarray:
"""Convert data values to the space in which the LUT is applied
Args:
values: Data values
Returns:
Base-10 logarithm of the values (see :meth:`_recompute_log_data` for
values lower than or equal to zero) if the Z-axis log scale is enabled,
the values themselves otherwise
"""
if self._is_zaxis_log:
with np.errstate(invalid="ignore", divide="ignore"):
return np.log10(np.maximum(values, self._log_floor, dtype=np.float64))
return values
def set_data(
self, data: np.ndarray, lut_range: tuple[float, float] | None = None
) -> None:
"""Set image data
Args:
data: 2D NumPy array
lut_range: LUT range -- tuple (levelmin, levelmax), in data units, even
when the Z-axis log scale is enabled (Default value = None)
"""
self.data = data
self.histogram_cache = None
self.update_bounds()
self.update_border()
# Refresh the cached log10 data when log scale is active, otherwise the
# display would keep using the previous (now stale) log data.
if self._is_zaxis_log:
self._recompute_log_data()
# The new data may have another data type than the previous one
self._sync_interpolation_dtype()
if not self.param.keep_lut_range:
if self._is_zaxis_log:
# The linear LUT range, restored when the log scale is disabled,
# is updated as it would have been without the log scale
self._lin_lut_range = (
get_nan_range(data) if lut_range is None else tuple(lut_range)
)
if lut_range is None:
lut_range = self.get_lut_range_full()
self.set_lut_range(lut_range)
def get_data(
self, x0: float, y0: float, x1: float | None = None, y1: float | None = None
) -> float | tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Get image data
Args:
x0: X coordinate of first point
y0: Y coordinate of first point
x1: X coordinate of second point (Default value = None)
y1: Y coordinate of second point (Default value = None)
Returns:
Image level, or image levels in rectangular area (x0,y0,x1,y1)
as a tuple (x, y, data) of arrays
"""
i0, j0 = self.get_closest_indexes(x0, y0)
if x1 is None or y1 is None:
return self.data[j0, i0]
else:
i1, j1 = self.get_closest_indexes(x1, y1)
i1 += 1
j1 += 1
return (
self.get_x_values(i0, i1),
self.get_y_values(j0, j1),
self.data[j0:j1, i0:i1],
)
def get_closest_coordinates(self, x: float, y: float) -> tuple[float, float]:
"""
Get the closest coordinates to the given point
Args:
x: X coordinate
y: Y coordinate
Returns:
tuple[float, float]: Closest coordinates
"""
return self.get_closest_indexes(x, y)
def get_coordinates_label(self, x: float, y: float) -> str:
"""
Get the coordinates label for the given coordinates
Args:
x: X coordinate
y: Y coordinate
Returns:
str: Coordinates label
"""
title = self.title().text()
z = self.get_data(x, y)
zstr = "--" if z is np.ma.masked else f"{z:g}"
return f"{title}:<br>x = {int(x):d}<br>y = {int(y):d}<br>z = {zstr}"
def set_background_color(self, qcolor: QColor | str) -> None:
"""Set background color
Args:
qcolor: Background color
"""
# mask = np.uint32(255*self.param.alpha+0.5).clip(0,255) << 24
self.bg_qcolor = qcolor
a, b, _bg, cmap = self.lut
if qcolor is None:
self.lut = (a, b, None, cmap)
else:
self.lut = (a, b, np.uint32(QG.QColor(qcolor).rgb() & 0xFFFFFF), cmap)
def set_color_map(
self, name_or_table: str | EditableColormap, invert: bool | None = None
) -> None:
"""Set colormap
Args:
name_or_table: Colormap name or colormap
invert: True to invert colormap, False otherwise (Default value = None,
i.e. do not change the default behavior)
"""
if name_or_table is self.cmap_table:
# This avoids rebuilding the LUT all the time
return
if isinstance(name_or_table, str):
table = get_cmap(name_or_table)
else:
table = name_or_table
if invert is not None:
table.invert = invert
self.cmap_table = table
colors, lut = _get_colormap_lut(
table, self.param.alpha, self.param.alpha_function
)
self.cmap = list(colors)
self.lut[3][:] = lut
plot = self.plot()
if plot:
plot.update_colormap_axis(self)
def get_color_map(self) -> EditableColormap | None:
"""Get colormap
Returns:
Colormap
"""
return self.cmap_table
def set_interpolation(self, interp_mode: int, size: int | None = None) -> None:
"""Set interpolation mode
Args:
interp_mode: INTERP_NEAREST, INTERP_LINEAR, INTERP_AA
size: (for anti-aliasing only) AA matrix size (Default value = None)
"""
if interp_mode in (INTERP_NEAREST, INTERP_LINEAR):
self.interpolate = (interp_mode,)
if interp_mode == INTERP_AA:
# The kernel must have the same data type as the data drawn
aa = np.ones((size, size), self._get_display_data().dtype)
self.interpolate = (interp_mode, aa)
def get_interpolation(self) -> tuple[int] | tuple[int, np.ndarray]:
"""Get interpolation mode"""
return self.interpolate
def _get_interpolation_for(
self, data: np.ndarray
) -> tuple[int] | tuple[int, np.ndarray]:
"""Return the interpolation mode to be used to scale the given data
The scaling functions require the anti-aliasing kernel to have the data
type of the data they scale, which is not always the data drawn (e.g. the
raw data, exported without the LUT, instead of its logarithm drawn with
the Z-axis logarithmic scale).
Args:
data: Data to be scaled
Returns:
Interpolation mode, with an anti-aliasing kernel of the data type of
the given data
"""
interp = self.interpolate
if interp[0] == INTERP_AA and interp[1].dtype != data.dtype:
interp = (INTERP_AA, interp[1].astype(data.dtype))
return interp
def _sync_interpolation_dtype(self) -> None:
"""Give the anti-aliasing kernel the data type of the data drawn"""
if self.data is not None:
self.interpolate = self._get_interpolation_for(self._get_display_data())
def set_lut_range(self, lut_range: tuple[float, float]) -> None:
"""
Set the current active lut range
Args:
lut_range: Lut range, tuple(min, max), in data units (even when the
Z-axis log scale is enabled: values lower than or equal to zero are
then replaced by the smallest positive value of the data)
Example:
>>> item.set_lut_range((0.0, 1.0))
"""
vmin, vmax = lut_range
if self._is_zaxis_log:
if vmax <= 0:
vmax = self._log_floor
if vmin <= 0:
vmin = min(self._log_floor, vmax)
self.min, self.max = vmin, vmax
_a, _b, bg, cmap = self.lut
if self._is_zaxis_log:
lmin, lmax = np.log10(float(vmin)), np.log10(float(vmax))
else:
lmin, lmax = self.min, self.max
if lmax == lmin:
self.lut = (LUT_MAX, lmin, bg, cmap)
else:
fmin, fmax = float(lmin), float(lmax) # avoid overflows
self.lut = (
LUT_MAX / (fmax - fmin),
-LUT_MAX * fmin / (fmax - fmin),
bg,
cmap,
)
def get_lut_range(self) -> tuple[float, float]:
"""Get the current active lut range
Returns:
tuple[float, float]: Lut range, tuple(min, max), in data units
"""
return self.min, self.max
def set_lut_threshold(self, threshold: float) -> None:
"""Set lut threshold value, eliminating the given percent of the histogram
Args:
threshold: Lut threshold value
"""
self.set_lut_range(lut_range_threshold(self, 256, threshold))
def get_lut_range_full(self) -> tuple[float, float]:
"""Return full dynamic range
Returns:
tuple[float, float]: Lut range, tuple(min, max), in data units. When the
Z-axis log scale is enabled, the minimum is the smallest positive value
of the data.
"""
vmin, vmax = get_nan_range(self.data)
if self._is_zaxis_log:
return self._log_floor, max(vmax, self._log_floor)
return vmin, vmax
# ---- Z-axis logarithmic scale --------------------------------------------
def supports_zaxis_log(self) -> bool:
"""Return True if the item supports the Z-axis logarithmic scale
Items which do not support it (e.g. RGB images, which have no colormap)
are ignored by :class:`.ZAxisLogTool`, and :meth:`set_zaxis_log_state`
has no effect on them.
"""
return self._ZAXIS_LOG_SUPPORTED
def get_zaxis_log_state(self) -> bool:
"""Return True if Z-axis is in logarithmic scale"""
return self._is_zaxis_log
def set_zaxis_log_state(self, state: bool) -> None:
"""Set Z-axis logarithmic scale state
With the logarithmic scale, the colors are mapped to the base-10 logarithm
of the data, whereas the LUT range (see :meth:`get_lut_range`), the color
bar, the contrast adjustment panel and the cursor values remain in data
units. Values lower than or equal to zero are shown with the lowest color
of the colormap.
Enabling the logarithmic scale sets the LUT range to the full range of the
positive values of the data; disabling it restores the previous LUT range.
Args:
state: True to enable logarithmic scale, False otherwise
"""
state = bool(state)
if not self.supports_zaxis_log() or state == self._is_zaxis_log:
return
if state:
self._lin_lut_range = self.get_lut_range()
self._is_zaxis_log = True
if self.data is not None:
self._recompute_log_data()
self.set_lut_range(self.get_lut_range_full())
else:
self._is_zaxis_log = False
self._log_data = None
self.set_lut_range(self._lin_lut_range)
self._sync_interpolation_dtype()
plot = self.plot()
if plot is not None:
plot.update_colormap_axis(self)
def get_lut_range_max(self) -> tuple[float, float]:
"""Get maximum range for this dataset
Returns:
tuple[float, float]: Lut range, tuple(min, max)
"""
kind = self.data.dtype.kind
if kind in np.typecodes["AllFloat"]:
info = np.finfo(self.data.dtype)
else:
info = np.iinfo(self.data.dtype)
return info.min, info.max
def update_bounds(self) -> None:
"""Update image bounds to fit image shape"""
if self.data is None:
return
self.bounds = QC.QRectF(0, 0, self.data.shape[1], self.data.shape[0])
def update_border(self) -> None:
"""Update image border rectangle to fit image shape"""
bounds = self.boundingRect().getCoords()
self.border_rect.set_rect(*bounds)
def draw_border(
self,
painter: QPainter,
xMap: qwt.scale_map.QwtScaleMap,
yMap: qwt.scale_map.QwtScaleMap,
canvasRect: QRectF,
) -> None:
"""Draw image border rectangle
Args:
painter: Painter
xMap: X axis scale map
yMap: Y axis scale map
canvasRect: Canvas rectangle
"""
self.border_rect.draw(painter, xMap, yMap, canvasRect)
def _has_linear_scales(self) -> bool:
"""Return True if the image axes of the plot have linear scales
Returns:
True if linear scales
"""
plot: BasePlot = self.plot()
return isinstance(
plot.axisScaleEngine(plot.X_BOTTOM), QwtLinearScaleEngine
) and isinstance(plot.axisScaleEngine(plot.Y_LEFT), QwtLinearScaleEngine)
def warn_if_non_linear_scale(self, painter: QPainter, canvasRect: QRectF) -> bool:
"""Warn if non-linear scale
Args:
painter: Painter
canvasRect: Canvas rectangle
Returns:
True if non-linear scale
"""
if not self._has_linear_scales():
painter.setPen(QC.Qt.red)
painter.drawText(
canvasRect,
QC.Qt.AlignCenter,
_("Non-linear scales are not supported for image items"),
)
return True
return False
@reusable_rendering
def draw_image(
self,
painter: QPainter,
canvasRect: QRectF,
src_rect: tuple[float, float, float, float],
dst_rect: tuple[float, float, float, float],
xMap: qwt.scale_map.QwtScaleMap,
yMap: qwt.scale_map.QwtScaleMap,
) -> None:
"""Draw image
Args:
painter: Painter
canvasRect: Canvas rectangle
src_rect: Source rectangle
dst_rect: Destination rectangle
xMap: X axis scale map
yMap: Y axis scale map
"""
if self.warn_if_non_linear_scale(painter, canvasRect):
return
dest = _scale_rect(
self._get_display_data(),
src_rect,
self._offscreen,
self._offscreen_rect(dst_rect),
self.lut,
self.interpolate,
)
self._draw_offscreen(painter, dest)
def _offscreen_rect(
self, rect: tuple[float, float, float, float]
) -> tuple[int, int, int, int]:
"""Convert a rectangle from canvas coordinates to offscreen image pixels
Args:
rect: Rectangle (x1, y1, x2, y2), in canvas coordinates
Returns:
View remainder of file in raw view
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.