-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_editing_view.py
More file actions
669 lines (592 loc) · 29.8 KB
/
image_editing_view.py
File metadata and controls
669 lines (592 loc) · 29.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
import base64
import os
import typing
from io import BytesIO
from pathlib import Path
import cv2
import flet as ft
import numpy as np
import tifffile
from PIL import Image
from drawing_tool import DrawingTool
from drawing_util import bresenham_line, search_free_id, trace_contour, fill_polygon_from_outline, find_border_pixels, \
mask_shifting, rgb_to_hex
def load_image(image_path,get_slice=-1):
image = tifffile.imread(image_path)
shape = list(image.shape)
check = image.ndim == 3
if check:
if not get_slice == -1:
image = np.take(image, get_slice, axis=2).astype(np.uint16)
else:
image = np.max(image, axis=2).astype(np.uint16)
_, buffer = cv2.imencode('.png', image)
return base64.b64encode(buffer).decode('utf-8'),shape,check
def convert_npy_to_canvas(mask, outline, mask_color, outline_color, opacity, slice_id=-1):
"""
handles the conversion of the given file data
Args:
mask= the mask data stored in the numpy directory
outline= the outline data stored in the numpy directory
"""
buffer= BytesIO()
if mask.ndim == 3:
if slice_id >= 0:
mask = np.take(mask, slice_id, axis=0).astype(np.uint16)
else:
mask = np.max(mask, axis=0).astype(np.uint16)
if outline.ndim == 3:
if slice_id >= 0:
outline = np.take(outline, slice_id, axis=0).astype(np.uint16)
else:
outline = np.max(outline, axis=0).astype(np.uint16)
image_mask = np.zeros(shape=(mask.shape[0], mask.shape[1], 4), dtype=np.uint8)
r,g,b = mask_color
image_mask[mask != 0] = (r, g, b, opacity)
r, g, b = outline_color
image_mask[outline != 0] = (r, g, b, 255)
im= Image.fromarray(image_mask).convert("RGBA")
#saves the image as a image(base64)
im.save(buffer, format="PNG")
buffer.seek(0)
image_base_64= base64.b64encode(buffer.getvalue()).decode('utf-8')
#saves the created output image.
return image_base_64
def _get_cell_id_from_position(position, mask):
"""
Get the cell ID from the clicked position.
"""
x, y = int(position[0]), int(position[1])
if 0 <= x < mask.shape[1] and 0 <= y < mask.shape[0]:
return mask[y, x]
return None
class ImageEditingView(ft.Card):
def __init__(self,on_mask_change: typing.Callable[[str], None] = None):
super().__init__()
self._mask_paths = None
self._main_paths = None
self._mask_path = r"C:\Users\Jenna\Studium\FS5\data\data\output\Series003c2_seg.npy" #Could set a mask_path for TESTING
self._mask_data = None
self._slice_id = -1
self._image_3d = False
self._image_id = None
self._channel_id = None
self._seg_channel_id = None
self.mask_color = (255, 0, 0)
self.outline_color = (0, 255, 0)
self.mask_opacity = 128
self._user_2_5d = False
self.on_mask_change = on_mask_change or (lambda x: None)
self.mask_suffix = "_seg"
self.expand=True
self._redo_stack = []
self._undo_stack = []
self._edit_allowed = True
self._mask_image = ft.Image(src="Placeholder", fit=ft.BoxFit.CONTAIN, visible=False,gapless_playback=True,expand=True)
self._main_image = ft.Image(src="Placeholder", fit=ft.BoxFit.CONTAIN,visible=False,gapless_playback=True,expand=True)
self.drawing_tool = DrawingTool(on_cell_drawn=self._cell_drawn, on_cell_deleted=self._delete_cell)
self.image_stack = ft.InteractiveViewer(content=ft.Stack([self._main_image, self._mask_image, self.drawing_tool],expand=True),expand=True)
self._mask_button = ft.IconButton(icon=ft.Icons.REMOVE_RED_EYE, icon_color=ft.Colors.BLACK12,
style=ft.ButtonStyle(
shape=ft.RoundedRectangleBorder(radius=12),), on_click=lambda e: self._show_mask(),
tooltip="Show Mask", hover_color=ft.Colors.WHITE12, disabled=False)
self._edit_button = ft.IconButton(icon=ft.Icons.BRUSH, icon_color=ft.Colors.BLACK_12,
style=ft.ButtonStyle(
shape=ft.RoundedRectangleBorder(radius=12), ),disabled=True,
tooltip="Draw mode", hover_color=ft.Colors.WHITE_12,on_click=lambda e:self._toggle_draw())
self._delete_button = ft.IconButton(icon=ft.Icons.CLEAR, icon_color=ft.Colors.WHITE_60,
style=ft.ButtonStyle(
shape=ft.RoundedRectangleBorder(radius=12), ),
tooltip="Delete mode", hover_color=ft.Colors.WHITE12,on_click=lambda e: self._toggle_delete())
self._delete_mask_button = ft.IconButton(icon=ft.Icons.DELETE_FOREVER, icon_color=ft.Colors.WHITE_60,
style=ft.ButtonStyle(
shape=ft.RoundedRectangleBorder(radius=12), ),
tooltip="Delete the complete mask", hover_color=ft.Colors.WHITE12,
on_click=lambda e: self.delete_mask())
self._redo_button = ft.IconButton(icon=ft.Icons.REDO_SHARP, icon_color=ft.Colors.BLACK_12,
style=ft.ButtonStyle(
shape=ft.RoundedRectangleBorder(radius=12), ),
tooltip="Redo action", hover_color=ft.Colors.WHITE_12,
on_click=lambda e: self.redo_stack(e),disabled=True)
self._undo_button = ft.IconButton(icon=ft.Icons.UNDO_SHARP, icon_color=ft.Colors.BLACK_12,
style=ft.ButtonStyle(
shape=ft.RoundedRectangleBorder(radius=12), ),
tooltip="Undo action", hover_color=ft.Colors.WHITE12,
on_click=lambda e: self.undo_stack(e),disabled=True)
self._slider_2_5d = ft.Slider(
min=0, max=100, divisions=None, label="Slice: {value}",value=0,
opacity=1.0 if self._user_2_5d else 0.0, height=20,
active_color=ft.Colors.WHITE60, thumb_color=ft.Colors.WHITE, disabled=True,
animate_opacity=ft.Animation(duration=600, curve=ft.AnimationCurve.LINEAR_TO_EASE_OUT),
on_change=lambda e: self._slider2_5d_change()
)
self._slider_2d = ft.CupertinoSlidingSegmentedButton(
selected_index=0 if not self._user_2_5d else 1,
thumb_color=ft.Colors.WHITE,
bgcolor=ft.Colors.WHITE60,
padding=ft.padding.symmetric(0, 0),
controls=[
ft.Text("2D", color=ft.Colors.BLACK,weight=ft.FontWeight.BOLD),
ft.Text("2.5D", color=ft.Colors.BLACK,weight=ft.FontWeight.BOLD)
],
on_change=lambda e: self._slider2d_update(e)
)
self._shifting_check_box = ft.IconButton(
icon=ft.Icons.EXPAND,
icon_color=ft.Colors.WHITE60,
style=ft.ButtonStyle(
shape=ft.RoundedRectangleBorder(radius=12),),
hover_color=ft.Colors.WHITE12,
selected_icon=ft.Icons.COMPRESS_ROUNDED,
selected_icon_color=ft.Colors.WHITE,
selected=False,
on_click=lambda e: self._toggle_shifting(e),
)
self.control_tools = ft.Container(ft.Container(ft.Row(
[ self._undo_button,
self._redo_button,
self._shifting_check_box,
self._edit_button,
self._delete_button,
self._mask_button,
self._slider_2d,
ft.Container(
content=self._slider_2_5d,
theme=ft.Theme(
slider_theme=ft.SliderTheme(
value_indicator_text_style=ft.TextStyle(color=ft.Colors.BLACK, size=15,weight=ft.FontWeight.BOLD),
)
),
dark_theme=ft.Theme(
slider_theme=ft.SliderTheme(
value_indicator_text_style=ft.TextStyle(color=ft.Colors.BLACK, size=15,weight=ft.FontWeight.BOLD),
)
),
),
self._delete_mask_button,
], spacing=2,alignment=ft.MainAxisAlignment.CENTER,
), bgcolor=ft.Colors.BLUE_400, expand=True, border_radius=ft.border_radius.vertical(top=0, bottom=12),
))
self.content = ft.Column(controls=[ft.Container(self.image_stack,alignment=ft.Alignment.CENTER,expand=True),self.control_tools],spacing=0)
def set_mask_paths(self, mask_paths: list):
self._mask_paths = mask_paths
def set_main_paths(self, main_paths: list):
self._main_paths = main_paths
def set_colors(self, mask_color, outline_color, opacity):
self.drawing_tool.draw_color= rgb_to_hex(outline_color)
self.mask_color = mask_color
self.outline_color = outline_color
self.mask_opacity = opacity
self.update_mask_image()
def reset_image(self):
self._main_image.src = "Placeholder"
self._main_image.visible = False
self._main_image.update()
self._mask_path = None
self._mask_data = None
self._mask_image.src = "Placeholder"
self._mask_image.visible = False
self._mask_image.update()
self._mask_button.tooltip = "Show mask"
self._mask_button.icon_color = ft.Colors.BLACK12
self._mask_button.disabled = True
self._mask_button.update()
self._edit_button.icon_color = ft.Colors.BLACK12
self._edit_button.disabled = True
self._edit_button.update()
self.drawing_tool.deactivate_drawing()
def select_image(self, img_id, channel_id,seg_channel_id):
if self._seg_channel_id != seg_channel_id or self._image_id != img_id:
self._load_mask_image(img_id, seg_channel_id)
self._image_id = img_id
self._channel_id = channel_id
self._seg_channel_id = seg_channel_id
self._load_main_image(img_id, channel_id)
#reset undo/redo when a new image is selected
self._redo_stack.clear()
self._undo_stack.clear()
self._redo_button.disabled = True
self._undo_button.disabled = True
self._redo_button.icon_color = ft.Colors.BLACK_12
self._redo_button.disabled = True
self._undo_button.icon_color = ft.Colors.BLACK_12
self._undo_button.disabled = True
self._redo_button.update()
self._undo_button.update()
def _load_main_image(self, img_id, channel_id):
if self._main_paths is not None:
if img_id in self._main_paths:
if channel_id in self._main_paths[img_id]:
self._load_main_image_with_path(self._main_paths[img_id][channel_id])
return
self._image_3d = False
self._main_image.src = "Placeholder"
self._mask_image.visible = False
self._main_image.update()
def _slider2d_update(self,e):
if int(e.data) == 1:
self._slider_2_5d.opacity = 1.0
self.user_2_5d = True
else:
self._slider_2_5d.opacity = 0.0
self.user_2_5d = False
self._slider2_5d_change()
self._slider_2_5d.update()
def _slider2_5d_change(self):
if self.user_2_5d:
self._slice_id = int(self._slider_2_5d.value)
else:
self._slice_id = -1
if self._main_image.src != "Placeholder":
self._load_main_image(self._image_id,self._channel_id)
self.update_mask_image()
def _load_main_image_with_path(self,path):
src, shape, img_3d = load_image(path, get_slice=self._slice_id)
self._main_image.src = src
self._main_image.visible = True
self.drawing_tool.set_bounds(shape[1],shape[0])
self._main_image.update()
if img_3d:
self._image_3d = True
if self._slider_2_5d.opacity == 1.0 and self._edit_allowed:
if self._edit_button.disabled:
self._edit_button.icon_color = ft.Colors.WHITE60
self._edit_button.disabled = False
self._edit_button.update()
else:
self._edit_button.icon_color = ft.Colors.BLACK12
self._edit_button.disabled = True
self._edit_button.update()
self.drawing_tool.deactivate_drawing()
self._slider_2_5d.value = 0 if shape[
-2] - 1 < self._slider_2_5d.value else self._slider_2_5d.value
self._slider_2_5d.max = shape[2] - 1
self._slider_2_5d.divisions = shape[2] - 2
self._slider_2_5d.disabled = False
self._slider_2_5d.update()
else:
self._image_3d = False
if self._edit_allowed:
if self._edit_button.disabled:
self._edit_button.icon_color = ft.Colors.WHITE60
self._edit_button.disabled = False
self._edit_button.update()
self._slider_2_5d.value = 0
self._slider_2_5d.max = 1
self._slider_2_5d.divisions = None
self._slider_2_5d.disabled = True
self._slider_2_5d.update()
return
def _load_mask_image(self, img_id, seg_channel_id):
if self._mask_paths is not None:
if img_id in self._mask_paths:
if seg_channel_id in self._mask_paths[img_id]:
new_path = self._mask_paths[img_id][seg_channel_id]
if new_path != self._mask_path:
self._mask_data = np.load(
Path(self._mask_paths[img_id][seg_channel_id]),allow_pickle=True).item()
self._mask_path = new_path
mask = self._mask_data["masks"].astype(np.uint16)
outline = self._mask_data["outlines"].astype(np.uint16)
self._mask_image.src = convert_npy_to_canvas(mask, outline, self.mask_color, self.outline_color, self.mask_opacity, slice_id=self._slice_id)
self._mask_image.update()
if not self._mask_image.visible:
self._mask_button.icon_color = ft.Colors.WHITE60
self._mask_button.tooltip = "Show mask"
self._mask_button.disabled = False
self._mask_button.update()
return
self._mask_path = None
self._mask_data = None
self._mask_image.src = "Placeholder"
self._mask_image.visible = False
self._mask_image.update()
self._mask_button.tooltip = "Show mask"
self._mask_button.icon_color = ft.Colors.BLACK12
self._mask_button.disabled = True
self._mask_button.update()
def update_mask_image(self):
if self._mask_path is not None:
self._update_mask_image()
elif self._mask_paths is not None and self._image_id in self._mask_paths and self._seg_channel_id in self._mask_paths[self._image_id] and self._mask_paths[self._image_id][self._seg_channel_id] is not None:
self._mask_path = self._mask_paths[self._image_id][self._seg_channel_id]
self._update_mask_image()
else:
self._mask_image.src = "Placeholder"
self._mask_image.visible = False
self._mask_image.update()
self._mask_button.tooltip = "Show mask"
self._mask_button.icon_color = ft.Colors.BLACK12
self._mask_button.disabled = True
self._mask_button.update()
def _update_mask_image(self):
if not self._mask_image.visible:
self._mask_button.icon_color = ft.Colors.WHITE60
self._mask_button.tooltip = "Show mask"
self._mask_button.disabled = False
self._mask_button.update()
if self._mask_data is None:
self._mask_data = np.load(Path(self._mask_path), allow_pickle=True).item()
mask = self._mask_data["masks"].astype(np.uint16)
outline = self._mask_data["outlines"].astype(np.uint16)
self._mask_image.src = convert_npy_to_canvas(mask, outline, self.mask_color, self.outline_color,
self.mask_opacity, slice_id=self._slice_id)
self._mask_image.update()
def _show_mask(self):
self._mask_image.visible = not self._mask_image.visible
self._mask_image.update()
self._mask_button.icon_color = ft.Colors.WHITE if self._mask_image.visible else ft.Colors.WHITE60
self._mask_button.tooltip="Hide mask" if self._mask_image.visible else "Show mask"
self._mask_button.update()
def _toggle_draw(self):
self._edit_button.icon_color = ft.Colors.WHITE if self._edit_button.icon_color==ft.Colors.WHITE_60 else ft.Colors.WHITE60
self._edit_button.update()
if self._edit_button.icon_color==ft.Colors.WHITE:
self._delete_button.icon_color = ft.Colors.WHITE60
self._delete_button.update()
self.drawing_tool.draw()
else:
self.drawing_tool.deactivate_drawing()
def _toggle_delete(self):
self._delete_button.icon_color = ft.Colors.WHITE if self._delete_button.icon_color == ft.Colors.WHITE_60 else ft.Colors.WHITE60
self._delete_button.update()
if self._delete_button.icon_color == ft.Colors.WHITE:
if not self._edit_button.disabled:
self._edit_button.icon_color = ft.Colors.WHITE60
self._edit_button.update()
self.drawing_tool.delete()
else:
self.drawing_tool.deactivate_delete()
def _toggle_shifting(self,e):
e.control.selected = not e.control.selected
if e.control.selected:
e.control.tooltip = "Shifting IDs: ON \n(Shifts the IDs when a mask is deleted to restore an order without gaps.)"
else:
e.control.tooltip = "Shifting IDs: OFF \n(Deleted masks will leave gaps in the order of the IDs. No shifting will occur.)"
e.control.update()
def _cell_drawn(self, lines_data: list | np.ndarray):
#update the mask data
# gets the pixels that build the lines of the drawn cell
if self._mask_path is None: #currently no mask is given
if self._image_id is None or self._seg_channel_id is None or not self._image_id in self._main_paths or not self._seg_channel_id in self._main_paths[self._image_id]:
return
image_path = self._main_paths[self._image_id][self._seg_channel_id]
directory, filename = os.path.split(image_path)
name, _ = os.path.splitext(filename)
mask_file_name = f"{name}{self.mask_suffix}.npy"
self._mask_path = os.path.join(directory, mask_file_name)
if self._image_id not in self._mask_paths:
self._mask_paths[self._image_id] = {}
self._mask_paths[self._image_id][self._seg_channel_id] = self._mask_path
image_width, image_height = self.drawing_tool.get_bounds()
if not self._image_3d:
#2D Case
empty_mask = {
"masks": np.zeros((image_height, image_width), dtype=np.uint16),
"outlines": np.zeros((image_height, image_width), dtype=np.uint16)
}
else:
#3D-Image Case (with Z-Slices)
empty_mask = {
"masks": np.zeros((self._slider_2_5d.max + 1, image_height, image_width), dtype=np.uint16),
"outlines": np.zeros((self._slider_2_5d.max + 1, image_height, image_width), dtype=np.uint16)
}
#Save the new empty mask
np.save(self._mask_path, empty_mask)
line_pixels = set()
if type(lines_data) is list:
for line in lines_data:
pixels = bresenham_line(line[0], line[1]) # Calculates the pixels along the line
line_pixels.update(pixels)
if self._mask_data is None:
mask_data = np.load(self._mask_path, allow_pickle=True).item()
mask = self._mask_data["masks"].astype(np.uint16)
outline = self._mask_data["outlines"].astype(np.uint16)
if mask.ndim == 3:
if self._slice_id < 0:
raise ValueError("slice_id should be non-negative")
mask = np.take(mask, self._slice_id, axis=0).astype(np.uint16)
if outline.ndim == 3:
if self._slice_id < 0:
raise ValueError("slice_id should be non-negative")
outline = np.take(outline, self._slice_id, axis=0).astype(np.uint16)
free_id = search_free_id(mask, outline) # search for the next free id in mask and outline
# add action to undo stack to be able to delete the cell afterward
self._undo_stack.append(("delete_action", free_id))
self._undo_button.icon_color = ft.Colors.WHITE_60
self._undo_button.disabled = False
self._undo_button.update()
# add the outline of the new mask (only the parts which not overlap with already existing cells) to outline npy array and fill the complete outline to new_cell_outline to calculate inner pixels
new_cell_outline = np.zeros_like(outline, dtype=np.uint16)
if type(lines_data) is list:
for x, y in line_pixels:
if 0 <= x < outline.shape[1] and 0 <= y < outline.shape[0]:
new_cell_outline[y, x] = 1
if outline[y, x] == 0 and mask[y, x] == 0:
outline[y, x] = free_id
else:
new_cell_outline = lines_data
# Traces the outline of the new cell and fills the mask based on the outline
contour = trace_contour(new_cell_outline)
new_mask = fill_polygon_from_outline(contour, mask.shape) # gets the inner pixels of the new cell
mask[(new_mask == 1) & (mask == 0) & (
outline == 0)] = free_id # adds them to the npy if they not overlap with the already existing cells
# search if inline pixels (mask) have no outline, if the pixel have no outline neighbor make them to outline and delete them from mask
new_border_pixels = find_border_pixels(mask, outline, free_id)
for y, x in new_border_pixels:
if 0 <= x < outline.shape[1] and 0 <= y < outline.shape[0]:
mask[y, x] = 0
outline[y, x] = free_id
mask_3d = None
outline_3d = None
if self._slice_id >= 0:
mask_3d = mask_data["masks"]
outline_3d = mask_data["outlines"]
if mask_3d.ndim == 3:
mask_3d[self._slice_id, :, :] = mask
if outline_3d.ndim == 3:
outline_3d[self._slice_id, :, :] = outline
self._mask_data = {"masks": mask if self._slice_id == -1 else mask_3d,
"outlines": outline if self._slice_id == -1 else outline_3d}
self.update_mask_image()
if not self._mask_image.visible:
self._mask_image.visible = True
self._mask_image.update()
self._mask_button.icon_color = ft.Colors.WHITE
self._mask_button.tooltip = "Hide mask"
self._mask_button.update()
np.save(self._mask_path, self._mask_data, allow_pickle=True)
self.on_mask_change(self._image_id)
def _delete_cell(self, pos: tuple | int):
#delete the cell in the mask data
if self._mask_path is None:
return
if self._mask_data is None:
self._mask_data = np.load(self._mask_path, allow_pickle=True).item()
mask = self._mask_data["masks"].astype(np.uint16)
outline = self._mask_data["outlines"].astype(np.uint16)
if mask.ndim == 3:
if self._slice_id < 0:
raise ValueError("slice_id should be non-negative")
mask = np.take(mask, self._slice_id, axis=0).astype(np.uint16)
if outline.ndim == 3:
if self._slice_id < 0:
raise ValueError("slice_id should be non-negative")
outline = np.take(outline, self._slice_id, axis=0).astype(np.uint16)
cell_id = pos if type(pos) != tuple else _get_cell_id_from_position(pos, mask)
if not cell_id:
cell_id_outline = _get_cell_id_from_position(pos, outline)
if not cell_id_outline:
return
cell_id = cell_id_outline
# Update the mask and outline (delete the cell)
cell_mask = (mask == cell_id).copy()
cell_outline = (outline == cell_id).copy()
# add line data to the undo stack to draw the cell later out of the line
self._undo_stack.append(("draw_action", cell_outline))
self._undo_button.icon_color = ft.Colors.WHITE_60
self._undo_button.disabled = False
self._undo_button.update()
#------
mask[cell_mask] = 0
outline[cell_outline] = 0
if self._shifting_check_box.selected:
mask_shifting(self._mask_data, cell_id, self._slice_id)
mask_3d = None
outline_3d = None
if self._slice_id >= 0:
mask_3d = self._mask_data["masks"]
outline_3d = self._mask_data["outlines"]
if mask_3d.ndim == 3:
mask_3d[self._slice_id, :, :] = mask
if outline_3d.ndim == 3:
outline_3d[self._slice_id, :, :] = outline
final_masks = mask if self._slice_id == -1 else mask_3d
final_outlines = outline if self._slice_id == -1 else outline_3d
self._mask_data = {"masks": final_masks,
"outlines": final_outlines}
self.update_mask_image()
np.save(self._mask_path, self._mask_data, allow_pickle=True)
self.on_mask_change(self._image_id)
def delete_mask(self):
def cancel_dialog(a):
cupertino_alert_dialog.open = False
a.control.page.update()
def ok_dialog(a):
cupertino_alert_dialog.open = False
a.control.page.update()
if self._mask_path is not None:
if os.path.exists(self._mask_path):
os.remove(self._mask_path)
if self._mask_paths and self._image_id in self._mask_paths:
self._mask_paths[self._image_id].pop(self._seg_channel_id, None)
self._mask_path = None
self._mask_data = None
self._redo_stack.clear()
self._undo_stack.clear()
self._redo_button.disabled = True
self._undo_button.disabled = True
self._redo_button.icon_color = ft.Colors.BLACK_12
self._undo_button.icon_color = ft.Colors.BLACK_12
self._redo_button.update()
self._undo_button.update()
self.update_mask_image()
self.on_mask_change(self._image_id)
cupertino_alert_dialog = ft.CupertinoAlertDialog(
title=ft.Text("Delete Entire Mask"),
content=ft.Text("Are you sure you want to delete all drawn cells on this image?\n\n"
"The underlying mask file will be deleted. "
"You can always start over by drawing new cells, but the current state cannot be recovered with undo operations."),
actions=[
ft.CupertinoDialogAction(
"Cancel", default=True, on_click=cancel_dialog
),
ft.CupertinoDialogAction("Ok", destructive=True, on_click=lambda a: ok_dialog(a)),
],
)
self.page.overlay.append(cupertino_alert_dialog)
cupertino_alert_dialog.open = True
self.page.update()
def redo_stack(self,e):
if self._redo_stack.__sizeof__() == 0 or not self._mask_image.visible:
return
self._undo_button.icon_color = ft.Colors.WHITE_60
self._undo_button.disabled = False
self._undo_button.update()
first_list_item = self._redo_stack.pop()
if first_list_item[0] == "delete_action":
self._delete_cell(first_list_item[1])
elif first_list_item[0] == "draw_action":
self._cell_drawn(first_list_item[1])
else:
raise KeyError("no valid action for redo button")
if len(self._redo_stack) == 0:
self._redo_button.icon_color = ft.Colors.BLACK_12
self._redo_button.disabled = True
self._redo_button.update()
if len(self._undo_stack) == 0:
self._undo_button.icon_color = ft.Colors.BLACK_12
self._undo_button.disabled = True
self._undo_button.update()
def undo_stack(self,e):
if self._undo_stack.__sizeof__() == 0 or not self._mask_image.visible:
return
self._redo_button.icon_color = ft.Colors.WHITE_60
self._redo_button.disabled = False
self._redo_button.update()
first_list_item = self._undo_stack.pop()
if first_list_item[0] == "delete_action":
self._delete_cell(first_list_item[1])
elif first_list_item[0] == "draw_action":
self._cell_drawn(first_list_item[1])
else:
raise KeyError("no valid action for undo button")
self._redo_stack.append(self._undo_stack.pop())
if len(self._redo_stack) == 0:
self._redo_button.icon_color = ft.Colors.BLACK_12
self._redo_button.disabled = True
self._redo_button.update()
if len(self._undo_stack) == 0:
self._undo_button.icon_color = ft.Colors.BLACK_12
self._undo_button.disabled = True
self._undo_button.update()