/
_figure.py
2624 lines (2306 loc) · 97.2 KB
/
_figure.py
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
import csv
import logging
import os
import sys
import textwrap
import uuid
import centrosome.cpmorphology
import centrosome.outline
import matplotlib
import matplotlib.axes
import matplotlib.backend_bases
import matplotlib.backends.backend_wxagg
import matplotlib.cm
import matplotlib.collections
import matplotlib.colorbar
import matplotlib.colors
import matplotlib.gridspec
import matplotlib.image
import matplotlib.patches
import matplotlib.pyplot
import matplotlib.transforms
import matplotlib.widgets
import numpy
import numpy.ma
import scipy.ndimage
import scipy.sparse
import skimage.exposure
import wx
import wx.grid
import wx.lib.intctrl
import wx.lib.masked
from cellprofiler_core.preferences import INTENSITY_MODE_GAMMA
from cellprofiler_core.preferences import INTENSITY_MODE_LOG
from cellprofiler_core.preferences import INTENSITY_MODE_RAW
from cellprofiler_core.preferences import get_default_colormap
from cellprofiler_core.preferences import get_intensity_mode
from cellprofiler_core.preferences import get_next_cpfigure_position
from cellprofiler_core.preferences import get_normalization_factor
from cellprofiler_core.preferences import get_primary_outline_color
from cellprofiler_core.preferences import get_secondary_outline_color
from cellprofiler_core.preferences import get_tertiary_outline_color
from cellprofiler_core.preferences import get_title_font_name
from cellprofiler_core.preferences import get_title_font_size
from cellprofiler_core.utilities.core.object import overlay_labels
from ._navigation_toolbar import NavigationToolbar
from ._outline_artist import OutlineArtist
from ..artist import CPImageArtist
from ..constants.figure import COLOR_NAMES
from ..constants.figure import CPLDM_ALPHA
from ..constants.figure import CPLDM_LINES
from ..constants.figure import CPLDM_NONE
from ..constants.figure import CPLDM_OUTLINES
from ..constants.figure import CPLD_ALPHA_COLORMAP
from ..constants.figure import CPLD_ALPHA_VALUE
from ..constants.figure import CPLD_LABELS
from ..constants.figure import CPLD_LINE_WIDTH
from ..constants.figure import CPLD_MODE
from ..constants.figure import CPLD_NAME
from ..constants.figure import CPLD_OUTLINE_COLOR
from ..constants.figure import CPLD_SHOW
from ..constants.figure import EVT_NAV_MODE_CHANGE
from ..constants.figure import MATPLOTLIB_FILETYPES
from ..constants.figure import MATPLOTLIB_UNSUPPORTED_FILETYPES
from ..constants.figure import MENU_CLOSE_ALL
from ..constants.figure import MENU_CLOSE_WINDOW
from ..constants.figure import MENU_FILE_SAVE
from ..constants.figure import MENU_FILE_SAVE_TABLE
from ..constants.figure import MENU_LABELS_ALPHA
from ..constants.figure import MENU_LABELS_LINES
from ..constants.figure import MENU_LABELS_OFF
from ..constants.figure import MENU_LABELS_OUTLINE
from ..constants.figure import MENU_LABELS_OVERLAY
from ..constants.figure import MENU_RGB_CHANNELS
from ..constants.figure import MENU_SAVE_SUBPLOT
from ..constants.figure import MENU_TOOLS_MEASURE_LENGTH
from ..constants.figure import MODE_MEASURE_LENGTH
from ..constants.figure import MODE_NONE
from ..constants.figure import NAV_MODE_NONE
from ..constants.figure import WINDOW_IDS
from ..constants.figure import MENU_INTERPOLATION_NEAREST
from ..constants.figure import MENU_INTERPOLATION_BILINEAR
from ..constants.figure import MENU_INTERPOLATION_BICUBIC
from ..help import make_help_menu
from ..help.content import FIGURE_HELP
from ..tools import renumber_labels_for_display
from ..utilities.figure import allow_sharexy
from ..utilities.figure import close_all
from ..utilities.figure import create_or_find
from ..utilities.figure import find_fig
from ..utilities.figure import format_plate_data_as_array
from ..utilities.figure import get_matplotlib_interpolation_preference
from ..utilities.figure import get_menu_id
from ..utilities.figure import match_rgbmask_to_image
from ..utilities.figure import wraparound
from ..utilities.icon import get_cp_icon
LOGGER = logging.getLogger(__name__)
for filetype in matplotlib.backends.backend_wxagg.FigureCanvasWxAgg.filetypes:
if filetype not in MATPLOTLIB_FILETYPES:
MATPLOTLIB_UNSUPPORTED_FILETYPES.append(filetype)
for filetype in MATPLOTLIB_UNSUPPORTED_FILETYPES:
del matplotlib.backends.backend_wxagg.FigureCanvasWxAgg.filetypes[filetype]
class Figure(wx.Frame):
"""A wx.Frame with a figure inside"""
def __init__(
self,
parent=None,
identifier=-1,
title="",
pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.DEFAULT_FRAME_STYLE,
name=wx.FrameNameStr,
subplots=None,
on_close=None,
secret_panel_class=None,
help_menu_items=FIGURE_HELP,
):
"""Initialize the frame:
parent - parent window to this one, typically CPFrame
id - window ID
title - title in title bar
pos - 2-tuple position on screen in pixels
size - 2-tuple size of frame in pixels
style - window style
name - searchable window name
subplots - 2-tuple indicating the layout of subplots inside the window
on_close - a function to run when the window closes
secret_panel_class - class to use to construct the secret panel
help_menu_items - menu items to place in the help menu
"""
if pos == wx.DefaultPosition:
pos = get_next_cpfigure_position()
super(Figure, self).__init__(parent, identifier, title, pos, size, style, name)
self.close_fn = on_close
self.mouse_mode = MODE_NONE
self.length_arrow = None
self.table = None
self.current_plane = 0
self.images = {}
self.colorbar = {}
self.volumetric = False
self.subplot_params = {}
self.subplot_user_params = {}
self.event_bindings = {}
self.popup_menus = {}
self.subplot_menus = {}
self.widgets = []
self.mouse_down = None
self.many_plots = False
self.remove_menu = []
self.figure = matplotlib.pyplot.Figure(constrained_layout=True)
self.figure.set_constrained_layout_pads(
w_pad=0.1, h_pad=0.05, wspace=0, hspace=0
)
self.panel = matplotlib.backends.backend_wxagg.FigureCanvasWxAgg(
self, -1, self.figure
)
self.__gridspec = None
self.dimensions = 2
if secret_panel_class is None:
secret_panel_class = wx.Panel
self.secret_panel = secret_panel_class(self)
self.secret_panel.Hide()
self.status_bar = self.CreateStatusBar()
self.Bind(wx.EVT_CLOSE, self.on_close)
self.Bind(wx.EVT_SIZE, self.on_size)
if subplots:
self.subplots = numpy.zeros(subplots, dtype=object)
self.create_menu(help_menu_items)
self.create_toolbar()
self.figure.canvas.mpl_connect("button_press_event", self.on_button_press)
self.figure.canvas.mpl_connect("motion_notify_event", self.on_mouse_move)
self.figure.canvas.mpl_connect("button_release_event", self.on_button_release)
self.figure.canvas.mpl_connect("resize_event", self.on_resize)
try:
self.SetIcon(get_cp_icon())
except:
pass
if size == wx.DefaultSize:
self.panel.SetInitialSize(wx.Size(640, 480))
self.panel.SetMinSize(wx.Size(320, 240))
self.Fit()
else:
self.Layout()
self.Show()
if sys.platform.lower().startswith("win"):
try:
parent_menu_bar = parent.MenuBar
except:
# when testing, there may be no parent
parent_menu_bar = None
if parent_menu_bar is not None and isinstance(parent_menu_bar, wx.MenuBar):
for menu, label in parent_menu_bar.GetMenus():
if "Window" in label:
menu_ids = [menu_item.Id for menu_item in menu.MenuItems]
for window_id in WINDOW_IDS + [None]:
if window_id not in menu_ids:
break
if window_id is None:
window_id = wx.NewId()
WINDOW_IDS.append(window_id)
assert isinstance(menu, wx.Menu)
menu.Append(window_id, title)
def on_menu_command(event):
self.Raise()
parent.Bind(wx.EVT_MENU, on_menu_command, id=window_id)
self.remove_menu.append([menu, window_id])
def create_menu(self, figure_help=FIGURE_HELP):
self.MenuBar = wx.MenuBar()
self.__menu_file = wx.Menu()
self.__menu_file.Append(MENU_FILE_SAVE, "&Save")
self.__menu_file.Append(MENU_FILE_SAVE_TABLE, "&Save table")
self.__menu_file.Enable(MENU_FILE_SAVE_TABLE, False)
self.Bind(wx.EVT_MENU, self.on_file_save, id=MENU_FILE_SAVE)
self.Bind(wx.EVT_MENU, self.on_file_save_table, id=MENU_FILE_SAVE_TABLE)
self.MenuBar.Append(self.__menu_file, "&File")
self.menu_subplots = wx.Menu()
self.MenuBar.Append(self.menu_subplots, "Subplots")
self.Bind(wx.EVT_MENU, self.on_measure_length, id=MENU_TOOLS_MEASURE_LENGTH)
# work around mac window menu losing bindings
if wx.Platform == "__WXMAC__":
hidden_menu = wx.Menu()
hidden_menu.Append(MENU_CLOSE_ALL, "&L")
self.Bind(
wx.EVT_MENU, lambda evt: close_all(self.Parent), id=MENU_CLOSE_ALL
)
accelerators = wx.AcceleratorTable(
[
(wx.ACCEL_CMD, ord("W"), MENU_CLOSE_WINDOW),
(wx.ACCEL_CMD, ord("L"), MENU_CLOSE_ALL),
]
)
else:
accelerators = wx.AcceleratorTable(
[(wx.ACCEL_CMD, ord("W"), MENU_CLOSE_WINDOW)]
)
self.SetAcceleratorTable(accelerators)
self.Bind(wx.EVT_MENU, self.on_close, id=MENU_CLOSE_WINDOW)
self.MenuBar.Append(make_help_menu(figure_help, self), "&Help")
def create_toolbar(self):
self.navtoolbar = NavigationToolbar(self.figure.canvas, want_measure=True)
self.navtoolbar.Bind(EVT_NAV_MODE_CHANGE, self.on_navtool_changed)
def clf(self):
"""Clear the figure window, resetting the display"""
self.figure.clf()
if hasattr(self, "subplots"):
self.subplots[:, :] = None
# Remove the subplot menus
for (x, y) in self.subplot_menus:
self.menu_subplots.Remove(self.subplot_menus[(x, y)])
for (x, y) in self.event_bindings:
[self.figure.canvas.mpl_disconnect(b) for b in self.event_bindings[(x, y)]]
self.subplot_menus = {}
self.subplot_params = {}
self.subplot_user_params = {}
self.colorbar = {}
self.images = {}
for x, y, width, height, halign, valign, ctrl in self.widgets:
ctrl.Destroy()
self.widgets = []
def on_resize(self, event):
"""Handle mpl_connect('resize_event')"""
assert isinstance(event, matplotlib.backend_bases.ResizeEvent)
for x, y, width, height, halign, valign, ctrl in self.widgets:
self.align_widget(
ctrl, x, y, width, height, halign, valign, event.width, event.height
)
ctrl.ForceRefresh() # I don't know why, but it seems to be needed.
@staticmethod
def align_widget(
ctrl, x, y, width, height, halign, valign, canvas_width, canvas_height
):
"""Align a widget within the canvas
ctrl - the widget to be aligned
x, y - the fractional position (0 <= {x,y} <= 1) of the top-left of the
allotted space for the widget
width, height - the fractional width and height of the allotted space
halign, valign - alignment of the widget if its best size is smaller
than the space (wx.ALIGN_xx or wx.EXPAND)
canvas_width, canvas_height - the width and height of the canvas parent
"""
assert isinstance(ctrl, wx.Window)
x = x * canvas_width
y = y * canvas_height
width = width * canvas_width
height = height * canvas_height
best_width, best_height = ctrl.GetBestSize()
vscroll_x = wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X)
hscroll_y = wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y)
if height < best_height:
#
# If the control's ideal height is less than what's allowed
# then we have to account for the scroll bars
#
best_width += vscroll_x
if width < best_width:
best_height += hscroll_y
if height > best_height and valign != wx.EXPAND:
if valign == wx.ALIGN_BOTTOM:
y = y + height - best_height
height = best_height
elif valign in (wx.ALIGN_CENTER, wx.ALIGN_CENTER_VERTICAL):
y += (height - best_height) / 2
height = best_height
if width > best_width:
if halign == wx.ALIGN_RIGHT:
x = x + width - best_width
elif halign in (wx.ALIGN_CENTER, wx.ALIGN_CENTER_VERTICAL):
x += (width - best_width) / 2
width = best_width
ctrl.SetPosition(wx.Point(x, y))
ctrl.SetSize(wx.Size(width, height))
def on_size(self, event):
"""Handle resizing of canvas, bars and secret panel
Sizers have proven to be too unpredictable and useless. So
we do it manually here. Reinventing the wheel is so much quicker
and works much better.
"""
if any([not hasattr(self, bar) for bar in ("navtoolbar", "status_bar")]):
return
available_width, available_height = self.GetClientSize()
nbheight = self.navtoolbar.GetSize()[1]
# On some operating systems (specifically Ubuntu), the matplotlib toolbar
# may not render with an appropriate height. This is the result of creating
# the navtoolbar without an appropriate slider. Until this is refactored
# to make it size properly, this check ensures the navtoolbar at least appears.
# https://github.com/CellProfiler/CellProfiler/issues/2679
if nbheight < 40:
nbheight = 40
self.navtoolbar.SetPosition((0, 0))
self.navtoolbar.SetSize((available_width, nbheight))
if self.secret_panel.IsShown():
sp_width = self.secret_panel.GetVirtualSize()[0]
canvas_width = min(
max(available_width - sp_width, 250), available_width - 100
)
sp_width = available_width - canvas_width
self.secret_panel.SetPosition((canvas_width, nbheight))
self.secret_panel.SetSize((sp_width, available_height - nbheight))
self.secret_panel.Layout()
self.secret_panel.SetupScrolling()
self.secret_panel.ClearBackground()
self.secret_panel.Refresh()
for kid in self.secret_panel.GetChildren():
kid.Refresh()
kid.Update()
else:
canvas_width = available_width
self.panel.SetPosition((0, nbheight))
self.panel.SetSize((canvas_width, available_height - nbheight))
self.ClearBackground()
def on_close(self, event):
if self.close_fn is not None:
self.close_fn(event)
self.clf() # Free memory allocated by imshow
for menu, menu_id in self.remove_menu:
self.Parent.Unbind(wx.EVT_MENU, id=menu_id)
menu.Delete(menu_id)
self.Destroy()
def on_navtool_changed(self, event):
if event.EventObject.mode == "measure":
self.on_measure_length(event)
elif self.mouse_mode == MODE_MEASURE_LENGTH:
self.mouse_mode = MODE_NONE
def on_measure_length(self, event):
"""Measure length menu item selected."""
if self.mouse_mode == MODE_NONE:
self.mouse_mode = MODE_MEASURE_LENGTH
else:
self.mouse_mode = MODE_NONE
self.navtoolbar.cancel_mode()
self.Layout()
def on_button_press(self, event):
if not hasattr(self, "subplots"):
return
if event.inaxes in self.subplots.flatten() or self.dimensions == 3:
if event.xdata is not None:
self.mouse_down = (event.xdata, event.ydata)
else:
self.mouse_down = None
if self.mouse_mode == MODE_MEASURE_LENGTH:
self.on_measure_length_mouse_down(event)
def on_measure_length_mouse_down(self, event):
pass
def on_mouse_move(self, evt):
if self.mouse_down is None:
x0 = evt.xdata
x1 = evt.xdata
y0 = evt.ydata
y1 = evt.ydata
else:
x0 = min(self.mouse_down[0], evt.xdata or self.mouse_down[0])
x1 = max(self.mouse_down[0], evt.xdata or self.mouse_down[0])
y0 = min(self.mouse_down[1], evt.ydata or self.mouse_down[1])
y1 = max(self.mouse_down[1], evt.ydata or self.mouse_down[1])
if self.mouse_mode == MODE_MEASURE_LENGTH:
self.on_mouse_move_measure_length(evt, x0, y0, x1, y1)
else:
self.on_mouse_move_show_pixel_data(evt, x0, y0, x1, y1)
def get_pixel_data_fields_for_status_bar(self, image, xi, yi):
fields = []
is_float = True
x, y = [int(round(xy)) for xy in (xi, yi)]
if not self.in_bounds(image, x, y):
return fields
if numpy.issubdtype(image.dtype, numpy.integer):
is_float = False
if image.dtype.type == numpy.uint8:
image = image.astype(numpy.float32) / 255.0
if image.ndim == 2:
if is_float:
fields += ["Intensity: {:.4f}".format(image[y, x] or 0)]
# This is to allow intensity values to be displayed more intuitively
else:
fields += ["Intensity: {:d}".format(image[y, x] or 0)]
elif image.ndim == 3 and image.shape[2] == 3:
fields += [
"Red: %.4f" % (image[y, x, 0]),
"Green: %.4f" % (image[y, x, 1]),
"Blue: %.4f" % (image[y, x, 2]),
]
elif image.ndim == 3:
fields += [
"Channel %d: %.4f" % (idx + 1, image[y, x, idx])
for idx in range(image.shape[2])
]
return fields
@staticmethod
def in_bounds(image, xi, yi):
"""Return false if xi or yi are outside of the bounds of the image"""
return not (
image is None
or xi >= image.shape[1]
or yi >= image.shape[0]
or xi < 0
or yi < 0
)
def on_mouse_move_measure_length(self, event, x0, y0, x1, y1):
# Get the fields later populated in the statusbar
fields = None
if event.xdata and event.ydata:
xi = int(event.xdata + 0.5)
yi = int(event.ydata + 0.5)
fields = self.get_fields(event, yi, xi, x1)
else:
# Mouse has moved off the plot, stop updating.
return
# Calculate the length field if mouse is down
if self.mouse_down is not None:
x0 = min(self.mouse_down[0], event.xdata)
x1 = max(self.mouse_down[0], event.xdata)
y0 = min(self.mouse_down[1], event.ydata)
y1 = max(self.mouse_down[1], event.ydata)
length = numpy.sqrt((x0 - x1) ** 2 + (y0 - y1) ** 2)
fields.append("Length: %.1f" % length)
xinterval = event.inaxes.xaxis.get_view_interval()
yinterval = event.inaxes.yaxis.get_view_interval()
diagonal = numpy.sqrt(
(xinterval[1] - xinterval[0]) ** 2 + (yinterval[1] - yinterval[0]) ** 2
)
mutation_scale = max(min(int(length * 100 / diagonal), 20), 1)
if self.length_arrow is not None:
self.length_arrow.set_positions(
(self.mouse_down[0], self.mouse_down[1]), (event.xdata, event.ydata)
)
self.length_arrow.set_mutation_scale(mutation_scale)
else:
self.length_arrow = matplotlib.patches.FancyArrowPatch(
(self.mouse_down[0], self.mouse_down[1]),
(event.xdata, event.ydata),
edgecolor="blue",
arrowstyle="<->",
mutation_scale=mutation_scale,
)
try:
event.inaxes.add_patch(self.length_arrow)
except:
self.length_arrow = None
self.figure.canvas.draw()
self.Refresh()
# Update the statusbar
if fields:
self.status_bar.SetFieldsCount(len(fields))
for idx, field in enumerate(fields):
self.status_bar.SetStatusText(field, i=idx)
else:
self.status_bar.SetFieldsCount(1)
self.status_bar.SetStatusText("")
def get_fields(self, event, yi, xi, x1):
"""Get the standard fields at the cursor location"""
if event.inaxes:
fields = ["X: %d" % xi, "Y: %d" % yi]
if self.dimensions >= 2:
im = self.find_image_for_axes(event.inaxes)
else: # self.dimensions == 3
axes = event.inaxes
axes_image_list = axes.get_images()
if len(axes_image_list):
axes_image = axes_image_list[0]
fields += ["Z: {}".format(axes.get_label())]
im = axes_image.get_array().data
else:
im = None
if im is not None:
fields += self.get_pixel_data_fields_for_status_bar(im, x1, yi)
elif isinstance(event.inaxes, matplotlib.axes.Axes):
for artist in event.inaxes.artists:
if isinstance(artist, CPImageArtist):
fields += [
"%s: %.4f" % (k, v)
for k, v in list(artist.get_channel_values(xi, yi).items())
]
else:
fields = []
return fields
def on_mouse_move_show_pixel_data(self, event, x0, y0, x1, y1):
# Get the fields later populated in the statusbar
fields = None
if event.xdata and event.ydata:
xi = int(event.xdata + 0.5)
yi = int(event.ydata + 0.5)
fields = self.get_fields(event, yi, xi, x1)
# Update the statusbar
if fields:
self.status_bar.SetFieldsCount(len(fields))
for idx, field in enumerate(fields):
self.status_bar.SetStatusText(field, i=idx)
else:
self.status_bar.SetFieldsCount(1)
self.status_bar.SetStatusText("")
def find_image_for_axes(self, axes):
for i, sl in enumerate(self.subplots):
for j, slax in enumerate(sl):
if axes == slax:
rtnimg = self.images.get((i, j), None)
if self.dimensions == 3 and rtnimg is not None:
rtnimg = rtnimg[self.current_plane, :, :]
return rtnimg
return None
def on_button_release(self, event):
if not hasattr(self, "subplots"):
return
if (
event.inaxes in self.subplots.flatten()
and self.mouse_down
and event.xdata is not None
):
x0 = min(self.mouse_down[0], event.xdata)
x1 = max(self.mouse_down[0], event.xdata)
y0 = min(self.mouse_down[1], event.ydata)
y1 = max(self.mouse_down[1], event.ydata)
if self.mouse_mode == MODE_MEASURE_LENGTH:
self.on_measure_length_done(event, x0, y0, x1, y1)
elif self.mouse_down:
if self.mouse_mode == MODE_MEASURE_LENGTH:
self.on_measure_length_canceled(event)
self.mouse_down = None
def on_measure_length_done(self, event, x0, y0, x1, y1):
self.on_measure_length_canceled(event)
def on_measure_length_canceled(self, event):
if self.length_arrow is not None:
self.length_arrow.remove()
self.length_arrow = None
self.figure.canvas.draw()
self.Refresh()
def on_file_save(self, event):
with wx.FileDialog(
self,
"Save figure",
wildcard="PDF file (*.pdf)|*.pdf|PNG image (*.png)|*.png",
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
) as dlg:
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
if dlg.FilterIndex == 1:
file_format = "png"
elif dlg.FilterIndex == 0:
file_format = "pdf"
elif dlg.FilterIndex == 2:
file_format = "tif"
elif dlg.FilterIndex == 3:
file_format = "jpg"
else:
file_format = "pdf"
if "." not in os.path.split(path)[1]:
path += "." + file_format
self.figure.savefig(path, format=file_format)
def on_file_save_table(self, event):
if self.table is None:
return
with wx.FileDialog(
self,
"Save table",
wildcard="Excel file (*.csv)|*.csv",
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
) as dlg:
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
with open(path, "w", newline="") as fd:
csv.writer(fd).writerows(self.table)
def on_file_save_subplot(self, event, x, y):
"""Save just the contents of a subplot w/o decorations
event - event generating the request
x, y - the placement of the subplot
"""
#
# Thank you Joe Kington
# http://stackoverflow.com/questions/4325733/save-a-subplot-in-matplotlib
#
ax = self.subplots[x, y]
extent = ax.get_window_extent().transformed(
self.figure.dpi_scale_trans.inverted()
)
with wx.FileDialog(
self,
"Save axes",
wildcard="PDF file (*.pdf)|*.pdf|Png image (*.png)|*.png|Postscript file (*.ps)|*.ps",
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
) as dlg:
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
if dlg.FilterIndex == 1:
file_format = "png"
elif dlg.FilterIndex == 0:
file_format = "pdf"
elif dlg.FilterIndex == 2:
file_format = "ps"
else:
file_format = "pdf"
self.figure.savefig(path, format=file_format, bbox_inches=extent)
def set_subplots(self, subplots, dimensions=2):
self.clf() # get rid of any existing subplots, menus, etc.
self.dimensions = dimensions
if max(subplots) > 3:
self.many_plots = True
if subplots is None:
if hasattr(self, "subplots"):
delattr(self, "subplots")
else:
if dimensions >= 2:
self.subplots = numpy.zeros(subplots, dtype=object)
self.__gridspec = matplotlib.gridspec.GridSpec(
subplots[1], subplots[0], figure=self.figure
)
else:
self.set_grids(subplots)
@allow_sharexy
def subplot(self, x, y, sharex=None, sharey=None):
"""Return the indexed subplot
x - column
y - row
sharex - If creating a new subplot, you can specify a subplot instance
here to share the X axis with. eg: for zooming, panning
sharey - If creating a new subplot, you can specify a subplot instance
here to share the Y axis with. eg: for zooming, panning
"""
if self.dimensions == 4:
return None
if not self.subplots[x, y]:
if self.__gridspec:
# Add the plot to a premade subplot layout
plot = self.figure.add_subplot(
self.__gridspec[y, x], sharex=sharex, sharey=sharey,
)
else:
rows, cols = self.subplots.shape
plot = self.figure.add_subplot(
cols, rows, x + y * rows + 1, sharex=sharex, sharey=sharey
)
self.subplots[x, y] = plot
return self.subplots[x, y]
def set_subplot_title(self, title, x, y):
"""Set a subplot's title in the standard format
title - title for subplot
x - subplot's column
y - subplot's row
"""
fontname = get_title_font_name()
if self.many_plots:
fontsize = 8
else:
fontsize = get_title_font_size()
self.subplot(x, y).set_title(
textwrap.fill(title, 30 if fontsize > 10 else 50), fontname=fontname, fontsize=fontsize,
)
def clear_subplot(self, x, y):
"""Clear a subplot of its gui junk. Noop if no subplot exists at x,y
x - subplot's column
y - subplot's row
"""
if not self.subplots[x, y]:
return
axes = self.subplot(x, y)
try:
del self.images[(x, y)]
del self.popup_menus[(x, y)]
except:
pass
axes.clear()
def show_imshow_popup_menu(self, pos, subplot_xy):
popup = self.get_imshow_menu(subplot_xy)
self.PopupMenu(popup, pos)
def get_imshow_menu(self, coordinates):
"""returns a menu corresponding to the specified subplot with items to:
- launch the image in a new cpfigure window
- Show image histogram
- Change contrast stretching
- Toggle channels on/off
Note: Each item is bound to a handler.
"""
(x, y) = coordinates
params = self.subplot_params[(x, y)]
# If no popup has been built for this subplot yet, then create one
popup = wx.Menu()
self.popup_menus[(x, y)] = popup
has_image = params["vmax"] is not None
open_in_new_figure_item = wx.MenuItem(popup, -1, "Open image in new window")
popup.Append(open_in_new_figure_item)
if has_image:
contrast_item = wx.MenuItem(popup, -1, "Adjust Contrast")
popup.Append(contrast_item)
show_hist_item = wx.MenuItem(popup, -1, "Show image histogram")
popup.Append(show_hist_item)
submenu = wx.Menu()
item_nearest = submenu.Append(
MENU_INTERPOLATION_NEAREST,
"Nearest neighbor",
"Use the intensity of the nearest image pixel when displaying "
"screen pixels at sub-pixel resolution. This produces a blocky "
"image, but the image accurately reflects the data.",
wx.ITEM_RADIO,
)
item_bilinear = submenu.Append(
MENU_INTERPOLATION_BILINEAR,
"Linear",
"Use the weighted average of the four nearest image pixels when "
"displaying screen pixels at sub-pixel resolution. This produces "
"a smoother, more visually appealing image, but makes it more "
"difficult to find pixel borders",
wx.ITEM_RADIO,
)
item_bicubic = submenu.Append(
MENU_INTERPOLATION_BICUBIC,
"Cubic",
"Perform a bicubic interpolation of the nearby image pixels when "
"displaying screen pixels at sub-pixel resolution. This produces "
"the most visually appealing image but is the least faithful to "
"the image pixel values.",
wx.ITEM_RADIO,
)
popup.Append(-1, "Interpolation", submenu)
save_subplot_id = get_menu_id(MENU_SAVE_SUBPLOT, (x, y))
popup.Append(
save_subplot_id,
"Save subplot",
"Save just the display portion of this subplot",
)
if params["interpolation"] == "bilinear":
item_bilinear.Check()
elif params["interpolation"] == "bicubic":
item_bicubic.Check()
else:
item_nearest.Check()
def open_image_in_new_figure(evt):
"""Callback for "Open image in new window" popup menu item """
# Store current zoom limits
xlims = self.subplot(x, y).get_xlim()
ylims = self.subplot(x, y).get_ylim()
new_title = self.subplot(x, y).get_title()
fig = create_or_find(
self, -1, new_title, subplots=(1, 1), name=str(uuid.uuid4())
)
fig.dimensions = self.dimensions
fig.subplot_imshow(0, 0, self.images[(x, y)], **params)
# XXX: Cheat here so the home button works.
# This needs to be fixed so it copies the view history for the
# launched subplot to the new figure.
fig.navtoolbar.push_current()
# Set current zoom
fig.subplot(0, 0).set_xlim(xlims[0], xlims[1])
fig.subplot(0, 0).set_ylim(ylims[0], ylims[1])
fig.figure.canvas.draw()
def show_hist(evt):
"""Callback for "Show image histogram" popup menu item"""
new_title = "%s %s image histogram" % (self.Title, (x, y))
fig = create_or_find(self, -1, new_title, subplots=(1, 1), name=new_title)
fig.subplot_histogram(
0, 0, self.images[(x, y)].flatten(), bins=200, xlabel="pixel intensity"
)
fig.figure.canvas.draw()
def open_contrast_dialog(evt):
nonlocal params
orig_params = params.copy()
id_dict = {
False: "Raw",
True: "Normalized",
"log": "Log Normalized",
"gamma": "Gamma Normalized",
}
if params["normalize"]:
maxval = 1
minval = 0
else:
imgmax = orig_params["vmax"]
imgmin = orig_params["vmin"]
maxval = max(1, imgmax)
minval = min(0, imgmin)
start_min = int((params["vmin"] / minval) * 255 if minval != 0 else 0)
start_max = int((params["vmax"] / maxval) * 255)
axes = self.subplot(x, y)
background = self.figure.canvas.copy_from_bbox(axes.bbox)
size = self.images[(x, y)].shape[:2]
axesdata = axes.plot([0, 0], list(size), "k")[0]
if sys.platform == "win32":
slider_flags = wx.SL_HORIZONTAL | wx.SL_MIN_MAX_LABELS
else:
slider_flags = wx.SL_HORIZONTAL
with wx.Dialog(
self, title="Adjust Contrast", size=wx.Size(250, 350)
) as dlg:
dlg.Sizer = wx.BoxSizer(wx.VERTICAL)
sizer = wx.BoxSizer(wx.VERTICAL)
dlg.Sizer.Add(sizer, 1, wx.EXPAND | wx.ALL, border=5)
sizer.Add(
wx.StaticText(dlg, label="Normalization Mode"), 0, wx.ALIGN_LEFT,
)
method_select = wx.ComboBox(
dlg,
id=2,
choices=list(id_dict.values()),
value=id_dict[params["normalize"]],
style=wx.CB_READONLY,
)
sizer.Add(method_select, flag=wx.ALL | wx.EXPAND, border=3)
sizer.Add(
wx.StaticText(dlg, label="Minimum Brightness"), 0, wx.ALIGN_LEFT,
)
slidermin = wx.Slider(
dlg,
id=0,
value=start_min,
minValue=0,
maxValue=255,
style=slider_flags,
name="Minimum Intensity",
)
sliderminbox = wx.lib.intctrl.IntCtrl(
dlg,
id=0,
value=start_min,
min=-999,
max=9999,
limited=True,
size=wx.Size(35, 22),
style=wx.TE_CENTRE,
)
minbright_sizer = wx.BoxSizer()
minbright_sizer.Add(slidermin, 1, wx.EXPAND)
minbright_sizer.AddSpacer(4)
minbright_sizer.Add(sliderminbox)
sizer.Add(minbright_sizer, 1, wx.EXPAND)
sizer.Add(
wx.StaticText(dlg, label="Maximum Brightness"), 0, wx.ALIGN_LEFT,
)
slidermax = wx.Slider(
dlg,
id=1,
value=start_max,
minValue=0,
maxValue=255,
style=slider_flags,
name="Maximum Intensity",
)
slidermaxbox = wx.lib.intctrl.IntCtrl(
dlg,