-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTkinter_Implementation.py
More file actions
1359 lines (1135 loc) · 55.8 KB
/
Tkinter_Implementation.py
File metadata and controls
1359 lines (1135 loc) · 55.8 KB
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 tkinter as tk
from tkinter import ttk, filedialog, messagebox
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
import tifffile as tiff
import matplotlib.pyplot as plt
from PIL import Image
import json
import os
import io
import gc
from threading import Thread
from queue import Queue
import mmap
from concurrent.futures import ThreadPoolExecutor
class DataInImage:
"""
Class for handling metadata of 3D figure properties.
"""
tag_dict = {
'Number_of_Layers': 'num_layers',
'Image_Height': 'height',
'Image_Width': 'width',
'X_Resolution': 'x_resolution',
'Y_Resolution': 'y_resolution',
'Z_Resolution': 'z_resolution',
'Resolution_Unit': 'resolution_unit',
'Volume': 'volume',
'Volume_unit': 'volume_unit',
'Surface': 'surface',
'Surface_unit': 'surface_unit',
'L': 'L',
'd': 'd',
'Spine_Color': 'spine_color',
'Connection_Point': 'point_connect',
'Spine_Middle_Point': 'point_middle',
'Spine_Far_Point': 'point_far',
'Connection_Is_Inner': 'point_connect_value',
'Description': 'description'
}
def __init__(self):
self.num_layers = None
self.height = None
self.width = None
self.x_resolution = None
self.y_resolution = None
self.z_resolution = None
self.resolution_unit = "nm"
self.volume = None
self.volume_unit = "um3"
self.surface = None
self.surface_unit = "um2"
self.L = None
self.d = None
self.spine_color = (255, 0, 0)
self.point_connect = (None, None, None)
self.point_middle = (None, None, None)
self.point_far = (None, None, None)
self.point_connect_value = None
self.description = None
def update(self, **kwargs):
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
else:
print(f"Attribute {key} not found in the class.")
def update_from_strings(self, attr_value_dict):
"""
Update attributes from a dictionary of strings, converting to the appropriate type.
"""
for attr, value_str in attr_value_dict.items():
if not hasattr(self, attr):
continue # Skip unknown attributes
# Determine the type of the attribute
current_value = getattr(self, attr)
attr_type = type(current_value)
if current_value is None:
# Assume default types based on attribute name
if attr in ['num_layers', 'height', 'width', 'point_connect_value']:
attr_type = int
elif attr in ['x_resolution', 'y_resolution', 'z_resolution', 'volume', 'surface', 'L', 'd']:
attr_type = float
elif attr in ['point_connect', 'point_middle', 'point_far', 'spine_color']:
attr_type = tuple
else:
attr_type = str
if attr_type is tuple:
# Handle tuples, e.g., "(1, 2, 3)"
try:
# Remove parentheses and split by comma
value = tuple(map(float, value_str.strip('()').split(',')))
# If original tuple contains ints, convert to ints
if all(isinstance(x, int) for x in current_value or []):
value = tuple(map(int, value))
except ValueError:
value = current_value # Keep original value if parsing fails
elif attr_type is int:
try:
value = int(float(value_str)) # Convert via float to handle inputs like "1.0"
except ValueError:
value = current_value # Keep original value if parsing fails
elif attr_type is float:
try:
value = float(value_str)
except ValueError:
value = current_value # Keep original value if parsing fails
else:
# Keep as string
value = value_str
setattr(self, attr, value)
def print_data(self):
data = self.tag_dict
for key, value in data.items():
print(f"{key}: {getattr(self, value)}")
class Estimator:
"""
Class that contains all the estimation functions.
Optimized for performance while maintaining the same calculation logic.
"""
def __init__(self, image_data, rgb_colors):
self.image_data = image_data
self.rgb_colors = rgb_colors
# Pre-calculate coordinates for reuse
self._coords_cache = {}
# Cache for common calculations
self._calculation_cache = {}
def run_estimations(self, spine_number, data_in_spine):
"""
Run estimations for the selected color and populate all fields in DataInImage.
"""
# Clear caches for new spine
self._coords_cache = {}
self._calculation_cache = {}
data_in_spine.spine_color = self.rgb_colors[spine_number]
self.generate_estimations(spine_number, data_in_spine)
return data_in_spine
def generate_estimations(self, spine_number, data_in_spine):
"""
Generate estimations for the given spine number.
Optimized to minimize redundant calculations.
"""
# Set the color of the spine
self.set_spine_color(spine_number, data_in_spine)
# Extract the mask and subvolume - cached for reuse
mask, spine_3D = self.extract_spine_mask(spine_number)
if mask is None or spine_3D is None:
print(f"No voxels found for spine number {spine_number}")
return data_in_spine
# Calculate dimensions using cached coordinates
self.calculate_dimensions(mask, data_in_spine)
# Cache resolution estimate as it's used multiple times
resolution_estimate = self.estimate_resolution(data_in_spine)
self._calculation_cache['resolution_estimate'] = resolution_estimate
# Run estimations in parallel using ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=4) as executor:
# Submit all estimation tasks
volume_future = executor.submit(self.estimate_volume, spine_3D, resolution_estimate, data_in_spine)
surface_future = executor.submit(self.estimate_surface_area, spine_3D, resolution_estimate, data_in_spine)
length_future = executor.submit(self.estimate_length_L, spine_3D, resolution_estimate, data_in_spine)
diameter_future = executor.submit(self.estimate_diameter, spine_3D, resolution_estimate, data_in_spine)
# Wait for all tasks to complete
volume_future.result()
surface_future.result()
length_future.result()
diameter_future.result()
# Set description (quick operation, no need for parallel)
self.set_description(data_in_spine)
def set_spine_color(self, spine_number, data_in_spine):
"""
Set the color of the spine in data_in_spine.
"""
spine_color = self.rgb_colors[spine_number]
data_in_spine.spine_color = spine_color
def extract_spine_mask(self, spine_number):
"""
Extract the mask and subvolume containing the spine.
Optimized with caching and efficient array operations.
"""
if spine_number in self._coords_cache:
return self._coords_cache[spine_number]
# Use boolean indexing for efficiency
mask = self.image_data == spine_number
coords = np.argwhere(mask)
if coords.size == 0:
self._coords_cache[spine_number] = (None, None)
return None, None
# Use vectorized operations for min/max
min_coords = coords.min(axis=0)
max_coords = coords.max(axis=0)
min_k, min_i, min_j = min_coords
max_k, max_i, max_j = max_coords
# Extract subvolume efficiently using views
spine_3D = mask[min_k:max_k + 1, min_i:max_i + 1, min_j:max_j + 1]
# Cache the result
self._coords_cache[spine_number] = (mask, spine_3D)
return mask, spine_3D
def calculate_dimensions(self, mask, data_in_spine):
"""
Calculate the dimensions of the spine and update data_in_spine.
Uses cached coordinates when possible.
"""
if 'dimensions' in self._calculation_cache:
di, dj, dk = self._calculation_cache['dimensions']
else:
coords = np.argwhere(mask)
min_coords = coords.min(axis=0)
max_coords = coords.max(axis=0)
min_k, min_i, min_j = min_coords
max_k, max_i, max_j = max_coords
di = max_i - min_i + 1
dj = max_j - min_j + 1
dk = max_k - min_k + 1
self._calculation_cache['dimensions'] = (di, dj, dk)
data_in_spine.height = di
data_in_spine.width = dj
data_in_spine.num_layers = dk
def estimate_resolution(self, data_in_spine):
"""
Estimate the resolution based on the maximum dimension.
"""
dmax = max(data_in_spine.height, data_in_spine.width, data_in_spine.num_layers)
if dmax > 2:
resolution_estimate = 1000.0 / (dmax - 2)
else:
resolution_estimate = 1.0
data_in_spine.x_resolution = resolution_estimate
data_in_spine.y_resolution = resolution_estimate
data_in_spine.z_resolution = resolution_estimate
data_in_spine.resolution_unit = "nm"
return resolution_estimate
def estimate_volume(self, spine_3D, resolution_estimate, data_in_spine):
"""
Estimate the volume of the spine and update data_in_spine.
"""
spine_3D_volume_estimate = np.sum(spine_3D)
volume_voxel = resolution_estimate ** 3
data_in_spine.volume = spine_3D_volume_estimate * volume_voxel * 1e-9 # nm^3 to um^3
data_in_spine.volume_unit = "um3"
def estimate_surface_area(self, spine_3D, resolution_estimate, data_in_spine):
"""
Estimate the surface area of the spine and update data_in_spine.
Currently set to None (placeholder for future implementation).
"""
data_in_spine.surface = None # Placeholder
data_in_spine.surface_unit = "um2"
def estimate_length_L(self, spine_3D, resolution_estimate, data_in_spine):
"""
Estimate the length L of the spine and update data_in_spine.
"""
dk_connect, di_connect, dj_connect = self.find_mid_point_by_arithmetic_mean(spine_3D)
mk, mi, mj, L = self.find_far_point(dk_connect, di_connect, dj_connect, spine_3D)
data_in_spine.L = L * resolution_estimate / 1000.0 # nm to um
# Points
data_in_spine.point_connect = (int(dj_connect), int(di_connect), int(dk_connect))
data_in_spine.point_far = (int(mj), int(mi), int(mk))
point_middle = ((dj_connect + mj) / 2, (di_connect + mi) / 2, (dk_connect + mk) / 2)
data_in_spine.point_middle = (int(point_middle[0]), int(point_middle[1]), int(point_middle[2]))
data_in_spine.point_connect_value = int(spine_3D[int(dk_connect), int(di_connect), int(dj_connect)])
def estimate_diameter(self, spine_3D, resolution_estimate, data_in_spine):
"""
Estimate the diameter of the spine and update data_in_spine.
Currently set to None (placeholder for future implementation).
"""
data_in_spine.d = None # Placeholder
def set_description(self, data_in_spine):
"""
Set the description field in data_in_spine.
"""
data_in_spine.description = f"Estimations for selected color with RGB {data_in_spine.spine_color}"
def find_mid_point_by_arithmetic_mean(self, matrix):
"""
Find the arithmetic mean point of the voxels in the matrix.
Optimized using numpy's efficient array operations.
"""
coords = np.argwhere(matrix)
if coords.size == 0:
return 0, 0, 0
# Use numpy's mean for better performance
mean_coords = np.mean(coords, axis=0)
return mean_coords[0], mean_coords[1], mean_coords[2]
def find_far_point(self, dk_connect, di_connect, dj_connect, matrix):
"""
Find the farthest point from the given connection point in the matrix.
Optimized using vectorized operations.
"""
coords = np.argwhere(matrix)
if coords.size == 0:
return 0, 0, 0, 0
# Vectorized distance calculation
given_point = np.array([dk_connect, di_connect, dj_connect])
distances = np.linalg.norm(coords - given_point, axis=1)
max_distance_idx = np.argmax(distances)
max_distance = distances[max_distance_idx]
farthest_point = coords[max_distance_idx]
return tuple(farthest_point) + (max_distance,)
class TIFFViewerUI:
"""
Class that handles all the UI tasks and interactions.
"""
def __init__(self, root, viewer):
self.root = root
self.viewer = viewer
self.metadata_entries = {}
# Performance settings
self.downsample_factor = tk.IntVar(value=1) # For downsampling large datasets
self.max_points = tk.IntVar(value=100000) # Maximum points to render
self.quality_level = tk.IntVar(value=3) # Quality level for rendering (1-5)
self.chunk_size = tk.IntVar(value=100) # Chunk size for processing
# Status bar for progress updates
self.status_bar = tk.Label(root, text="Ready", bd=1, relief=tk.SUNKEN, anchor=tk.W)
self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
# Initialize frames
self.welcome_frame = tk.Frame(self.root, bg="#f0f0f0")
self.viewer_frame = tk.Frame(self.root, bg="#f0f0f0")
self.single_color_frame = tk.Frame(self.root, bg="#f0f0f0")
# Show the welcome frame initially
self.show_welcome_frame()
def update_status(self, message):
"""Update the status bar with a message"""
self.status_bar.config(text=message)
self.root.update_idletasks()
def show_welcome_frame(self):
"""Show the welcome frame with performance settings"""
self.clear_frames()
self.welcome_frame.pack(fill=tk.BOTH, expand=True)
# Welcome content
welcome_label = tk.Label(self.welcome_frame,
text="Welcome to the 3D TIFF Viewer",
font=("Helvetica", 20, "bold"),
bg="#f0f0f0")
welcome_label.pack(pady=20)
# Performance settings frame
settings_frame = tk.LabelFrame(self.welcome_frame,
text="Performance Settings",
font=("Helvetica", 12),
bg="#f0f0f0")
settings_frame.pack(pady=10, padx=10, fill="x")
# Downsample factor
tk.Label(settings_frame,
text="Downsample Factor:",
font=("Helvetica", 10),
bg="#f0f0f0").grid(row=0, column=0, padx=5, pady=5)
tk.Scale(settings_frame,
from_=1, to=10,
orient="horizontal",
variable=self.downsample_factor,
length=200,
bg="#f0f0f0").grid(row=0, column=1, padx=5, pady=5)
# Quality level
tk.Label(settings_frame,
text="Render Quality:",
font=("Helvetica", 10),
bg="#f0f0f0").grid(row=1, column=0, padx=5, pady=5)
tk.Scale(settings_frame,
from_=1, to=5,
orient="horizontal",
variable=self.quality_level,
length=200,
bg="#f0f0f0").grid(row=1, column=1, padx=5, pady=5)
# Max points
tk.Label(settings_frame,
text="Max Points (thousands):",
font=("Helvetica", 10),
bg="#f0f0f0").grid(row=2, column=0, padx=5, pady=5)
tk.Scale(settings_frame,
from_=10, to=1000,
orient="horizontal",
variable=self.max_points,
length=200,
bg="#f0f0f0").grid(row=2, column=1, padx=5, pady=5)
# Chunk size
tk.Label(settings_frame,
text="Processing Chunk Size:",
font=("Helvetica", 10),
bg="#f0f0f0").grid(row=3, column=0, padx=5, pady=5)
tk.Scale(settings_frame,
from_=50, to=500,
orient="horizontal",
variable=self.chunk_size,
length=200,
bg="#f0f0f0").grid(row=3, column=1, padx=5, pady=5)
# Help text
help_text = "Higher downsample = faster but less detailed\n"
help_text += "Lower quality = faster rendering\n"
help_text += "Lower max points = better performance\n"
help_text += "Larger chunk size = faster but more memory"
tk.Label(settings_frame,
text=help_text,
font=("Helvetica", 8),
bg="#f0f0f0",
fg="gray").grid(row=4, column=0, columnspan=2, pady=5)
# Upload button
upload_button = tk.Button(self.welcome_frame,
text="Upload TIFF File",
command=self.upload_file,
font=("Helvetica", 14),
bg="#4a90e2",
fg="white",
relief=tk.FLAT)
upload_button.pack(pady=10)
# Save directory selection
self.save_directory = tk.StringVar()
save_directory_label = tk.Label(self.welcome_frame,
text="Save Directory:",
font=("Helvetica", 14),
bg="#f0f0f0")
save_directory_label.pack(pady=5)
save_directory_entry = tk.Entry(self.welcome_frame,
textvariable=self.save_directory,
font=("Helvetica", 12),
width=50)
save_directory_entry.pack(pady=5)
browse_button = tk.Button(self.welcome_frame,
text="Browse",
command=self.browse_directory,
font=("Helvetica", 12),
bg="#4a90e2",
fg="white",
relief=tk.FLAT)
browse_button.pack(pady=5)
def show_viewer_frame(self):
self.clear_frames()
self.viewer_frame.pack(fill=tk.BOTH, expand=True)
self.add_navbar(self.viewer_frame)
# Matplotlib figure setup
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111, projection='3d')
# Embed the matplotlib figure into Tkinter window
self.canvas = FigureCanvasTkAgg(self.fig, master=self.viewer_frame)
self.canvas.draw()
self.canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=30, pady=30)
# Bind mouse scroll event for zoom functionality
self.canvas.mpl_connect("scroll_event", self.on_scroll)
# Create a frame for displaying all unique colors
self.color_frame = tk.Frame(self.viewer_frame, relief=tk.RAISED, borderwidth=2, bg="#f0f0f0")
self.color_frame.pack(side=tk.RIGHT, fill=tk.Y, padx=10, pady=10)
# Make the color frame scrollable
self.color_canvas = tk.Canvas(self.color_frame, bg="#f0f0f0")
self.scrollbar = tk.Scrollbar(self.color_frame, orient="vertical", command=self.color_canvas.yview)
self.scrollable_frame = tk.Frame(self.color_canvas, bg="#f0f0f0")
self.scrollable_frame.bind(
"<Configure>",
lambda e: self.color_canvas.configure(
scrollregion=self.color_canvas.bbox("all")
)
)
self.color_canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
self.color_canvas.configure(yscrollcommand=self.scrollbar.set)
self.color_canvas.pack(side="left", fill="both", expand=True)
self.scrollbar.pack(side="right", fill="y")
# Bind mouse wheel events for scrolling - only to the color frame
self.color_canvas.bind_all("<MouseWheel>", self.on_mousewheel_color_frame)
self.checkbuttons = [] # Store references to checkbuttons
# Create a title label for the color selection area
color_frame_title = tk.Label(self.scrollable_frame, text="Select Colors:", font=("Helvetica", 14, "bold"),
bg="#f0f0f0")
color_frame_title.pack(pady=10, padx=5)
self.populate_color_frame()
# Create a frame for the select/unselect all buttons
select_frame = tk.Frame(self.scrollable_frame, bg="#f0f0f0")
select_frame.pack(pady=10)
# Create a "Select All" button
select_all_button = tk.Button(select_frame, text="Select All", command=self.select_all_colors,
font=("Helvetica", 12), bg="#4a90e2", fg="white", relief=tk.FLAT)
select_all_button.pack(side=tk.LEFT, padx=5)
# Create an "Unselect All" button
unselect_all_button = tk.Button(select_frame, text="Unselect All", command=self.unselect_all_colors,
font=("Helvetica", 12), bg="#4a90e2", fg="white", relief=tk.FLAT)
unselect_all_button.pack(side=tk.LEFT, padx=5)
# Create an "Apply" button
apply_button = tk.Button(self.scrollable_frame, text="Apply", command=self.apply_selections,
font=("Helvetica", 12), bg="#4a90e2", fg="white", relief=tk.FLAT)
apply_button.pack(pady=10)
# Create the initial voxel plot
self.create_voxel_plot(full_image=True)
def on_mousewheel_color_frame(self, event):
"""
Scroll the color frame using the mouse wheel.
"""
if self.color_canvas.winfo_containing(event.x_root, event.y_root) in [self.color_canvas, self.scrollable_frame]:
self.color_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def show_single_color_frame(self):
"""Show single color frame with optimized rendering"""
self.clear_frames()
self.single_color_frame.pack(fill=tk.BOTH, expand=True)
self.metadata_entries = {}
for widget in self.single_color_frame.winfo_children():
widget.destroy()
self.add_navbar(self.single_color_frame)
# Extract current color data
p_value = self.viewer.selected_p_values[self.viewer.current_color_index]
self.viewer.current_p_value = p_value
self.viewer.current_spine_number = p_value
rgb_color = self.viewer.rgb_colors[p_value]
rgb_normalized = np.array(rgb_color, dtype=np.float32) / 255.0
# Get mask efficiently using boolean indexing
mask = self.viewer.image_uploaded == p_value
# Apply downsampling if enabled
if self.downsample_factor.get() > 1:
factor = self.downsample_factor.get()
mask = mask[::factor, ::factor, ::factor]
# Optimize visualization based on data size and performance settings
total_points = np.sum(mask)
use_scatter = total_points > self.max_points.get() * 1000
# Create figure with optimized settings based on quality level
quality_factor = 6 - self.quality_level.get() # Convert quality level to scaling factor
dpi = max(80, 100 // quality_factor) # Adjust DPI based on quality
self.single_fig = plt.figure(figsize=(8, 6), dpi=dpi)
self.single_ax = self.single_fig.add_subplot(111, projection='3d')
if use_scatter:
# Memory-efficient coordinate extraction
coords = np.argwhere(mask)
if len(coords) > self.max_points.get() * 1000:
idx = np.random.choice(len(coords),
self.max_points.get() * 1000,
replace=False)
coords = coords[idx]
# Adjust point size and alpha based on quality level
point_size = max(5, 15 // quality_factor)
alpha = max(0.3, 0.8 / quality_factor)
# Optimized scatter plot
self.single_ax.scatter(coords[:, 2],
coords[:, 1],
coords[:, 0],
c=[rgb_normalized],
s=point_size,
alpha=alpha)
else:
# Optimized voxel plot
# Only create colors array for visible voxels
colors = np.zeros(mask.shape + (4,), dtype=np.float32)
colors[mask] = np.append(rgb_normalized, 0.7) # Use 0.7 alpha
# Process in chunks if needed
if total_points > 50000:
chunk_size = self.chunk_size.get()
for start_idx in range(0, len(mask), chunk_size):
end_idx = min(start_idx + chunk_size, len(mask))
chunk_mask = mask[start_idx:end_idx]
chunk_colors = colors[start_idx:end_idx]
self.single_ax.voxels(chunk_mask,
facecolors=chunk_colors,
edgecolor=None) # Remove edges for better visibility
# Update progress
progress = (end_idx / len(mask)) * 100
self.update_status(f"Rendering voxels... {progress:.1f}%")
else:
self.single_ax.voxels(mask,
facecolors=colors,
edgecolor=None) # Remove edges for better visibility
self.single_ax.set_title('3D Voxel Plot')
self.single_ax.set_xlabel('X axis')
self.single_ax.set_ylabel('Y axis')
self.single_ax.set_zlabel('Z axis')
self.single_ax.set_box_aspect([1, 1, 1])
# Embed figure with optimized canvas
self.single_canvas = FigureCanvasTkAgg(self.single_fig, master=self.single_color_frame)
self.single_canvas.draw()
self.single_canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Add zoom functionality
self.single_canvas.mpl_connect("scroll_event",
lambda event: self.on_scroll_single(event, self.single_ax, self.single_canvas))
# Create metadata panel
self._create_metadata_panel(p_value, mask)
# Force garbage collection
gc.collect()
self.update_status("Ready")
def _create_metadata_panel(self, p_value, mask):
"""Create metadata panel with optimized estimation processing"""
metadata_frame = tk.Frame(self.single_color_frame, bg="#f0f0f0", relief=tk.RAISED, borderwidth=2)
metadata_frame.pack(side=tk.RIGHT, fill=tk.BOTH, padx=10, pady=10)
# Make the metadata frame scrollable
self.metadata_canvas = tk.Canvas(metadata_frame, bg="#f0f0f0", width=300) # Set fixed width
scrollbar = tk.Scrollbar(metadata_frame, orient="vertical", command=self.metadata_canvas.yview)
self.scrollable_metadata_frame = tk.Frame(self.metadata_canvas, bg="#f0f0f0")
self.scrollable_metadata_frame.bind(
"<Configure>",
lambda e: self.metadata_canvas.configure(
scrollregion=self.metadata_canvas.bbox("all")
)
)
self.metadata_canvas.create_window((0, 0), window=self.scrollable_metadata_frame, anchor="nw")
self.metadata_canvas.configure(yscrollcommand=scrollbar.set)
self.metadata_canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# Bind mouse wheel events for scrolling - only to the metadata frame
self.metadata_canvas.bind_all("<MouseWheel>", self.on_mousewheel_metadata_frame)
# Create title label in the scrollable frame
metadata_label = tk.Label(self.scrollable_metadata_frame,
text="Metadata:",
font=("Helvetica", 14, "bold"),
bg="#f0f0f0")
metadata_label.pack(pady=5)
# Status label for estimation progress
status_label = tk.Label(self.scrollable_metadata_frame,
text="Calculating estimations...",
font=("Helvetica", 10),
bg="#f0f0f0")
status_label.pack(pady=5)
# Run estimations in background thread
def run_estimations():
try:
# Create a new DataInImage instance for this color
data_in_spine = DataInImage()
# Copy existing metadata if available
if self.viewer.data_in_image:
data_in_spine.__dict__.update(self.viewer.data_in_image.__dict__)
# Create estimator and run calculations
estimator = Estimator(self.viewer.image_uploaded, self.viewer.rgb_colors)
single_color_data = estimator.run_estimations(p_value, data_in_spine)
# Update UI in main thread
self.root.after(0, lambda: self._update_metadata_ui(single_color_data, self.scrollable_metadata_frame, mask))
self.root.after(0, lambda: status_label.destroy())
except Exception as e:
self.root.after(0, lambda: status_label.config(
text=f"Error calculating estimations: {str(e)}",
fg="red"
))
print(f"Error in estimation calculation: {e}")
Thread(target=run_estimations, daemon=True).start()
def _update_metadata_ui(self, single_color_data, frame, mask):
"""Update metadata UI with estimation results"""
# Clear any existing widgets in the frame
for widget in frame.winfo_children():
widget.destroy()
# Create title label again since we cleared all widgets
metadata_label = tk.Label(frame,
text="Metadata:",
font=("Helvetica", 14, "bold"),
bg="#f0f0f0")
metadata_label.pack(pady=5)
single_color_data.print_data()
# Store the data and mask for saving
self.viewer.single_color_data = single_color_data
self.viewer.current_mask = mask
# Create metadata entries
for key, attr in single_color_data.tag_dict.items():
# Create a frame for each metadata item
item_frame = tk.Frame(frame, bg="#f0f0f0")
item_frame.pack(fill='x', padx=5, pady=2)
# Label for the metadata item
metadata_label = tk.Label(item_frame,
text=f"{key}:",
font=("Helvetica", 12),
bg="#f0f0f0",
anchor='w')
metadata_label.pack(side='top', fill='x')
# Entry for the metadata value
default_value = getattr(single_color_data, attr)
var = tk.StringVar(value=str(default_value))
metadata_entry = tk.Entry(item_frame,
textvariable=var,
font=("Helvetica", 12),
width=30)
metadata_entry.pack(side='top', fill='x')
self.metadata_entries[attr] = var
# Add buttons frame
button_frame = tk.Frame(frame, bg="#f0f0f0")
button_frame.pack(pady=10)
# Add buttons
save_button = tk.Button(button_frame,
text="Save",
command=self.save_current_mask,
font=("Helvetica", 12),
bg="#4a90e2",
fg="white",
relief=tk.FLAT)
save_button.pack(side=tk.LEFT, padx=5)
prev_button = tk.Button(button_frame,
text="Previous",
command=self.previous_single_color,
font=("Helvetica", 12),
bg="#4a90e2",
fg="white",
relief=tk.FLAT)
prev_button.pack(side=tk.LEFT, padx=5)
next_button_text = "Finish" if self.viewer.current_color_index == len(
self.viewer.selected_p_values) - 1 else "Next"
next_button = tk.Button(button_frame,
text=next_button_text,
command=self.next_single_color,
font=("Helvetica", 12),
bg="#4a90e2",
fg="white",
relief=tk.FLAT)
next_button.pack(side=tk.LEFT, padx=5)
def on_mousewheel_metadata_frame(self, event):
"""
Scroll the metadata frame using the mouse wheel.
"""
if event.widget.winfo_containing(event.x_root, event.y_root) in [self.metadata_canvas, self.scrollable_metadata_frame]:
self.metadata_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def save_current_mask(self):
"""
Save the current mask as a multi-layered TIFF file with metadata when the "SAVE" button is pressed.
"""
if self.save_directory.get():
# Before saving, update self.viewer.single_color_data with modified values
attr_value_dict = {}
for attr in self.viewer.single_color_data.tag_dict.values():
var = self.metadata_entries.get(attr)
if var:
value_str = var.get()
attr_value_dict[attr] = value_str
# Update self.viewer.single_color_data with the modified values
self.viewer.single_color_data.update_from_strings(attr_value_dict)
base_name = os.path.splitext(os.path.basename(self.viewer.image_path))[0]
save_dir = self.save_directory.get()
p_value = self.viewer.current_p_value
# Save the mask as a layered TIFF file with metadata
tiff_save_path = os.path.join(save_dir, f"{base_name}_color_{p_value}_data.tiff")
self.viewer.save_data_as_tiff(tiff_save_path, self.viewer.single_color_data)
print(f"Saved data TIFF with metadata to {tiff_save_path}")
else:
messagebox.showinfo("Save Directory Not Set", "Please set a save directory before saving.")
def clear_frames(self):
"""Remove all frames and clean up bindings"""
# Unbind all mousewheel events before clearing frames
try:
self.color_canvas.unbind_all("<MouseWheel>")
except AttributeError:
pass
try:
self.metadata_canvas.unbind_all("<MouseWheel>")
except AttributeError:
pass
# Remove all frames from the root window
for frame in (self.welcome_frame, self.viewer_frame, self.single_color_frame):
frame.pack_forget()
def browse_directory(self):
directory = filedialog.askdirectory()
if directory:
self.save_directory.set(directory)
def upload_file(self):
file_path = filedialog.askopenfilename(filetypes=[("TIFF files", "*.tiff"), ("All files", "*.*")])
if file_path:
self.viewer.initialize_viewer(file_path)
self.show_viewer_frame()
def add_navbar(self, window):
"""
Add a navigation bar to the specified window.
"""
navbar = tk.Frame(window, bg="#4a4a4a")
navbar.pack(side=tk.TOP, fill=tk.X)
nav_title = tk.Label(navbar, text="3D TIFF Viewer", font=("Helvetica", 16, "bold"), fg="white", bg="#4a4a4a")
nav_title.pack(side=tk.LEFT, padx=20)
def on_scroll(self, event):
"""
Handle zooming in and out of the 3D plot using the mouse scroll wheel.
"""
base_scale = 1.1
if event.button == 'up':
scale_factor = 1 / base_scale
elif event.button == 'down':
scale_factor = base_scale
else:
# No need to handle other events
return
# Get the current limits
xlim = self.ax.get_xlim()
ylim = self.ax.get_ylim()
zlim = self.ax.get_zlim()
# Compute the new limits
self.ax.set_xlim([xlim[0] * scale_factor, xlim[1] * scale_factor])
self.ax.set_ylim([ylim[0] * scale_factor, ylim[1] * scale_factor])
self.ax.set_zlim([zlim[0] * scale_factor, zlim[1] * scale_factor])
self.canvas.draw()
def create_voxel_plot(self, full_image=False):
"""Create an optimized voxel plot"""
self.update_status("Creating plot...")
self.ax.clear()
if full_image:
try:
# Get mask with memory-efficient boolean indexing
mask = self.viewer.image_uploaded > 0
# Create color array with proper RGBA values
colors = np.zeros(mask.shape + (4,), dtype=np.float32)
unique_values = np.unique(self.viewer.image_uploaded[mask])
for idx in unique_values:
if idx == 0: # Skip background
continue
color_mask = self.viewer.image_uploaded == idx
rgb_color = np.array(self.viewer.rgb_colors[idx], dtype=np.float32) / 255.0
colors[color_mask] = np.append(rgb_color, 1.0) # Full opacity
# Downsample if needed
if self.downsample_factor.get() > 1:
factor = self.downsample_factor.get()
mask = mask[::factor, ::factor, ::factor]
colors = colors[::factor, ::factor, ::factor]
# Use scatter plot for very large datasets
if np.sum(mask) > self.max_points.get() * 1000:
coords = np.argwhere(mask)
if len(coords) > self.max_points.get() * 1000:
idx = np.random.choice(len(coords),
self.max_points.get() * 1000,
replace=False)
coords = coords[idx]
# Get colors for scatter plot
point_colors = colors[coords[:, 0], coords[:, 1], coords[:, 2], :3]
quality_factor = 6 - self.quality_level.get()
point_size = max(5, 15 // quality_factor)
alpha = max(0.3, 0.8 / quality_factor)
self.ax.scatter(coords[:, 2],
coords[:, 1],
coords[:, 0],
c=point_colors,
s=point_size,
alpha=alpha)
else:
# Use voxels for smaller datasets
self.ax.voxels(mask,
facecolors=colors,
edgecolor=None, # Remove edges for better visibility
alpha=0.8) # Slightly transparent
self.ax.set_title('3D Voxel Plot')
self.ax.set_xlabel('X axis')
self.ax.set_ylabel('Y axis')
self.ax.set_zlabel('Z axis')
self.ax.set_box_aspect([1, 1, 1])
# Force garbage collection
gc.collect()
except Exception as e:
self.update_status(f"Error creating plot: {str(e)}")
return
self.canvas.draw()
self.update_status("Ready")
def populate_color_frame(self):
"""
Populate the frame with the unique colors extracted from the image.
"""
for idx, color in self.viewer.color_index_list:
rgb_color = tuple(color)
hex_color = f'#{rgb_color[0]:02x}{rgb_color[1]:02x}{rgb_color[2]:02x}'
var = tk.BooleanVar(value=False) # Set the initial value to False for all colors
color_button = tk.Checkbutton(self.scrollable_frame, bg=hex_color, width=25, height=2, variable=var,
command=lambda p=idx, v=var: self.on_color_select(p, v))
color_button.p_value = idx # Store p_value in the button for easy access
color_button.pack(pady=5, padx=5, anchor='w')
self.checkbuttons.append((color_button, var))
def on_color_select(self, p_value, var):
"""
Handle the color selection and store the P value.
If the color is already selected, deselect it.
"""
if var.get():