-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1383 lines (1101 loc) · 37.8 KB
/
app.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
from functools import reduce
import math
import os
import uuid
from enum import Enum
from typing import List, Optional
import numpy as np
import xarray as xr
from colorthief import ColorThief
from matplotlib import cm
from PIL import Image
from xarray_multiscale import multiscale
from xarray_multiscale.reducers import windowed_mean
import cv2
from mikro.api.schema import (
MetricFragment,
OmeroFileFragment,
RepresentationFragment,
RepresentationVariety,
ROIFragment,
ROIType,
ThumbnailFragment,
RoiTypeInput,
DatasetFragment,
StageFragment,
PositionFragment,
create_position,
create_metric,
create_roi,
create_stage,
create_thumbnail,
create_channel,
from_xarray,
get_representation,
OmeroRepresentationInput,
PhysicalSizeInput,
AffineMatrix,
RepresentationViewInput,
OmeroRepresentationInput,
PhysicalSizeInput,
InputVector,
create_era,
EraFragment,
TableFragment,
from_df,
)
import operator
from arkitekt import register, log, group
from functools import partial
from skimage import transform
from api.mikro import get_filedataset
import datetime
from typing import Tuple
from skimage import data
import skimage
from scipy import ndimage
from sklearn.cluster import DBSCAN
import pandas as pd
class Colormap(Enum):
VIRIDIS = partial(cm.viridis) # partial needed to make it register as an enum value
PLASMA = partial(cm.plasma)
@register(collections=["conversion", "rendering"])
def array_to_image(
rep: RepresentationFragment,
rescale=True,
max=True,
cm: Colormap = Colormap.VIRIDIS,
) -> ThumbnailFragment:
"""Thumbnail Image
Generates Thumbnail for the Image
Args:
rep (Representation): The to be converted Image
rescale (bool, optional): SHould we rescale the image to fit its dynamic range?. Defaults to True.
max (bool, optional): Automatically z-project if stack. Defaults to True.
cm: (Colormap, optional): The colormap to use. Defaults to Colormap.VIRIDIS.
Returns:
Thumbnail: The Thumbnail
"""
array = rep.data
cm = cm.value
if "z" in array.dims:
if not max:
raise Exception("Set Max to Z true if you want to convert image stacks")
array = array.max(dim="z")
if "t" in array.dims:
array = array.sel(t=0)
if "c" in array.dims:
# Check if we have to convert to monoimage
if array.c.size == 1:
array = array.sel(c=0)
if rescale is True:
log("Rescaling")
min, max = array.min(), array.max()
image = np.interp(array, (min, max), (0, 255)).astype(np.uint8)
else:
image = (array * 255).astype(np.uint8)
print(cm)
mapped = cm(image)
finalarray = (mapped * 255).astype(np.uint8)
else:
if array.c.size >= 3:
array = array.sel(c=[0, 1, 2]).transpose(*list("yxc")).data
elif array.c.size == 2:
# Two Channel Image will be displayed with a Dark Channel
array = np.concatenate(
[
array.sel(c=[0, 1]).transpose(*list("yxc")).data,
np.zeros((array.x.size, array.y.size, 1)),
],
axis=2,
)
if rescale is True:
log("Rescaling")
min, max = array.min(), array.max()
finalarray = np.interp(array.compute(), (min, max), (0, 255)).astype(
np.uint8
)
else:
finalarray = (array.compute() * 255).astype(np.uint8)
else:
raise NotImplementedError("Image Does not provide the channel Argument")
print("Final Array Shape", finalarray.shape)
temp_file = uuid.uuid4().hex + ".jpg"
aspect = finalarray.shape[0] / finalarray.shape[1]
img = Image.fromarray(finalarray)
img = img.convert("RGB")
if finalarray.shape[0] > 512:
img = img.resize((512, int(512 * aspect)), Image.Resampling.BILINEAR)
img.save(temp_file, quality=80)
ColorThief(temp_file)
# with open(temp_file, "rb") as image_file:
# hash = blurhash.encode(image_file, x_components=6, y_components=6)
# print(hash)
hash = None
print("Hash", hash)
major_color = None
# major_color = "#%02x%02x%02x" % color_thief.get_color(quality=3)
# print("Major Color", major_color)
th = create_thumbnail(
file=open(temp_file, "rb"),
rep=rep,
major_color=major_color,
blurhash=hash,
)
print("Done")
os.remove(temp_file)
return th
@register(collections=["quantitative"])
def measure_max(
rep: RepresentationFragment,
key: str = "max",
) -> MetricFragment:
"""Measure Max
Measures the maxium value of an image
Args:
rep (OmeroFiRepresentationFragmentle): The image
key (str, optional): The key to use for the metric. Defaults to "max".
Returns:
Representation: The Back
"""
return create_metric(
key=key, value=float(rep.data.max().compute()), representation=rep
)
@register(collections=["creation"])
def create_era_func(
name: str = "max",
) -> EraFragment:
"""Create Era Now
Creates an era with the current time as a starttime
Returns:
Representation: The Back
"""
return create_era(name=name, start=datetime.datetime.now())
@register(collections=["collection"])
def iterate_images(
dataset: DatasetFragment,
) -> RepresentationFragment:
"""Iterate Images
Iterate over all images in a dataset
Args:
rep (Dataset): The dataset
yields:
Representation: The image
"""
for x in get_filedataset(dataset).representations:
yield x
@register(collections=["quantitative"])
def measure_sum(
rep: RepresentationFragment,
key: str = "Sum",
) -> MetricFragment:
"""Measure Sum
Measures the sum of all values of an image
Args:
rep (OmeroFiRepresentationFragmentle): The image
key (str, optional): The key to use for the metric. Defaults to "max".
Returns:
Representation: The Back
"""
return create_metric(
key=key, value=float(rep.data.sum().compute()), representation=rep
)
@register(collections=["quantitative"])
def measure_fraction(
rep: RepresentationFragment,
key: str = "Fraction",
value: float = 1,
) -> MetricFragment:
"""Measure Fraction
Measures the appearance of this value in the image (0-1)
Args:
rep (OmeroFiRepresentationFragmentle): The image
key (str, optional): The key to use for the metric. Defaults to "max".
Returns:
Representation: The Back
"""
x = rep.data == value
sum = x.sum().compute()
all_values = reduce(lambda x, t: x * t, rep.data.shape, 1)
return create_metric(key=key, value=float(sum / all_values), representation=rep)
@register(collections=["quantitative"])
def measure_basics(
rep: RepresentationFragment,
) -> List[MetricFragment]:
"""Measure Basic Metrics
Measures basic meffffftrics of an image like max, mifffffn, mean
Args:
rep (OmeroFiRepresentationFragmentle): The image
Returns:
Representation: The Back
"""
x = rep.data.compute()
return [
create_metric(key="maximum", value=float(x.max()), representation=rep),
create_metric(key="mean", value=float(x.mean()), representation=rep),
create_metric(key="min", value=float(x.min()), representation=rep),
]
@register(collections=["conversion"])
def t_to_frame(
rep: RepresentationFragment,
interval: int = 1,
key: str = "frame",
) -> ROIFragment:
"""T to Frame
Converts a time series to a single frame
Args:
rep (RepresentationFragment): The Representation
frame (int): The frame to select
Returns:
RepresentationFragment: The new Representation
"""
assert "t" in rep.data.dims, "Cannot convert non time series to frame"
for i in range(rep.data.sizes["t"]):
if i % interval == 0:
yield create_roi(
representation=rep,
label=f"{key} {i}",
type=RoiTypeInput.FRAME,
tags=[f"t{i}", "frame"],
vectors=[InputVector(t=i), InputVector(t=i + interval)],
)
@register(collections=["conversion"])
def z_to_slice(
rep: RepresentationFragment,
interval: int = 1,
key: str = "Slice",
) -> ROIFragment:
"""Z to Slice
Creates a slice roi for each z slice
Args:
rep (RepresentationFragment): The Representation
frame (int): The frame to select
Returns:
RepresentationFragment: The new Representation
"""
assert "z" in rep.data.dims, "Cannot convert non time series to frame"
for i in range(rep.data.sizes["z"]):
if i % interval == 0:
yield create_roi(
representation=rep,
label=f"{key} {i}",
type=RoiTypeInput.SLICE,
tags=[f"z{i}", "frame"],
vectors=[InputVector(z=i), InputVector(z=i + interval)],
)
def cropND(img, bounding):
start = tuple(map(lambda a, da: a // 2 - da // 2, img.shape, bounding))
end = tuple(map(operator.add, start, bounding))
slices = tuple(map(slice, start, end))
return img[slices]
@register(collections=["conversion", "cropping"])
def crop_image(
roi: ROIFragment, rep: Optional[RepresentationFragment]
) -> RepresentationFragment:
"""Crop Image
Crops an Image based on a ROI
Args:
roi (ROIFragment): The Omero File
rep (Optional[RepresentationFragment], optional): The Representation to be cropped. Defaults to the one of the ROI.
Returns:
Representation: The Back
"""
if rep is None:
rep = get_representation(roi.representation.id)
array = rep.data
if roi.type == ROIType.RECTANGLE:
x_start = roi.vectors[0].x
y_start = roi.vectors[0].y
x_end = roi.vectors[0].x
y_end = roi.vectors[0].y
for vector in roi.vectors:
if vector.x < x_start:
x_start = vector.x
if vector.x > x_end:
x_end = vector.x
if vector.y < y_start:
y_start = vector.y
if vector.y > y_end:
y_end = vector.y
roi.vectors[0]
array = array.sel(
x=slice(math.floor(x_start), math.floor(x_end)),
y=slice(math.floor(y_start), math.floor(y_end)),
)
return from_xarray(
array,
name="Cropped " + rep.name,
tags=["cropped"],
origins=[rep],
roi_origins=[roi],
)
if roi.type == ROIType.FRAME:
array = array.sel(
t=slice(math.floor(roi.vectors[0].t), math.floor(roi.vectors[1].t))
)
return from_xarray(
array,
name="Cropped " + rep.name,
tags=["cropped"],
origins=[rep],
roi_origins=[roi],
)
if roi.type == ROIType.SLICE:
array = array.sel(
z=slice(math.floor(roi.vectors[0].z), math.floor(roi.vectors[1].z))
)
return from_xarray(
array,
name="Cropped " + rep.name,
tags=["cropped"],
origins=[rep],
roi_origins=[roi],
)
raise Exception(f"Roi Type {roi.type} not supported")
class DownScaleMethod(Enum):
MEAN = "mean"
MAX = "max"
MIN = "min"
MEDIAN = "median"
@register(collections=["processing", "scaling"])
def downscale_image(
rep: RepresentationFragment,
factor: int = 2,
depth=0,
method: DownScaleMethod = DownScaleMethod.MEAN,
) -> RepresentationFragment:
"""Downscale
Scales down the Representatoi by the factor of the provided
Args:
rep (RepresentationFragment): The Image where we should count cells
Returns:
RepresentationFragment: The Downscaled image
"""
s = tuple([1 if c == 1 else factor for c in rep.data.squeeze().shape])
newrep = multiscale(rep.data.squeeze(), windowed_mean, s)
return from_xarray(
newrep[1],
name=f"Downscaled {rep.name} by {factor}",
tags=[f"scale-{factor}"],
variety=RepresentationVariety.VOXEL,
origins=[rep],
)
@register(collections=["processing", "scaling"])
def rescale(
rep: RepresentationFragment,
factor_x: float = 2.0,
factor_y: float = 2.0,
factor_z: float = 2.0,
factor_t: float = 1.0,
factor_c: float = 1.0,
anti_alias: bool = True,
method: DownScaleMethod = DownScaleMethod.MEAN,
) -> RepresentationFragment:
"""Rescale
Rescale the dimensions by the factors provided
Args:
rep (RepresentationFragment): The Image we should rescale
Returns:
RepresentationFragment: The Rescaled image
"""
scale_map = {
"x": factor_x,
"y": factor_y,
"z": factor_z,
"t": factor_t,
"c": factor_c,
}
squeezed_data = rep.data.squeeze()
dims = squeezed_data.dims
s = tuple([scale_map[d] for d in dims])
newrep = transform.rescale(squeezed_data.data, s, anti_aliasing=anti_alias)
return from_xarray(
xr.DataArray(newrep, dims=dims),
name=f"Rescaled {rep.name}",
tags=[f"scale-{key}-{factor}" for key, factor in scale_map.items()],
variety=RepresentationVariety.VOXEL,
origins=[rep],
)
@register(collections=["processing", "scaling"])
def resize(
rep: RepresentationFragment,
dim_x: Optional[int],
dim_y: Optional[int],
dim_z: Optional[int],
dim_t: Optional[int],
dim_c: Optional[int],
anti_alias: bool = True,
) -> RepresentationFragment:
"""Resize
Resize the image to the dimensions provided
Args:
rep (RepresentationFragment): The Image we should resized
Returns:
RepresentationFragment: The resized image
"""
scale_map = {
"x": dim_x or rep.data.sizes["x"],
"y": dim_y or rep.data.sizes["y"],
"z": dim_z or rep.data.sizes["z"],
"t": dim_t or rep.data.sizes["t"],
"c": dim_c or rep.data.sizes["c"],
}
squeezed_data = rep.data.squeeze()
dims = squeezed_data.dims
s = tuple([scale_map[d] for d in dims])
newrep = transform.resize(
squeezed_data.data, s, anti_aliasing=anti_alias, preserve_range=True
)
newrep = skimage.util.img_as_uint(newrep)
return from_xarray(
xr.DataArray(newrep, dims=dims),
name=f"Resized {rep.name}",
tags=[f"resize-{key}-{factor}" for key, factor in scale_map.items()],
variety=RepresentationVariety.VOXEL,
origins=[rep],
)
class CropMethod(Enum):
CENTER = "mean"
TOP_LEFT = "top-left"
BOTTOM_RIGHT = "bottom-right"
class ExpandMethod(Enum):
PAD_ZEROS = "zeros"
@register(
groups={
"ensure_dim_x": ["advanced"],
"ensure_dim_y": ["advanced"],
"ensure_dim_z": ["advanced"],
"crop_method": ["advanced"],
"pad_method": ["advanced"],
"anti_alias": ["advanced"],
},
port_groups=[group(key="advanced", hidden=True)],
collections=["processing", "scaling"],
)
def resize_to_physical(
rep: RepresentationFragment,
rescale_x: Optional[float],
rescale_y: Optional[float],
rescale_z: Optional[float],
ensure_dim_x: Optional[int],
ensure_dim_y: Optional[int],
ensure_dim_z: Optional[int],
crop_method: CropMethod = CropMethod.CENTER,
pad_method: ExpandMethod = ExpandMethod.PAD_ZEROS,
anti_alias: bool = True,
) -> RepresentationFragment:
"""Resize to Physical
Resize the image to match the physical size of the dimensions,
if the physical size is not provided, it will be assumed to be 1.
Additional dimensions will be cropped or padded according to the
crop_method and pad_method if the ensure_dim is provided
Args:
rep (RepresentationFragment): The Image we should resized
rescale_x (Optional[float]): The physical size of the x dimension
rescale_y (Optional[float]): The physical size of the y dimension
rescale_z (Optional[float]): The physical size of the z dimension
ensure_dim_x (Optional[int]): The size of the x dimension
ensure_dim_y (Optional[int]): The size of the y dimension
ensure_dim_z (Optional[int]): The size of the z dimension
crop_method (CropMethod, optional): The method to crop the image. Defaults to crop center.
pad_method (ExpandMethod, optional): The method to pad the image. Defaults to expand with zeros.
Returns:
RepresentationFragment: The resized image
"""
if not rep.omero or not rep.omero.physical_size:
raise ValueError("Input Image has no physical size provided")
originial_scale = rep.omero.physical_size
scale_map = {
"x": rescale_x / rep.omero.physical_size.x if rescale_x else 1,
"y": rescale_y / rep.omero.physical_size.y if rescale_y else 1,
"z": rescale_z / rep.omero.physical_size.z if rescale_z else 1,
"t": 1,
"c": 1,
}
squeezed_data = rep.data.squeeze()
dims = squeezed_data.dims
s = tuple([scale_map[d] for d in dims])
if not all([d == 1 for d in s]):
newrep = transform.rescale(
squeezed_data.data.compute(), s, anti_aliasing=anti_alias, preserve_range=True
)
else:
newrep = squeezed_data.data.compute()
new_array = xr.DataArray(newrep, dims=dims)
if ensure_dim_x or ensure_dim_y or ensure_dim_z:
print(newrep.shape)
size_map = {
"x": ensure_dim_x or newrep.shape[2],
"y": ensure_dim_y or newrep.shape[1],
"z": ensure_dim_z or newrep.shape[0],
"t": rep.data.sizes["t"],
"c": rep.data.sizes["c"],
}
s = tuple([size_map[d] for d in dims])
new_array = cropND(
new_array,
s,
)
return from_xarray(
new_array,
name=f"Resized {rep.name}",
tags=[f"resize-{key}-{factor}" for key, factor in scale_map.items()],
variety=RepresentationVariety.VOXEL,
omero=OmeroRepresentationInput(
physicalSize=PhysicalSizeInput(
x=rescale_x if rescale_x else originial_scale.x,
y=rescale_y if rescale_y else originial_scale.y,
z=rescale_z if rescale_z else originial_scale.z,
),
),
origins=[rep],
)
class ThresholdMethod(Enum):
MEAN = "mean"
MAX = "max"
MIN = "min"
@register(collections=["processing", "thresholding"])
def threshold_image(
rep: RepresentationFragment,
threshold: float = 0.5,
method: ThresholdMethod = ThresholdMethod.MEAN,
) -> RepresentationFragment:
"""Binarize
Binarizes the image based on a threshold
Args:
rep (RepresentationFragment): The Image where we should count cells
Returns:
RepresentationFragment: The Downscaled image
"""
print(method)
if method == ThresholdMethod.MEAN.value:
m = rep.data.mean()
if method == ThresholdMethod.MAX.value:
m = rep.data.max()
if method == ThresholdMethod.MIN.value:
m = rep.data.min()
newrep = rep.data > threshold * m
return from_xarray(
newrep,
name=f"Thresholded {rep.name} by {threshold} through {method}",
tags=[f"thresholded-{threshold}", f"{method}-binarized"],
variety=RepresentationVariety.VOXEL,
origins=[rep],
)
@register(collections=["processing", "projection"])
def maximum_intensity_projection(
rep: RepresentationFragment,
) -> RepresentationFragment:
"""Maximum Intensity Projection
Projects the image onto the maximum intensity along the z axis
Args:
rep (RepresentationFragment): The Image where we should count cells
Returns:
RepresentationFragment: The Downscaled image
"""
m = rep.data.max(dim="z").compute()
print("Maximum?")
print(m.max())
print(m.min())
return from_xarray(
m,
name=f"Maximum Intensity Projection of {rep.name}",
tags=["maximum-intensity-projection"],
variety=RepresentationVariety.VOXEL,
origins=[rep],
)
class CV2NormTypes(Enum):
NORM_INF = cv2.NORM_INF
NORM_L1 = cv2.NORM_L1
NORM_L2 = cv2.NORM_L2
NORM_MINMAX = cv2.NORM_MINMAX
NORM_RELATIVE = cv2.NORM_RELATIVE
NORM_TYPE_MASK = cv2.NORM_TYPE_MASK
@register(collections=["processing", "thresholding", "adaptive"])
def adaptive_threshold_image(
rep: RepresentationFragment,
normtype: CV2NormTypes = CV2NormTypes.NORM_MINMAX,
) -> RepresentationFragment:
"""Adaptive Binarize
Binarizes the image based on a threshold
Args:
rep (RepresentationFragment): The Image where we should count cells
Returns:
RepresentationFragment: The Downscaled image
"""
x = rep.data.compute()
thresholded = xr.DataArray(np.zeros_like(x), dims=x.dims, coords=x.coords)
for c in range(x.sizes["c"]):
for z in range(x.sizes["z"]):
for t in range(x.sizes["t"]):
img = x.sel(c=c, z=z, t=t)
normed = cv2.normalize(img.data, None, 0, 255, normtype, cv2.CV_8U)
thresholded[c, t, z, :, :] = cv2.adaptiveThreshold(
normed,
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
11,
2,
)
return from_xarray(
thresholded,
name=f"Adaptive Thresholded {rep.name}",
tags=["adaptive-thresholded"],
variety=RepresentationVariety.VOXEL,
origins=[rep],
)
class CV2NormTypes(Enum):
NORM_INF = cv2.NORM_INF
NORM_L1 = cv2.NORM_L1
NORM_L2 = cv2.NORM_L2
NORM_MINMAX = cv2.NORM_MINMAX
NORM_RELATIVE = cv2.NORM_RELATIVE
NORM_TYPE_MASK = cv2.NORM_TYPE_MASK
@register(collections=["processing", "thresholding", "adaptive"])
def otsu_thresholding(
rep: RepresentationFragment,
gaussian_blur: bool = False,
) -> RepresentationFragment:
"""Otsu Thresholding
Binarizes the image based on a threshold, using Otsu's method
with option to guassian blur the image before, images are normalized
for each x,y slice before thresholding.
Args:
rep (RepresentationFragment): The Image to be thresholded
gaussian_blur (bool): Whether to apply a gaussian blur before thresholding (kernel_size=5)
Returns:
RepresentationFragment: The thresholded image
"""
x = rep.data.compute()
thresholded = xr.DataArray(np.zeros_like(x, dtype=np.uint8), dims=x.dims, coords=x.coords)
print("Hallo")
print(x.min())
print(x.max())
for c in range(x.sizes["c"]):
for z in range(x.sizes["z"]):
for t in range(x.sizes["t"]):
img = x.sel(c=c, z=z, t=t).data
# Find min and max values
min_val = np.min(img)
max_val = np.max(img)
# Apply min-max normalization
normalized_arr = ((img - min_val) / (max_val - min_val) * 255).astype(np.uint8)
if gaussian_blur:
normalized_arr = cv2.GaussianBlur(img, (5, 5), 0)
print(img)
threshold, image = cv2.threshold(
normalized_arr,
0,
255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU,
)
print(image, threshold)
print(image.dtype)
thresholded[c, t, z, :, :] = image
print(thresholded.dtype)
return from_xarray(
thresholded,
name=f"Otsu Thresholded {rep.name}",
tags=["otsu-thresholded"],
variety=RepresentationVariety.MASK,
origins=[rep],
)
@register(collections=["conversion"])
def roi_to_position(
roi: ROIFragment,
) -> PositionFragment:
"""Roi to Position
Transforms a ROI into a Position on the governing stage
Args:
rep (RepresentationFragment): The Image where we should count cells
Returns:
RepresentationFragment: The Downscaled image
"""
smart_image = get_representation(roi.representation)
while smart_image.omero is None or smart_image.omero.positions is None:
smart_image = get_representation(smart_image.origins[0])
assert (
smart_image.shape == roi.representation.shape
), "Could not find a matching position is not in the same space as the original (probably through a downsampling, or cropping)"
omero = smart_image.omero
affine_transformation = omero.affine_transformation
shape = smart_image.shape
position = smart_image.omero.positions[0]
# calculate offset between center of roi and center of image
print(position)
print(roi.get_vector_data(dims="ctzyx"))
center = roi.center_as_array()
print(center)
image_center = np.array(shape) / 2
print(image_center[2:])
print(center[2:])
offsetz, offsety, offsetx = image_center[2:]
z, y, x = center[2:]
x_from_center = x - offsetx
y_from_center = y - offsety
z_from_center = z - offsetz
# TODO: check if this is correct and extend to 3d
vec_center = np.array([x_from_center, y_from_center, z_from_center])
vec = np.matmul(np.array(affine_transformation).reshape((3, 3)), vec_center)
new_pos_x, new_pos_y, new_pos_z = (
np.array([position.x, position.y, position.z]) + vec
)
print(vec)
print("Affine", affine_transformation)
return create_position(
stage=position.stage,
name=f"Position of {roi.label or 'Unknown ROI'}",
x=new_pos_x,
y=new_pos_y,
z=new_pos_z,
roi_origins=[roi],
)
@register(collections=["conversion"])
def roi_to_physical_dimensions(
roi: ROIFragment,
) -> Tuple[float, float]:
"""Rectangular Roi to Dimensions
Measures the size of a Rectangular Roi in microns
(only works for Rectangular ROIS)
Parameters
----------
roi : ROIFragment
The roi to measure
Returns
-------
height: float
The height of the ROI in microns
width: float
The width of the ROI in microns
"""
assert roi.type == ROIType.RECTANGLE, "Only works for rectangular ROIs"
smart_image = get_representation(roi.representation)
while smart_image.omero is None or smart_image.omero.physical_size is None:
smart_image = get_representation(smart_image.origins[0])
assert (
smart_image.shape == roi.representation.shape
), "Could not find a matching position is not in the same space as the original (probably through a downsampling, or cropping)"
physical_size = smart_image.omero.physical_size
# Convert to a numpy array for easier manipulation
points = roi.get_vector_data(dims="yx")
# Find the minimum and maximum x and y coordinates
min_y, min_x = np.min(points, axis=0)
max_y, max_x = np.max(points, axis=0)
# Calculate the width and height
width = max_x - min_x
height = max_y - min_y
return width * physical_size.x, height * physical_size.y
@register(collections=["conversion"])
def rois_to_positions(
roi: List[ROIFragment],
) -> List[PositionFragment]:
"""Rois to Positions