-
Notifications
You must be signed in to change notification settings - Fork 0
/
inspection_utils.py
3339 lines (2647 loc) · 112 KB
/
inspection_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import concurrent
from concurrent.futures import ProcessPoolExecutor
from collections import defaultdict, OrderedDict
from zipfile import BadZipFile
import cv2
import csv
import glob
import json
import logging
import os
import shutil
from math import sqrt
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from mpl_toolkits.axes_grid1 import make_axes_locatable
from multiprocessing import Pool
from numcodecs import Blosc
import numpy as np
from numpy import ndarray
import platform
from pathlib import Path
import re
from numpy._typing import ArrayLike
from ruyaml import YAML
import skimage
from scipy import ndimage
from scipy.ndimage import convolve
from scipy.interpolate import CloughTocher2DInterpolator
from skimage.color import rgb2gray
from skimage.metrics import structural_similarity as ssim
from PIL import Image
import subprocess
from tqdm import tqdm
from typing import Tuple, List, Set, Union, Optional, Dict, Iterable, Any, Sequence
import yaml
from ome_zarr.io import parse_url
from ome_zarr.scale import Scaler
from ome_zarr.writer import write_image
import zarr
import pyramid_levels
Num = Union[int, float]
TileXY = tuple[int, int]
Vector = Union[tuple[int, int], tuple[int, int, int]] # [z]yx order
UniPath = Union[str, Path]
TileCoord = Union[Tuple[int, int, int, int], Tuple[int, int]] # (c, z, y, x)
GridXY = Tuple[Any, Any, Any]
MaskMap = Dict[TileXY, Optional[np.ndarray]]
# # # Set up logging
# logging.basicConfig(level=logging.DEBUG)
# logging.basicConfig(level=logging.INFO)
#logging.basicConfig(level=logging.WARNING)
def fix_zarr(path_orig: str, path_new: str):
zarr_volume = zarr.open(path_orig, mode='r')
img_data = zarr_volume['0']
if img_data.ndim == 2:
logging.info(f'{Path(path_orig).name} already fixed. Moving to destination folder.')
shutil.move(path_orig, path_new)
return
sec_name = str(Path(path_new).name)
sec_dir = str(Path(path_new).parent)
logging.info(f'Storing section {sec_name}')
store_section_zarr(img_data[0, ...], sec_name, Path(sec_dir))
return
def store_section_zarr(
img_data: np.ndarray,
section_name: str,
out_dir: UniPath
) -> None:
zarr_path = str(Path(out_dir) / section_name)
store = parse_url(zarr_path, mode="w").store
write_image(
image=img_data,
group=zarr.group(store=store),
scaler=Scaler(max_layer=0),
axes="yx",
storage_options=dict(
chunks=(2744, 2744),
compressor=Blosc(
cname="zstd",
clevel=3,
shuffle=Blosc.SHUFFLE,
),
overwrite=True,
write_empty_chunks=False,
),
)
return
def create_zarr(
output_dir: str,
volume_name: str,
yx_size: tuple[int, int],
) -> str:
target_dir = Path(output_dir) / volume_name
store = parse_url(str(target_dir), mode="w").store
zarr_root = zarr.group(store=store)
chunks = (1, 2744, 2744)
write_image(
image=np.zeros(
(1, yx_size[0], yx_size[1]),
dtype=np.uint8,
),
group=zarr_root,
axes="zyx",
scaler=Scaler(max_layer=0),
storage_options=dict(
chunks=chunks,
compressor=Blosc(cname="zstd", clevel=3, shuffle=Blosc.SHUFFLE),
overwrite=True,
write_empty_chunks=True,
),
)
return str(target_dir)
def scan_dirs(dir_path) -> List[Path]:
p = Path(dir_path)
if not p.is_dir():
print(f"{dir_path} is not a valid directory.")
return []
# List only top-level directories
dirs = [Path(d) for d in p.glob('*') if d.is_dir()]
return dirs
def find_files_with_substring(dir_path, substring):
p = Path(dir_path)
if not p.is_dir():
print(f"{dir_path} is not a valid directory.")
return []
matching_files = [str(file) for file in p.rglob('*') if file.is_file() and substring in file.name]
return matching_files
def create_multiscale(zarr_path: Union[str, Path], max_layer=5, num_processes=42) -> None:
zarr_path = cross_platform_path(str(zarr_path))
if not Path(zarr_path).exists():
logging.warning(f'Creating multiscale .zarr failed (zarr path does not exist).')
return
logging.info(f'Creating multiscale volume: {zarr_path}')
pyramid_levels.main(zarr_path=zarr_path, max_layer=max_layer, num_processes=num_processes)
return
def create_section_yaml_file(file_path,
section_num,
tile_grid_num,
grid_shape,
acquisition,
thickness,
tile_height,
tile_width,
tile_overlap,
tiles):
data = {
'section_num': section_num,
'tile_grid_num': tile_grid_num,
'grid_shape': grid_shape,
'acquisition': acquisition,
'thickness': thickness,
'tile_height': tile_height,
'tile_width': tile_width,
'tile_overlap': tile_overlap,
'tiles': tiles
}
with open(file_path, 'w') as file:
yaml.dump(data, file, default_flow_style=False, sort_keys=False)
logging.info(f"YAML file created at {file_path}")
return
def norm_img(data) -> np.ndarray:
logging.debug(f'norm_img shape:{data.shape}')
norm_gray = (data - np.min(data)) / (np.max(data) - np.min(data))
return (norm_gray * 255).astype(np.uint8)
# def plot_images_with_overlay(image1, image2, alpha=0.5):
# fig, ax = plt.subplots(figsize=(10, 5))
#
# # Plot the first image
# ax.imshow(image1, cmap='gray')
#
# # Plot the second image with transparency
# ax.imshow(image2, cmap='jet', alpha=alpha)
#
# # Set axis labels
# ax.set_xlabel('X')
# ax.set_ylabel('Y')
#
# # Show the plot
# plt.show()
# return
def build_tiles_coords(tile_id_map: np.ndarray) -> Optional[Tuple[TileXY]]:
"""Builds tile coordinates map from the given tile ID map.
Args:
tile_id_map (np.ndarray): The tile ID map.
Returns:
Optional[Tuple[TileXY]]: A tuple of tile coordinates (x, y).
"""
if not isinstance(tile_id_map, np.ndarray):
logging.error('Build tile coords failed: wrong input data.')
return None
tc = []
y, x = tile_id_map.shape
for i in range(y):
for j in range(x):
if int(tile_id_map[i, j]) != -1:
tc.append((j, i))
return tuple(tc)
def crop_bbox(img: np.ndarray,
pad: Optional[int] = 700,
offset: Optional[Vector] = None
) -> np.ndarray:
"""
Crop the bounding box around the non-zero elements in the image.
Args:
img (np.ndarray): Input image as a NumPy array.
pad:
offset:
Returns:
np.ndarray: Cropped image with the maximum extent of black canvas removed.
"""
is_vert = True if img.shape[0] < img.shape[1] else False
axis = 1 if is_vert else 0
if is_vert:
left = pad + offset[1 - axis]
right = left + img.shape[axis]
top = 0
bottom = 0
else:
left = 0
right = 0
top = pad + offset[1 - axis]
bottom = top + img.shape[axis]
# Crop the image
print(f'cropping params: {top, bottom, left, right}')
cropped_img = img[top:bottom, left:right]
print(f'orig shape: {img.shape}')
print(f'new shape: {cropped_img.shape}')
return cropped_img
def crop_nan(img: np.ndarray[float]) -> np.ndarray:
"""Remove all columns in the input image that contain nan values"""
nans = np.argwhere(np.isnan(img))
nan_col_indices = set(nans[:, 1])
mask = np.ones(img.shape[1], dtype=bool)
mask[list(nan_col_indices)] = False
# Crop out columns based on the mask
cropped_arr = img[:, mask]
return cropped_arr
def fill_holes(mask):
num_mask = np.asarray(mask, dtype=int)
filled_num_mask = ndimage.binary_fill_holes(num_mask)
filled_mask = filled_num_mask.astype(bool)
return filled_mask
def get_smearing_mask(
img: np.ndarray,
mask_top_edge: int = 0,
path_plot: Optional[str] = None,
plot=False
) -> Optional[np.ndarray]:
"""Commutes mask of a distortion appearing at the top of the EM-images.
Estimate the presence and extent of a smearing distortion at the top of the
input image and return it as a boolean mask.
Args:
img: input image for detection of distortion at its top border
mask_top_edge: number of lines at the top of the image to be masked entirely
path_plot: filepath where to save the mask image (if plot=True)
plot: switch to execute creation of various mask graphs
Returns:
Mask of smearing distortion with the shape same as the input image
"""
det_args = dict(
img=img,
segment_width=1000,
sigma=1.5,
dx=50,
dy=4
)
# Run smearing detection
smr_map = detect_smearing2d(**det_args)
smr_map_interp = interpolate_nan_2d(smr_map)
smr_map_interp = gaussian(smr_map_interp, sigma=2)
mask = create_mask(smr_map_interp, threshold=0.1)
clean_args = dict(
mask=mask,
min_size=800,
portion=1.0,
max_vert_extent=150,
top=mask_top_edge
)
def clean_mask(mask, top, min_size, portion, max_vert_extent):
# Mask entire top lines
if top > 0:
mask[:top] = True
# Mask top right border # TODO investigate if needed
mask[:, -1] = True
# Fill binary holes
mask = fill_holes(mask)
# Unmask all lines below line nr. 'max_vert_extent'
if 0 < max_vert_extent < mask.shape[0]:
mask[max_vert_extent:] = False
# Mask small masking irregularities
if portion > 0:
mask = flood_smearing(mask, portion)
# Remove True islands with small area
if min_size > 0:
mask = remove_isolated(mask, min_size)
return mask
mask_final2 = clean_mask(**clean_args)
# mask_filled = fill_holes(mask)
# # mask_flooded = flood_pixels(mask_filled, ratio=0.4)
# # mask_flood = flood_smearing(mask_flooded, portion=1.0)
# mask_flood = flood_smearing(mask_filled, portion=1.0)
# # mask_flood2 = flood_smearing(mask_flood, portion=.5)
# # mask_final = fill_holes(mask_flood2)
# mask_final = fill_holes(mask_flood)
# mask_final2 = remove_isolated(mask_final, min_size=800)
# if plot:
# to_plot = [smr_map, smr_map_interp, mask_flood,
# mask_flood, mask_final, mask_final2
# ]
# plot_smearing(plots=to_plot, path_plot=path_plot)
return mask_final2
def crop_ov(ov_img: np.ndarray, pad: int, offset: Vector,
is_vert: bool, tile_shape: Tuple[int, int]) -> np.ndarray:
# plt.imshow(ov_img, cmap='gray')
# plt.show()
dy, dx = 100, 100 # Half-widths of seam region
axis = 1 if is_vert else 0
h, w = np.shape(ov_img)
h_mid, w_mid = int(h / 2), int(w / 2)
c0 = int(pad / 2) + offset[1 - axis]
if is_vert:
left = max(int(pad / 2), c0)
right = min(int(pad / 2), c0) + tile_shape[axis]
top = h_mid - dy
bottom = h_mid + dy
else:
left = w_mid - dx
right = w_mid + dx
top = max(int(pad / 2), c0)
bottom = min(int(pad / 2), c0) + tile_shape[axis]
cropped_ov = ov_img[top:bottom, left:right]
# plt.imshow(ov_img, cmap='gray')
# plt.show()
# plt.imshow(cropped_ov, cmap='gray')
# plt.show()
return cropped_ov
def detect_bad_seam(
ov_img: np.ndarray,
is_vert: bool,
stride: int = 1,
plot: bool = False,
path_plot: Optional[str] = None,
show_plot: bool = False
) -> Optional[float]:
# Rotate overlap plot
if not is_vert:
ov_img = np.rot90(ov_img, k=1)
# Remove all columns in the image that contain nan values
ov_crop = crop_nan(ov_img)
# Apply one-directional Gaussian blurring
sigma = 2
ov_crop = ndimage.gaussian_filter(ov_crop, sigma=(0, sigma))
y, x = ov_crop.shape
if y < stride:
logging.warning(f'Cropped area is too small in (y) {ov_crop.shape} \
to be used with specified stride.')
return
if x < stride:
logging.warning(f'Cropped area is too small in (x) {ov_crop.shape} \
to be used with specified stride.')
return
# Find discontinuity using SSIM
peak_to_ssim = bad_seam_ssim(ov_crop, plot, path_plot, show_plot)
return peak_to_ssim
def bad_seam_ssim(
img: np.ndarray,
plot: bool = False,
path_plot: Optional[str] = None,
show_plot: bool = False
) -> float:
def moving_average(a, n=3):
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def pk_detect(a, n=7):
pk_arr = []
for i in range(len(a) - n):
pk_arr.append(np.max(a[i:i + n]) + abs(np.min(a[i:i + n])))
return np.array(pk_arr)
# Change to 8-bit depth
def norm_img(data) -> np.ndarray:
norm_gray = (data - np.min(data)) / (np.max(data) - np.min(data))
return (norm_gray * 255).astype(np.uint8)
res = []
dy = 10 # Width of an image stripe to be used for SSIM
line_range = np.arange(img.shape[0] - 1 - dy, step=dy // 2)
for i in line_range:
a = img[i: i + dy]
b = img[i + 1: i + dy + 1]
a, b = [skimage.filters.gaussian(i_img, sigma=1.5) for i_img in (a, b)]
a = norm_img(a)
b = norm_img(b)
res.append(ssim(a, b, win_size=5, full=False))
ssim_vals = np.array(res)
min_peak = np.min(ssim_vals)
min_pk_vs_mean = 1/(min_peak / np.mean(ssim_vals))
# diff_res = ssim_vals[1:] - ssim_vals[:-1]
# diff_res = moving_average(np.array(diff_res))
#
# pk_spectrum = pk_detect(diff_res, n=2)
# # plt.plot(pk_spectrum, 'o-')
# # # plt.plot(diff_res, 'o-')
# # plt.show()
# # return
#
# diff_res = pk_spectrum
# diff_mean, diff_std = np.mean(diff_res), np.std(diff_res)
# max_peak = np.max(diff_res)
#
# pk_vs_mean: float = max_peak / diff_mean
# pk_vs_std: float = max_peak / diff_std
#
# # mean = np.mean(ssim_vals)
# # std_dev = np.std(ssim_vals)
# #
# # # Calculate upper and lower bounds
# # upper_bound = mean + 2 * std_dev
# # lower_bound = mean - 2 * std_dev
# #
# # # Filter outliers
# # filtered_ssim_vals = ssim_vals[(ssim_vals >= lower_bound) & (ssim_vals <= upper_bound)]
# # mean = np.mean(filtered_ssim_vals)
# # std_dev = np.std(filtered_ssim_vals)
# # pk = min(ssim_vals)
# # print(pk)
# # print(mean, std_dev)
# # print((mean-pk)/std_dev)
# # pk_vs_mean = (mean-pk)/std_dev
#
# # plt.subplot(1, 2, 1)
# # plt.plot(res, line_range[::-1], 'o-')
# # plt.xlabel('Mean SSIM')
# # plt.ylabel('Line Index [pix]')
# #
# # plt.subplot(1, 2, 2)
# # _label = f'max pk vs. meanSSIM: {pk_vs_mean}, max pk vs. stddev: {pk_vs_std}'
# # plt.plot(diff_res, '-o', label=f'{_label}')
# # plt.axhline(diff_mean, color='red', linestyle='dashed', linewidth=2, label='Mean')
# #
# # # Plot one standard deviation band
# # plt.fill_between(range(len(diff_res)), diff_mean - diff_std, diff_mean + diff_std,
# # color='orange', alpha=0.3, label='1 Std Dev Band')
# #
# # # Plot two standard deviation band
# # plt.fill_between(range(len(diff_res)), diff_mean - 2 * diff_std, diff_mean + 2 * diff_std,
# # color='yellow', alpha=0.3, label='2 Std Dev Band')
# #
# # plt.xlabel('Mean SSIM (difference)')
# # plt.ylabel('Diff. SSIM value')
# # plt.legend()
# # plt.show()
#
# if plot:
# plt.figure(figsize=(12, 8), dpi=100)
# plt.subplot(311)
# plt.imshow(img, cmap='gray')
# plt.axis('off')
#
# plt.subplot(312)
# _label = f'inv. min pk vs. meanSSIM: {min_pk_vs_mean:.2f}'
# plt.plot(res, line_range[::-1], 'o-', label=_label)
# plt.xlabel('Mean SSIM')
# plt.ylabel('Line Index [pix]')
# plt.title('Mean SSIM')
# plt.legend()
# plt.grid(True)
#
# plt.subplot(313)
# _label = f'max pk vs. meanSSIM: {pk_vs_mean:.3f}, max pk vs. stddev: {pk_vs_std:.2f}'
# plt.plot(diff_res, '-o', color='orange', label=_label)
# plt.axhline(diff_mean, color='red', linestyle='dashed', linewidth=2, label='Mean')
# plt.fill_between(range(len(diff_res)), diff_mean - diff_std, diff_mean + diff_std,
# color='orange', alpha=0.3, label='1 Std Dev Band')
# plt.fill_between(range(len(diff_res)), diff_mean - 2 * diff_std, diff_mean + 2 * diff_std,
# color='yellow', alpha=0.3, label='2 Std Dev Band')
# plt.xlabel('Mean SSIM (difference)')
# plt.ylabel('Diff. SSIM value')
# plt.title('Difference SSIM')
# plt.grid(False)
# plt.legend()
# plt.tight_layout()
#
# if path_plot is not None:
# print(f'export path: {path_plot}')
# plt.savefig(path_plot)
#
# if show_plot:
# plt.show()
#
# plt.close()
return 1 / min_pk_vs_mean
def get_tid_idx(tile_id_map, tile_id) -> Optional[Tuple[int, int]]:
# Extract y, x coordinate of tile_id in tile_id_map
# logging.debug(tile_id_map)
if tile_id not in tile_id_map:
# logging.info(f'Tile_ID: {tile_id} not present in section!')
return None
if tile_id == -1:
logging.info(f'Tile_ID: {tile_id} has undefined mask!')
return None
coords = np.where(tile_id == tile_id_map)
y, x = int(coords[0][0]), int(coords[1][0])
return y, x
def plot_trace_from_backup(
path_cxyz: str,
path_id_maps: str,
path_plot: str,
tile_id: int,
sec_range: Tuple[Optional[int], Optional[int]],
show_plot: bool,
):
"""Plots traces from input cxyz tensor
Args:
path_cxyz: str - path to aggregated file containing all coarse offsets
path_id_map: str - path to aggregated file containing all tile_id_maps
path_plot: str - path here to store resulting graph
tile_id: int - ID of the tile trace to be plotted
sec_range: Optional[tuple(int, int)] - range of section numbers to be plotted
:return:
"""
def plot_traces(x_axis: np.ndarray, traces: np.ndarray, _path_plot: str,
_tile_id: int, _vert_nn_tile_id: Optional[int], _show_plot: bool) -> None:
"""Plots array of both coarse offset vectors' values """
fig, ax = plt.subplots(figsize=(15, 9))
labels = ('c0x', 'c0y', 'c1x', 'c1y')
for j in range(traces.shape[0]):
ax.plot(x_axis, traces[j, :], '-', label=f'{labels[j]}')
# Add labels, title, and legend
ax.set_xlabel('Section number')
ax.set_ylabel('Shift [pix]')
nn_tile_id = '' if _vert_nn_tile_id is None else f" ({str(_vert_nn_tile_id)})"
ax.set_title(f'Coarse Offsets for Tile ID {_tile_id} {nn_tile_id}')
ax.legend(loc='upper right')
ax.grid(True)
# Adjust x-axis and y-axis ticks density
ax.xaxis.set_major_locator(MaxNLocator(integer=True, nbins=30))
ax.yaxis.set_major_locator(MaxNLocator(integer=True, nbins=20))
plt.savefig(_path_plot)
if _show_plot:
plt.show()
plt.close(fig)
return
path_cxyz = Path(cross_platform_path(path_cxyz))
path_id_maps = Path(cross_platform_path(path_id_maps))
path_plot = cross_platform_path(path_plot)
if path_cxyz.exists() and path_id_maps.exists():
# Load coarse offsets
cxyz_obj = np.load(path_cxyz)
cxyz_keys = list(cxyz_obj.files)
sec_nums = set(map(int, cxyz_keys))
# Load tile_id_maps
tile_id_maps = np.load(path_id_maps)
tile_id_maps_keys = list(tile_id_maps.files)
sec_nums_id_maps = set(map(int, tile_id_maps_keys))
# Compatible section numbers
sec_nums = sec_nums.intersection(sec_nums_id_maps)
if len(sec_nums) == 0:
# Not possible to map tile_id_map files to the coarse offset files
print(f'Available offsets maps and tile_id_maps do not match.')
return
# Select range of sections to be processed
first, last = sec_range
if first is None:
first = min(sec_nums)
if last is None:
last = max(sec_nums)
if first > last:
logging.warning('Plot traces: wrong section range definition.')
return
sec_nums_plot = set(np.arange(first, last, step=1))
sec_nums_plot = sec_nums.intersection(sec_nums_plot)
logging.info(f'Trace plotting: {len(sec_nums_plot)} sections will be processed.')
if len(sec_nums_plot) > 1:
arr = np.full(shape=(4, last - first), fill_value=np.nan)
x_axis_sec_nums = np.arange(first, last)
vert_nn_tile_id = None
for i, num in enumerate(x_axis_sec_nums):
if num in sec_nums_plot:
tile_id_map = tile_id_maps[str(num)]
if vert_nn_tile_id is None:
vert_nn_tile_id = get_vert_tile_id(tile_id_map, tile_id)
coord = get_tid_idx(tile_id_map, tile_id)
if coord is not None:
y, x = coord
try:
shifts = cxyz_obj[str(num)][:, :, y, x]
arr[:, i] = shifts.flatten().transpose()
except IndexError as _:
logging.warning(f'Trace plotting: unable to determine shifts of s{num} t{tile_id}')
else:
continue
if not np.all(np.isnan(arr)):
plot_traces(x_axis_sec_nums, arr, path_plot, tile_id, vert_nn_tile_id, show_plot)
else:
print(f'Nothing to plot. Sections {first} : {last} not in available'
f'range: [{min(sec_nums)} : {max(sec_nums)}].')
return
else:
print(f'Input files are missing. Check path_cxyz: {path_cxyz}')
return
def plot_trace_eval_ov(
path_cxyz: str,
path_id_maps: str,
path_plot: str,
tile_id: int,
sec_range: Tuple[Optional[int], Optional[int]],
show_plot: bool,
):
"""Plots trace from input tensor
Args:
path_cxyz: str - path to aggregated file containing all coarse offsets
path_id_map: str - path to aggregated file containing all tile_id_maps
path_plot: str - path here to store resulting graph
tile_id: int - ID of the tile trace to be plotted
sec_range: Optional[tuple(int, int)] - range of section numbers to be plotted
:return:
"""
def plot_traces(x_axis: np.ndarray, traces: np.ndarray, _path_plot: str, _tile_id: int, _show_plot: bool) -> None:
# Plot four graphs of coarse offsets
fig, ax = plt.subplots(figsize=(15, 9))
labels = ('horizontal pairs', 'vertical pairs')
for j in range(len(labels)):
ax.plot(x_axis, traces[j, :], '-', label=f'{labels[j]}')
# Add labels, title, and legend
ax.set_xlabel('Section number')
ax.set_ylabel('Overlaps similarity (SSIM)')
ax.set_title(f'Similarity plots of tile-pair overlaps {_tile_id}')
ax.legend(loc='upper right')
# Set grid
ax.grid(True)
# Adjust x-axis ticks density
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
# Save the plot and show if needed
plt.savefig(_path_plot)
if _show_plot:
plt.show()
# Close the plot
plt.close()
return
print(f'path_cxyz: {path_cxyz}')
logging.warning(f'path_cxyz: {path_cxyz}')
path_cxyz = Path(cross_platform_path(path_cxyz))
path_id_maps = Path(cross_platform_path(path_id_maps))
path_plot = cross_platform_path(path_plot)
if not path_cxyz.exists() or not path_id_maps.exists:
print(f'Input files are missing. Check path_cxyz: {path_cxyz}')
else:
# Load coarse offsets
cxyz_obj = np.load(path_cxyz)
cxyz_keys = list(cxyz_obj.files)
sec_nums = set(map(int, cxyz_keys))
# Load tile_id_maps
tile_id_maps = np.load(path_id_maps)
tile_id_maps_keys = list(tile_id_maps.files)
sec_nums_id_maps = set(map(int, tile_id_maps_keys))
# Compatible section numbers
sec_nums = sec_nums.intersection(sec_nums_id_maps)
if len(sec_nums) == 0:
# Not possible to map tile_id_map files to the coarse offset files
print(f'Available offsets maps and tile_id_maps do not match.')
return
# Select range of sections to be processed
first, last = sec_range
if first is None:
first = min(sec_nums)
if last is None:
last = max(sec_nums)
if first > last:
print('Nothing to plot: wrong section range definition.')
return
sec_nums_plot = set(np.arange(first, last, step=1))
sec_nums_plot = sec_nums.intersection(sec_nums_plot)
logging.info(f'{len(sec_nums_plot)} sections will be processed.')
if len(sec_nums_plot) <= 1:
print(f'Nothing to plot. Sections {first} : {last} not in available'
f'range: [{min(sec_nums)} : {max(sec_nums)}].')
return
else:
arr = np.full(shape=(2, last - first), fill_value=np.nan)
x_axis_sec_nums = np.arange(first, last)
for i, num in enumerate(x_axis_sec_nums):
if num in sec_nums_plot:
tile_id_map = tile_id_maps[str(num)]
coord = get_tid_idx(tile_id_map, tile_id)
if coord is not None:
y, x = coord
shifts = cxyz_obj[str(num)][:, y, x]
arr[:, i] = shifts.flatten().transpose()
else:
continue
if not np.all(np.isnan(arr)):
plot_traces(x_axis_sec_nums, arr, path_plot, tile_id, show_plot)
return
def aggregate_tile_id_maps(
section_dirs: List[UniPath]
) -> Tuple[Dict[str, ndarray], List[str]]:
"""
Load tile_id_maps arrays from input folder and return them
as a dictionary with section numbers as keys
:param section_dirs:
:return: dictionary mapping tile_id array to section number
"""
maps: dict = {}
failed_paths = []
fn_map = 'tile_id_map.json'
for section_path in tqdm(section_dirs):
fp_map = Path(section_path) / fn_map
if not fp_map.exists():
logging.debug(f's{get_section_num(section_path)} tile_id_map.json file does not exist')
failed_paths.append(f's{get_section_num(section_path)}\n')
continue
key = str(get_section_num(section_path))
maps[key] = get_tile_id_map(fp_map)
return maps, failed_paths
def aggregate_coarse_offsets(
section_dirs: List[UniPath]
) -> Tuple[Dict[str, ndarray], List[str]]:
"""
Load coarse offset arrays from input folder and return them
as a dictionary with section numbers as keys
Coarse offsets can be read either from coarse.npz or from cx_cy.json file.
:param section_dirs:
:return:
"""
offsets: dict = {}
failed_paths = []
for section_path in tqdm(section_dirs):
cxy_path = None
cxy_names = ('cx_cy.json',)
for name in cxy_names:
path_to_check = Path(section_path) / name
if path_to_check.exists():
cxy_path = path_to_check
break
if cxy_path is None:
logging.debug(f's{get_section_num(section_path)} coarse-offsets file does not exist')
failed_paths.append(f's{get_section_num(section_path)}\n')
continue
_, cx, cy = read_coarse_mat(cxy_path)
key = str(get_section_num(section_path))
offsets[key] = np.array((cx, cy))
return offsets, failed_paths
def backup_tile_id_maps(dir_sections: UniPath, dir_out: Optional[UniPath]) -> None:
"""
Store all tile ID maps from sections inside the input folder into a .npz file.
:param dir_sections: Path to the parent directory containing section directories.
:param dir_out: Optional. Path to the output directory. If not provided, the result
is stored in the input directory.
:return: None
"""
dir_sections = Path(dir_sections)
all_sections = filter_and_sort_sections(str(dir_sections))
# Collect all tile ID maps
tile_id_maps, missing_files = aggregate_tile_id_maps(all_sections)
logging.debug(f'len missing files {len(missing_files)}')
for p in missing_files:
logging.debug(p)
fp_out = (dir_out or dir_sections) / "all_tile_id_maps.npz"
np.savez(fp_out, **tile_id_maps)
logging.info(f'Tile ID maps saved to: {fp_out}')
fp_out2 = fp_out.with_name("all_missing_tile_id_maps.txt")
with open(fp_out2, "w") as f:
f.writelines("\n".join(missing_files))
logging.info(f'Missing tile ID maps saved to: {fp_out2}')
return
def apply_clahe(image, clip_limit=2., grid_size=(8, 8)):
clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=grid_size)
return clahe.apply(image)
def backup_coarse_offsets(dir_sections: UniPath, dir_out: Optional[UniPath]) -> None:
"""
Store all coarse offset arrays from section inside input folder into a .npz file.
:param dir_sections: Path to the parent directory containing section directories.
:param dir_out: Optional. Path to the output directory. If not provided, the result
is stored in the input directory
:return: None
"""
dir_sections = Path(dir_sections)
all_sections = filter_and_sort_sections(str(dir_sections))
# Collect all offsets
offsets, missing_files = aggregate_coarse_offsets(all_sections)
logging.debug(f'len missing files {len(missing_files)}')
for p in missing_files:
logging.debug(p)
fp_out = (dir_out or dir_sections) / "all_offsets.npz"
np.savez(fp_out, **offsets)
logging.info(f'Coarse offsets saved to: {fp_out}')
fp_out2 = fp_out.with_name("all_offsets_missing_files.txt")
with open(fp_out2, "w") as f:
f.writelines("\n".join(missing_files))
logging.info(f'Missing offsets saved to: {fp_out2}')
return
def copy_stats_yaml(src_folder, dest_folder):
# Iterate over folders in the source directory
for folder_name in tqdm(os.listdir(src_folder)):
folder_path = os.path.join(src_folder, folder_name)
# Check if it's a directory and its name matches the expected pattern
if os.path.isdir(folder_path) and folder_name.startswith('s') and folder_name.endswith('_g1'):
# Construct the source and destination paths for stats.yaml
src_stats_yaml = os.path.join(folder_path, 'stats.yaml')
dest_section_folder = os.path.join(dest_folder, folder_name)
if Path(dest_section_folder).exists():
dest_stats_yaml = Path(dest_section_folder) / 'stats.yaml'
# Copy the file
shutil.copy(src_stats_yaml, dest_stats_yaml)
# print(f"Copied {src_stats_yaml} to {dest_stats_yaml}")
def create_directory(dir_path: UniPath):
dir_path = Path(cross_platform_path(str(dir_path)))
try:
dir_path.mkdir(parents=True, exist_ok=True)
except FileExistsError:
print(f"Directory '{dir_path}' already exists.")