-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·2147 lines (1710 loc) · 82.7 KB
/
main.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
"""
Written by: Pete, 2023, (peterlionelnewman @ github)
Helpful for students
1. GUI interface to:
2. search a folder for .czi files
3. export mips of various kinds for each czi channel
4. morphometrics about the images
Go check out the Allen Institue of Cell Science package !!!
This exists to help students with mip generation, and because of the bugs in the mosaic builder
"""
# std
import csv
import sys
from functools import partial
import itertools
import os
from multiprocessing import Pool, cpu_count
import pickle
import platform
import re
import time
from tkinter.filedialog import askdirectory
import tkinter as tk
from tkinter import ttk
import warnings
import xml.etree.ElementTree as ET
# 3rd
import aicspylibczi
import attr
from cellpose import models
import cv2
from itertools import product
from matplotlib import pyplot as plt
import numpy as np
from PIL import Image, ImageOps, ImageDraw, ImageFont, ImageChops, ImageTk
import pyvista as pv
from readlif.reader import LifFile
from scipy.ndimage import zoom, binary_fill_holes, distance_transform_edt, binary_dilation, binary_erosion
from skimage.measure import regionprops, label
from skimage import morphology
from torch import device
import torch
from tqdm import tqdm
import webcolors
global SO, DEVICE
if torch.cuda.is_available():
print("CUDA is available. PyTorch can use GPUs!")
DEVICE = torch.device('cuda')
elif torch.backends.mps.is_available():
print("PyTorch using GPU on mac.")
DEVICE = torch.device('mps')
else:
print("CPU ONLY. PyTorch can only use CPUs.")
DEVICE = torch.device('cpu')
@attr.s(auto_attribs=True, auto_detect=True)
class ProcessOptions:
# image path
image_path: str = attr.ib(default='')
save_path: str = attr.ib(default='')
# save options
save_mip_channels: bool = attr.ib(default=False)
save_mip_panel: bool = attr.ib(default=True)
save_mip_merge: bool = attr.ib(default=False)
save_dye_overlaid: bool = attr.ib(default=True)
save_colors: bool = attr.ib(default=True)
use_multiprocessing: bool = attr.ib(default=False)
# segmentation options
segment_image: bool = attr.ib(default=False)
mask_ch: int = attr.ib(default=0)
cyto: bool = attr.ib(default=False)
nuc: bool = attr.ib(default=False)
channels_of_interest: list = attr.ib(default=[0])
# same_for_all_images: bool = attr.ib(default=False)
def __setattr__(self, name, value):
super().__setattr__(name, value)
if name == 'image_path':
self.save_path = os.path.join(os.path.dirname(value), 'save')
@attr.s(auto_attribs=True, auto_detect=True)
class SegmentationOptions:
mask_channel_var: int = attr.ib(default=0)
cyto_var: bool = attr.ib(default=False)
nuc_var: bool = attr.ib(default=True)
segment_2D: bool = attr.ib(default=True)
segment_3D: bool = attr.ib(default=False)
same_for_all_images_var: bool = attr.ib(default=True)
channel_vars: list = attr.ib(default=[0])
mask_channel: int = attr.ib(default=0)
channels_of_interest_vars: list = attr.ib(default=[])
@attr.s(auto_attribs=True, auto_detect=True)
class MaskProperties2D:
centroid: np.array = attr.ib(default=np.array([[],[]]).T)
id: np.array = attr.ib(default=np.array([]))
area: np.array = attr.ib(default=np.array([]))
perimeter: np.array = attr.ib(default=np.array([]))
form_factor: np.array = attr.ib(default=np.array([]))
minor_ax: np.array = attr.ib(default=np.array([]))
major_ax: np.array = attr.ib(default=np.array([]))
eccentricity: np.array = attr.ib(default=np.array([]))
convexity: np.array = attr.ib(default=np.array([]))
orientation: np.array = attr.ib(default=np.array([]))
mask_sat: np.array = attr.ib(default=np.array([]))
tf_sat: np.array = attr.ib(default=np.array([]))
dist_from_edge: np.array = attr.ib(default=np.array([]))
@attr.s(auto_attribs=True, auto_detect=True)
class MaskProperties3D:
id: np.array = attr.ib(default=np.array([]))
volume: np.array = attr.ib(default=np.array([]))
centroid: np.array = attr.ib(default=np.array([[], [], []]).T)
surface_area: np.array = attr.ib(default=np.array([]))
sphericity: np.array = attr.ib(default=np.array([]))
major_ax: np.array = attr.ib(default=np.array([]))
minor_ax: np.array = attr.ib(default=np.array([]))
least_ax: np.array = attr.ib(default=np.array([]))
eccentricity: np.array = attr.ib(default=np.array([]))
convexity: np.array = attr.ib(default=np.array([]))
orientation: np.array = attr.ib(default=np.array([]))
mask_sat: np.array = attr.ib(default=np.array([]))
tf_sat: np.array = attr.ib(default=np.array([[], []]).T)
@attr.s(auto_attribs=True, auto_detect=True)
class BioImage:
"""
czi image class for lite image processing
wrapper class around the ACIS wrapper class;
around the czilib library
"""
path: str = attr.ib(default='')
imfile: aicspylibczi.CziFile = attr.ib(default=None)
czi: tuple = attr.ib(default=())
im: np.ndarray = attr.ib(default=[0., 0.])
cell_mass: np.ndarray = attr.ib(default=[0., 0.])
mosaic: np.ndarray = attr.ib(default=[0., 0.])
num_channels: int = attr.ib(default=0)
num_z_slices: int = attr.ib(default=0)
height: int = attr.ib(default=0)
width: int = attr.ib(default=0)
num_timepoints: int = attr.ib(default=0)
num_scenes: int = attr.ib(default=0)
num_blocks: int = attr.ib(default=0)
num_mosaics: int = attr.ib(default=0)
metadata: str = attr.ib(default='')
nmip: np.ndarray = attr.ib(default=[0., 0.])
mip: np.ndarray = attr.ib(default=[0., 0.])
colours: list = attr.ib(default=[])
dyes: list = attr.ib(default=[])
scale: np.array = attr.ib(default=[1., 1., 1.])
bbox: np.array = attr.ib(default=np.array([0., 0.]))
mask: np.ndarray = attr.ib(default=np.array([]))
mask_ch: int = attr.ib(default=0)
mask_props: MaskProperties2D = attr.ib(default=MaskProperties2D())
big_image: bool = attr.ib(default=False)
def load_tif(self):
"""
load a tif file
"""
# get the number of channels, z_slices and shape
os.chdir(os.path.dirname(self.path))
all_images = []
self.num_channels = 0
# search for tif files with same name
for root, _, files in os.walk(os.path.dirname(self.path)):
for file in files:
if file.endswith('.tif'):
# this line was put in here to deal with Leica/LSX exporting tif files with suffix - stalled Ben with some stuff
temp_path = self.path.replace('_overlay.tif', '.tif').replace('_SV.tif', '.tif')
if file[:2] == '._' and sys.platform.startswith('win'): # for windows
continue
if file[0] == '.' and sys.platform == 'darwin': # for mac
continue
if os.path.basename(temp_path)[:-4] in file \
and not file == os.path.basename(temp_path):
all_images.append(file)
self.num_channels += 1
self.num_z_slices = 1
if not all_images:
print('No tif files found')
return
(self.width, self.height, _) = plt.imread(all_images[0]).shape
self.metadata = ''
self.scale = -1
self.im = np.zeros((self.num_channels, self.num_z_slices, self.height, self.width))
self.colours = []
self.dyes = []
# convert im to f64
for c in range(self.num_channels):
im = plt.imread(all_images[c]).astype(np.float64)
# Get the R, G, and B channels
r, g, b = im[:, :, 0], im[:, :, 1], im[:, :, 2]
# r, g, b = im[:, :, 1], im[:, :, 2], im[:, :, 0]
# Calculate the grayscale image
try:
self.im[c, 0, :, :] = 0.2989 * r + 0.5870 * g + 0.1140 * b
except:
self.im[c, 0, :, :] = 0.2989 * r.T + 0.5870 * g.T + 0.1140 * b.T
color = [r.max(), g.max(), b.max()]
color /= np.max(color)
color = (color * 255).astype(int)
self.colours.append(color)
self.dyes.append(webcolors.rgb_to_name(color))
self.scale = np.array([1., 1., 1.])
def load_czi(self):
"""
load a czi file
"""
# get the image
if self.path.endswith('.czi'):
self.imfile = aicspylibczi.CziFile(self.path)
else:
# Set color to red
print('\033[91m', end='')
print(f'Failed to process: {self.path}')
# Reset color to default
print('\033[0m', end='')
dims = self.imfile.get_dims_shape()[0]
if dims['X'][1] == 0 and dims['Y'][1] == 0:
return 'metadata_only'
# get the number of channels, z_slices and shape
self.num_channels = dims['C'][1]
self.num_z_slices = dims['Z'][1]
self.width = dims['X'][1]
self.height = dims['Y'][1]
self.metadata = self.imfile.meta
# looks like the first 3 distance/values are camera props?
self.scale = np.array([float(self.metadata.findall('.//Distance/Value')[i].text) for i in range(3, 6)])[::-1]
self.scale = self.scale * 1e6
# load each image
if self.imfile.is_mosaic():
# additional checks
if not 'M' in dims:
raise ValueError('Mosaic image found, but no M dimension found')
# load in all the bounding boxes
self.num_mosaics = dims['M'][1]
self.bbox = np.zeros((self.num_mosaics, 4)).astype(int)
for m in range(self.num_mosaics):
_ = self.imfile.get_mosaic_tile_bounding_box(C=0, Z=0, M=m)
self.bbox[m, :] = int(_.x), int(_.y), int(_.w), int(_.h)
# check that w and h is the same
if not np.all(self.bbox[:, 2] == self.bbox[0, 2]) or not np.all(self.bbox[:, 3] == self.bbox[0, 3]):
raise ValueError('Mosaic bounding boxes are not the same size')
# simplify the box
self.bbox[:, 0] = self.bbox[:, 0] - np.min(self.bbox[:, 0])
self.bbox[:, 1] = self.bbox[:, 1] - np.min(self.bbox[:, 1])
# initialize the image
self.width = np.max(self.bbox[:, 0]) + self.bbox[0, 2]
self.height = np.max(self.bbox[:, 1]) + self.bbox[0, 3]
# get the 'im' == (czyx)
self.mosaic = np.moveaxis(self.imfile.read_image()[0],
[self.imfile.dims.index('C'),
self.imfile.dims.index('Z'),
self.imfile.dims.index('Y'),
self.imfile.dims.index('X'),
self.imfile.dims.index('M')],
[0, 1, 2, 3, 4])
# index the last dimensions at 0
for i in range(len(dims) - 5):
self.mosaic = self.mosaic[..., 0]
# look at the size of im and cry if really large
if (self.mosaic.nbytes / 1e9) > 5:
self.big_image = True
print(f'WARNING: Image size is {self.mosaic.nbytes / 1e9} GB, this may cause memory issues')
return
# move the mosaics into im - some rounding bug? means I need to add 1 to the width and height
self.im = np.zeros((self.num_channels, self.num_z_slices, self.height + 1, self.width + 1))
print(f'loading mosaic')
for m in range(self.num_mosaics):
if m % (self.num_mosaics // 10) == 0:
print(f'.', end='')
self.im[:, :, self.bbox[m, 1]:self.bbox[m, 1] + self.bbox[m, 3], self.bbox[m, 0]:self.bbox[m, 0] + self.bbox[m, 2]] = self.mosaic[:, :, :, :, m]
else:
self.im = self.imfile.read_image()
# get the 'im' == (czyx)
self.im = np.moveaxis(self.im[0],
[self.imfile.dims.index('C'),
self.imfile.dims.index('Z'),
self.imfile.dims.index('Y'),
self.imfile.dims.index('X')],
[0, 1, 2, 3])
# index the last dimensions at 0
for i in range(len(dims) - 4):
self.im = self.im[..., 0]
# convert im to f64
self.im = self.im.astype(np.float64)
# get the other info:
if 'T' in dims: # timepoints
# self.num_timepoints = dims['T'][1]
# warnings.warn('this script throws away this info')
pass
if 'S' in dims: # scenes
pass
if 'B' in dims: # blocks
pass
if 'V' in dims:
# The V-dimension ('view').
pass
if 'I' in dims:
# The I-dimension ('illumination').
pass
if 'R' in dims:
# The R-dimension ('rotation').
pass
if 'H' in dims:
# The H-dimension ('phase').
pass
def load_lif(self):
"""
load a lif file
"""
# get the image
if path.endswith('.lif'):
self.imfile = LifFile(self.path)
else:
# Set color to red
print('\033[91m', end='')
print(f'Failed to process: {path}')
# Reset color to default
print('\033[0m', end='')
return
dims = self.imfile.image_list[0]
if dims['dims'].x == 0 and dims['dims'].y == 0:
return 'metadata_only'
# get the number of channels, z_slices and shape
self.num_channels = dims['channels']
self.num_z_slices = dims['dims'].z
self.width = dims['dims'].x
self.height = dims['dims'].y
# get scale
self.scale = np.array(self.imfile.image_list[0]['scale'][0:3])
if self.scale[2] == None:
self.scale[2] = 0
self.scale = self.scale[::-1] # xyz to zyx
# load each image for mosaics
if dims['dims'].m > 1:
# Set color to red
print('\033[91m', end='')
print(f'Pete hasn''t implemened mosaics yet:')
# Reset color to default
print('\033[0m', end='')
return
# TBD additional checks
if not 'M' in dims:
raise ValueError('Mosaic image found, but no M dimension found')
# TDB look at the size of im and cry if really large
if (self.mosaic.nbytes / 1e9) > 5:
self.big_image = True
print(
f'WARNING: Image size is {self.im.nbytes / 1e9} GB, this will cause memory issues')
return
# load each image for non-mosaics
else:
# create an empty array C-Z-Y-X
self.im = np.zeros((self.num_channels, self.num_z_slices, self.height, self.width))
for c in range(self.num_channels):
for z in range(self.num_z_slices):
self.im[c, z, :, :] = self.imfile.get_image(0).get_frame(z=z, t=0, c=c)
# convert im to f64
self.im = self.im.astype(np.float64)
# get the other info:
if dims['dims'].t > 1: # timepoints
token = 'T'
self.num_timepoints = dims['dims'].t
warnings.warn(f'this script throws away this info: {token}')
pass
def extract_colors(self):
if self.path.endswith('.lif'):
self.metadata = xml_to_dict(self.imfile.xml_header)
# not sure whats up with lif files, they dont seem to store laser or dye info?
results = []
def find_key(dictionary, target):
for key, value in dictionary.items():
if key == target:
results.append(value)
elif isinstance(value, dict):
find_key(value, target)
find_key(self.metadata, 'dye')
find_key(self.metadata, 'color')
find_key(self.metadata, 'laser')
# assuming colors are in order blue to red
self.colours = []
self.dyes = []
for c in range(self.num_channels):
if c == 0:
self.colours.append([0, 255, 255])
self.dyes.append('cyan')
elif c == 1:
self.colours.append([255, 255, 0])
self.dyes.append('yellow')
elif c == 2:
self.colours.append([255, 0, 0])
self.dyes.append('red')
elif c == 3:
self.colours.append([255, 0, 255])
self.dyes.append('magenta')
elif c == 4:
self.colours.append([255, 255, 255])
self.dyes.append('white')
elif self.path.endswith('.czi'):
self.metadata = self.imfile.meta
dyes = self.metadata.findall('.//DyeName')
# looks like the first 3 distance/values are camera props?
self.scale = np.array([float(self.metadata.findall('.//Distance/Value')[i].text) for i in range(3, 6)])[::-1]
if len(dyes) != self.num_channels:
warnings.warn('num channel != num dyes')
return
self.dyes = [None] * self.num_channels
for c in range(self.num_channels):
self.dyes[c] = dyes[c].text
if 'DAPI' in self.dyes[c]\
or 'dapi' in self.dyes[c] \
or 'Hoechst 33342' in self.dyes[c] \
or 'Hoechst 33258' in self.dyes[c]:
self.colours.append([0, 255, 255])
continue
elif 'FITC' in self.dyes[c]:
self.colours.append([255, 255, 0])
continue
elif 'Cy3' in self.dyes[c] or 'Rhodamine' in self.dyes[c]:
self.colours.append([255, 0, 0])
continue
elif 'Cy5' in self.dyes[c]:
self.colours.append([255, 0, 255])
continue
# extract all numbers from dye
try:
dye_nums = float(re.findall(r'\d+', self.dyes[c])[0])
except:
dye_nums = -1
if dye_nums < 0:
self.colours.append([255, 255, 255])
elif dye_nums < 405:
self.colours.append([0, 255, 255])
elif dye_nums < 500:
self.colours.append([255, 255, 0])
elif dye_nums < 600:
self.colours.append([255, 0, 0])
elif dye_nums < 700:
self.colours.append([255, 0, 255])
else:
self.colours.append([0, 0, 0])
warnings.warn(f'no color found for {self.path}; channel {c}, {self.dyes[c]}')
def project_mip(self, side_projections=False, z_scale=1):
"""
make a maximum intensity projection
"""
# check for z slices
if self.num_z_slices == 1:
print('\033[96m', end='')
print(f'no z slices found in {self.path} returning')
print('\033[0m', end='')
self.mip = np.zeros((self.num_channels,
self.im.shape[2],
self.im.shape[3]))
for c in range(self.num_channels):
self.mip[c, :, :] = self.im[c, 0, :, :]
return
# initialize the mip
if side_projections:
if not self.big_image:
self.mip = np.zeros((self.num_channels,
self.im.shape[2] + self.im.shape[1] * z_scale + 1,
self.im.shape[3] + self.im.shape[1] * z_scale + 1))
for c in range(self.num_channels):
# check for z slices
self.mip[c,
0:self.im.shape[2],
0:self.im.shape[3]] = np.max(self.im[c, :, :, :], axis=0)
projection_yz = np.max(self.im[c, :, :, :], axis=1)
projection_yz = zoom(projection_yz, (z_scale, 1))
self.mip[c,
(self.im.shape[2] + 1):(self.im.shape[2] + 1 + self.im.shape[1] * z_scale),
0:self.im.shape[3]] = projection_yz
projection_xz = np.max(self.im[c, :, :, :], axis=2).T
projection_xz = zoom(projection_xz, (1, z_scale))
self.mip[c,
0:self.im.shape[2],
(self.im.shape[3] + 1):(self.im.shape[3] + 1 + self.im.shape[1] * z_scale)] = projection_xz
return
if self.big_image:
self.mip = np.zeros((self.num_channels,
self.height + self.num_z_slices * z_scale + 1,
self.width + self.num_z_slices * z_scale + 1))
for m in tqdm(range(self.num_mosaics), desc=f'Generating mip for *big image*:'):
if m % (self.num_mosaics // 10) == 0:
print(f'.', end='')
for c in range(self.num_channels):
self.mip[c,
self.bbox[m, 1]:self.bbox[m, 1] + self.bbox[m, 3],
self.bbox[m, 0]:self.bbox[m, 0] + self.bbox[m, 2]] = np.max(self.mosaic[c, :, :, :, m], axis=0)
projection_yz = np.max(self.mosaic[c, :, :, :, m], axis=1)
projection_yz = zoom(projection_yz, (z_scale, 1))
self.mip[c,
-(self.num_z_slices * z_scale + 1):-1,
self.bbox[m, 0]:self.bbox[m, 0] + self.bbox[m, 2]] = projection_yz
projection_xz = np.max(self.mosaic[c, :, :, :, m], axis=2).T
projection_xz = zoom(projection_xz, (1, z_scale))
self.mip[c,
self.bbox[m, 1]:self.bbox[m, 1] + self.bbox[m, 3],
-(self.num_z_slices * z_scale + 1):-1,] = projection_xz
return
else:
if not self.big_image:
self.mip = np.zeros((self.num_channels,
self.im.shape[2],
self.im.shape[3]))
for c in range(self.num_channels):
self.mip[c, :, :] = np.max(self.im[c, :, :, :], axis=0)
return
if self.big_image:
self.mip = np.zeros((self.num_channels,
self.height + 1,
self.width + 1))
for m in tqdm(range(self.num_mosaics), desc=f'Generating mip for *big image*:'):
for c in range(self.num_channels):
self.mip[c,
self.bbox[m, 1]:self.bbox[m, 1] + self.bbox[m, 3],
self.bbox[m, 0]:self.bbox[m, 0] + self.bbox[m, 2]] = np.max(self.mosaic[c, :, :, :, m], axis=0)
def normalize(self, max=False, gamma=1):
"""
modifies '.mip' normalizing the image
"""
if self.mip == [0, 0]:
print('No mip to normalize')
return
self.nmip = np.zeros((self.num_channels, self.mip.shape[2], self.mip.shape[1]))
for c in range(self.num_channels):
if max:
mip = (self.mip[c, :, :] - np.nanmin(self.mip[c, :, :])) / \
(np.nanmax(self.mip[c, :, :]) - np.nanmin(self.mip[c, :, :]))
else:
mip = self.mip[c, :, :] - np.nanmin(self.mip[c, :, :])
if np.nansum(mip) != 0:
mip_p = np.percentile(mip, 99.8)
mip[mip > mip_p] = mip_p
mip = mip/mip_p
if gamma != 1:
mip = mip ** gamma
try:
self.nmip[c, :, :] = mip * 255
except:
self.nmip[c, :, :] = mip.T * 255
def save(self,
save_path,
save_mip_channels,
save_mip_panel,
save_mip_merge,
save_dye_overlaid,
save_colors):
if self.mip == [0, 0]:
print('No mip to save')
return
cwd = os.getcwd()
try:
os.chdir(os.path.dirname(self.path))
except:
os.mkdir(os.path.dirname(self.path))
os.chdir(os.path.dirname(self.path))
if self.big_image:
optimize = False
else:
optimize = True
file_stem = os.path.splitext(os.path.basename(self.path))[0]
for c in range(self.num_channels):
# PIL on each channel
mip = Image.fromarray(self.mip[c, :, :])
mip = mip.convert('L')
base = np.ceil(self.num_channels ** 0.5).astype('int')
if save_colors and len(self.colours[c]) > 0:
mip = ImageOps.colorize(mip, (0, 0, 0), tuple(self.colours[c]))
else:
mip = mip.convert('RGB')
if save_dye_overlaid:
font_color = tuple(self.colours[c])
font_size = self.height // 50
draw = ImageDraw.Draw(mip)
if platform == 'linux' or platform == 'linux2' or platform == 'darwin':
text_overlay = [[]]
text_overlay.append(c * ['\n'])
text_overlay.append([self.dyes[c]])
text_overlay = ''.join([item for sublist in text_overlay for item in sublist])
draw.text((0, 0), text_overlay,
font_color,
ImageFont.truetype('Arial.ttf', size=font_size))
elif platform == 'win32':
draw.text((0, 0), self.dyes[c],
font_color,
ImageFont.truetype('arial.ttf', size=font_size))
# create an image of all 'c' merged
if save_mip_merge or \
save_mip_panel and self.num_channels > 1 and self.num_channels < base ** 2:
if c == 0:
self.mip_merge = mip.copy()
else:
self.mip_merge = Image.merge('RGB', (
ImageChops.add(self.mip_merge.getchannel('R'), mip.getchannel('R')),
ImageChops.add(self.mip_merge.getchannel('G'), mip.getchannel('G')),
ImageChops.add(self.mip_merge.getchannel('B'), mip.getchannel('B'))))
if c == 0:
self.mip_panel = np.zeros((mip.height * base, mip.width * base, 3))
self.mip_panel[c % base * mip.height:(c % base + 1) * mip.height,
c // base * mip.width:(c // base + 1) * mip.width,
:] = np.array(mip).copy()
# save
if save_mip_channels:
# mip.save(f'{file_stem}_ch{c}_.png', optimize=optimize)
cv2.imwrite(f'{file_stem}_ch{c}_.png', cv2.cvtColor(np.array(mip), cv2.COLOR_RGB2BGR))
# save merged images
if save_mip_merge:
# self.mip_merge.save(f'{file_stem}_merge.png', optimize=optimize)
cv2.imwrite(f'{file_stem}_merge.png', cv2.cvtColor(np.array(self.mip_merge), cv2.COLOR_RGB2BGR))
# save panel images
if save_mip_panel and self.num_channels > 1:
# add the merge to the panel if there is space
if self.num_channels < base ** 2:
self.mip_panel[self.num_channels % base * mip.height:(self.num_channels % base + 1) * mip.height,
self.num_channels // base * mip.width:(self.num_channels // base + 1) * mip.width,
:] \
= np.array(self.mip_merge).copy()
# remove black space
self.mip_panel = self.mip_panel[~np.all(self.mip_panel == 0, axis=(1, 2))]
# save mip panel cv2 (is much faster)
cv2.imwrite(f'{file_stem}_panel.png',
cv2.cvtColor(self.mip_panel.astype('uint8'), cv2.COLOR_RGB2BGR))
print(f'converted {file_stem} and saved')
os.chdir(cwd)
def combine_big_image_masks(self, mask):
mask = np.transpose(mask, (2, 1, 0))
# define mosaic bounds
window_size = 200
overlap = 100
mask = mask[::-1]
yl = np.hstack([0, np.arange(window_size - overlap, mask.shape[1], window_size)])
yu = np.hstack([window_size, np.arange(window_size - overlap + window_size, mask.shape[1], window_size), mask.shape[1]])
xl = np.hstack([0, np.arange(window_size - overlap, mask.shape[2], window_size)])
xu = np.hstack([window_size, np.arange(window_size - overlap + window_size, mask.shape[2], window_size), mask.shape[2]])
# process a mosaic of the areas (speeds up processing significantly due to morphological ops)
my = np.vstack([yl, yu]).T
mx = np.vstack([xl, xu]).T
mosaic = product(my, mx)
if not np.any(mask):
print(f'\033[94mError: {self.path} has no labels\033[0m')
return
combine_threshold = 0.7
for nm, m in enumerate(mosaic):
# get the mask for this mosaic
vol = mask[:, m[1][0]:m[1][1], m[0][0]:m[0][1]]
for nz in range(1, vol.shape[0]):
slice_j = vol[nz, :, :]
slice_i = vol[nz - 1, :, :]
# # get id for slices
# slice_j_labels = np.unique(slice_j)
# slice_i_labels = np.unique(slice_i)
check_labels_mask = slice_i - slice_j < 0
# check_labels_j = slice_j_labels * check_labels_mask
# check_labels_i = slice_i_labels * check_labels_mask
check_labels_j = slice_j * check_labels_mask
check_labels_i = slice_i * check_labels_mask
uni_slice_j = np.unique(check_labels_j)
uni_slice_i = np.unique(check_labels_i)
uni_slice_j = uni_slice_j[uni_slice_j != 0]
uni_slice_i = uni_slice_i[uni_slice_i != 0]
# check that theres something in both slices
if reduction(uni_slice_j, np.logical_or, 'any', None, None, None) \
and reduction(uni_slice_i, np.logical_or, 'any', None, None, None):
for j in uni_slice_j:
for i in uni_slice_i:
img_j = np.array(slice_j == j)
img_i = np.array(slice_i == i)
img_ij = np.logical_and(img_i, img_j)
sum_img_j = img_j.sum()
if sum_img_j > 2000: # remove the object if its got a really big 2D size note doesnt work for slice 0 objects
slice_j[slice_j == j] = 0
changed = True
elif reduction(img_ij, np.logical_or, 'any', None, None, None):
# if an object on adjacent layers has an intersection > 'combine_threshold' make them the same
sum_img_i = img_i.sum()
sum_img_ij = img_ij.sum()
if sum_img_ij / sum_img_i > combine_threshold or sum_img_ij / sum_img_j > combine_threshold:
slice_j[slice_j == j] = i
changed = True
if changed:
mask[nz, m[1][0]:m[1][1], m[0][0]:m[0][1]] = slice_j
# condense the mask
mask = np.max(mask, axis=0)
# convert back to xy
mask = np.transpose(mask, (1, 0))
return mask
def process_2d_mask(self):
print('processing 2D mask...')
# process vars
count = 0
try:
SO.channels_of_interest_vars[0].get()
ch_of_interest = [i.get() for i in SO.channels_of_interest_vars]
except:
ch_of_interest = [i for i in SO.channels_of_interest_vars]
self.mask_props = MaskProperties2D()
if not len(self.mask.shape) == 2:
print(f'\033[94mError: {self.path} isn''t 2D?\033[0m')
return
# rescale image to make yx of an pixel the same, then 1 µm, or if scale < 1 µm, scale.min()
min_scale = np.min(np.hstack([self.scale[1::], 1]))
zoom_by = self.scale[1::] / min_scale
im = np.zeros(np.hstack([self.num_channels, (np.array(self.mip.shape[1::]) * zoom_by).astype('int')]))
for c in range(self.num_channels):
im[c, :, :] = zoom(np.squeeze(self.mip[c, :, :]), zoom_by, order=1)
mask = zoom(self.mask, zoom_by, order=0)
# define mosaic bounds
window_size = 200
overlap = 100
yl = np.hstack([0, np.arange(window_size - overlap, im.shape[1], window_size)])
yu = np.hstack([window_size, np.arange(window_size - overlap + window_size, im.shape[1], window_size), im.shape[1]])
xl = np.hstack([0, np.arange(window_size - overlap, im.shape[2], window_size)])
xu = np.hstack([window_size, np.arange(window_size - overlap + window_size, im.shape[2], window_size), im.shape[2]])
# process a mosaic of the areas (speeds up processing significantly due to morphological ops)
my = np.vstack([yl, yu]).T
mx = np.vstack([xl, xu]).T
mosaic = product(my, mx)
if not np.any(mask):
print(f'\033[94mError: {self.path} has no labels\033[0m')
return
mask_id_processed = np.array([0])
for nm, m in enumerate(mosaic):
# get the mask for this mosaic
area = mask[m[1][0]:m[1][1], m[0][0]:m[0][1]]
area_im = im[:, m[1][0]:m[1][1], m[0][0]:m[0][1]]
# if there are no labels in this area, skip
if not np.any(area):
continue
# remove mask ids that have already been processed
area_id = np.unique(area)
# if area_id is in mask_id_processed, remove it
for i in np.intersect1d(area_id, mask_id_processed):
area[area == i] = 0
area_id = np.unique(area)
area_id = area_id[area_id != 0]
rp = regionprops(area)
for rn, r in enumerate(rp):
# filter out large & small objects
if r.area < 10 or r.area > 10_000:
continue
# save properties
self.mask_props.id = np.hstack((self.mask_props.id, area_id[rn]))
self.mask_props.area = np.hstack((self.mask_props.area, r.area))
self.mask_props.centroid = np.vstack((self.mask_props.centroid, np.array(r.centroid) + np.array([m[1][0], m[0][0]])))
self.mask_props.perimeter = np.hstack((self.mask_props.perimeter, r.perimeter))
self.mask_props.form_factor = np.hstack((self.mask_props.form_factor, r.perimeter ** 2 / r.area))
self.mask_props.minor_ax = np.hstack((self.mask_props.minor_ax, r.minor_axis_length))
self.mask_props.major_ax = np.hstack((self.mask_props.major_ax, r.major_axis_length))
self.mask_props.eccentricity = np.hstack((self.mask_props.eccentricity, r.eccentricity))
self.mask_props.convexity = np.hstack((self.mask_props.convexity, r.convex_area / r.area))
self.mask_props.orientation = np.hstack((self.mask_props.orientation, r.orientation))
# saturation intensity in mask of the other channels
try:
tf_sat = np.hstack([
np.mean(area_im[c][r.coords[:, 0], r.coords[:, 1]])
for c in range(self.num_channels)
])
except:
tf_sat = np.hstack([
np.mean(area_im[c].T[r.coords[:, 1], r.coords[:, 0]])
for c in range(self.num_channels)
])
if count == 0:
self.mask_props.tf_sat = tf_sat
else:
self.mask_props.tf_sat = np.vstack((self.mask_props.tf_sat, tf_sat))
count += 1
# add all area_id to mask_id_processed
mask_id_processed = np.hstack([area_id, mask_id_processed])
# calculate distance of each cell in mask from edge of cell mass
print('Calculating distances of cells from edge of cell mass...')
# cellpose_model = models.Cellpose(gpu=True, model_type='nuclei')
# nuc_mask = cellpose_model.eval(
# self.nmip[nuclear_channel].astype(np.uint8),
# diameter=diam,
# flow_threshold=flow_threshold,
# cellprob_threshold=cellprob_threshold)[0]
# # region props centroids
# properties = regionprops(label(nuc_mask))
# centroids = np.array([prop.centroid for prop in properties]).astype(np.int64)
#
# threshold = 1
# cell_mass = (nuc_mask > 0 * (threshold + 1)).astype(np.float64)
# tri_upper_ind = np.triu_indices(centroids.shape[0], k=1)
# centroid_combinations = centroids[np.array(tri_upper_ind)]
#
# # thin out centroid combinations
# dist = centroid_combinations[0, :, :] - centroid_combinations[1, :, :]
# dist = (dist[:, 0] ** 2 + dist[:, 1] ** 2) ** 0.5
# dist = dist < cell_mass.shape[1] / 2
# centroid_combinations = centroid_combinations[:, dist, :]
#
# z = np.zeros_like(cell_mass).astype(np.float64)
# for c1, c2 in tqdm(centroid_combinations.transpose((1, 0, 2)), total=centroid_combinations.shape[1]):
# temp = z.copy()
# cell_mass += cv2.line(temp, c1[::-1], c2[::-1], (1,), 5).astype(np.float64) / centroid_combinations.shape[1]
#
combo = self.nmip.astype(np.float64)
combo = combo.sum(axis=0)
combo = combo / combo.max() * 255
combo = combo.astype(np.uint8)
# bw = 255 - cv2.adaptiveThreshold(combo, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 5)
combo = cv2.medianBlur(combo, 33)
th, _ = cv2.threshold(combo, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
bw = combo > (th * 0.33)
bw = np.pad(bw, 2, 'constant', constant_values=255)
bw[0:2,0:2] = 0
bw[0:2,-3:-1] = 0
bw[-3:-1,0:2] = 0
bw[-3:-1,-3:-1] = 0
bw = bw > 0
bw = binary_fill_holes(bw)
bw = bw[2:-2, 2:-2]
diam = np.mean(self.mask_props.area) + 3 * np.std(self.mask_props.area)