-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaestro.py
executable file
·1953 lines (1551 loc) · 75.9 KB
/
maestro.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name,missing-docstring,c-extension-no-member,too-many-locals
# Licensed under the GPLv3: https://www.gnu.org/licenses/gpl-3.0.html
# Copyright (c) 2023-2024 Marek Kochańczyk, Paweł Nałęcz-Jawecki, Frederic Grabowski
'''
This module provides command-line utilities to manage and en masse process images generated
by Harmony, software featuring Operetta CLS, a high-throughput microplate imager.
Commands
--------
show
inspect contents (intented uses are: show channels, show wells, show settings)
check
search for single-pixel images and images devoid of respective entries in metadata
remaster
apply flat-field correction, stitch corrected tiles, generate intensity-adjusted pseudo-colored
multi-channel overlays and individual channels in grayscale (collectively termed "remixes"),
and encode movies, all according to a given config file (for an example config file,
see 'example_config.yaml')
trackerabilize
create folders with ShuttleTracker-compatibile views of "remixes" folders obtained during
remastering (using the above-described command 'remaster')
[ShuttleTracker: https://pmbm.ippt.pan.pl/software/shuttletracker]
folderize
move images to respective individual plate well-specific folders
archivize
move images to individual well-specific folders & archive/compress the folders
Type 'python maestro.py COMMAND --help' to learn about COMMAND's arguments and options.
'''
from __future__ import annotations
import sys
import shutil
import string
import re
import random
from operator import itemgetter
from itertools import product
from collections import Counter, defaultdict
from time import sleep
from datetime import timedelta
import pickle
from pathlib import Path
import subprocess as sp
from multiprocessing import Process, Queue
import tarfile
from typing import TYPE_CHECKING, List, Dict, Tuple, Literal
import psutil
import yaml
import click
import pandas as pd
import numpy as np
from tqdm import tqdm
import tifffile
import cv2
from harmony_export import (
EXPORTED_IMAGES_SUBFOLDER_NAME,
EXPORTED_IMAGE_FILE_NAME_RE,
EXPORTED_IMAGE_FILE_NAME_EXTENSION,
OBSERVABLE_COLOR_RE,
EXTRA_TILE_OVERLAP,
WellLocation,
assemble_image_file_name,
get_images_index_file_path,
get_image_files_paths,
determine_timepoints_count,
determine_planes_count,
determine_fields_count,
determine_fields_layout,
determine_channels_count,
field_number_to_xy,
extract_plate_layout,
extract_wells_info,
extract_channels_info,
extract_image_acquisition_settings,
extract_time_interval,
extract_and_derive_images_layout,
)
if TYPE_CHECKING:
from numpy.typing import NDArray
COLOR_COMPONENTS = {
'red': 'R',
'green': 'G',
'blue': 'B',
'cyan': 'GB',
'magenta': 'RB',
'yellow': 'RG',
'gray': 'RGB',
'grey': 'RGB',
}
WELL_PREFIX_NAME = 'well'
CORRTILES_FOLDER_BASE_NAME = 'Tiles'
STITCHES_FOLDER_BASE_NAME = 'Stitches'
REMIXES_FOLDER_BASE_NAME = 'Remixes'
MOVIES_FOLDER_BASE_NAME = 'Movies'
SHUTTLETRACKER_FOLDER_BASE_NAME = 'ST'
TIMESTAMP_SUFFIX = '--timestamped'
CONVERT_EXE_PATH = Path('/usr/bin/convert')
MOGRIFY_EXE_PATH = Path('/usr/bin/mogrify')
XVFB_EXE_PATH = Path('/usr/bin/xvfb-run')
XVFB_SERVER_NUMS = set(range(11, 91))
FIJI_EXE_PATH = Path('/opt/fiji/Fiji.app/ImageJ-linux64')
FIJI_SCRIPT_BASE_PATH = Path('/tmp/stitch-')
TEXT_ANNOTATIONS_DEFAULT_FONT_SIZE = 96
FFMPEG_EXE_PATH = Path('/usr/bin/ffmpeg')
FFMPEG_OPTS_SILENCE = '-nostdin -loglevel error -y'.split()
FFMPEG_OPTS_CODEC = '-vcodec libx264 -pix_fmt yuv420p -an'.split() # -b:v 24M
FFMPEG_OPTS_FILTERS = ''.split() # '-vf deshake'.split() # -vf "crop=trunc(iw/2)*2:trunc(ih/2)*2"
FFMPEG_OPTS_QUALITY = '-preset medium -crf 28 -tune fastdecode'.split()
MOVIE_DEFAULT_REALTIME_SPEEDUP = 3600 # 1m of live experiment => 1h of movie
CLICK_EXISTING_FILE_PATH_TYPE = click.Path(exists=True, file_okay=True, dir_okay=False)
CLICK_EXISTING_FOLDER_PATH_TYPE = click.Path(exists=True, file_okay=False, dir_okay=True)
TQDM_STYLE = {'bar_format': '{desc} {percentage:3.0f}% {postfix}'}
CONVERT_EXE_PATH_S, MOGRIFY_EXE_PATH_S, XVFB_EXE_PATH_S, \
FIJI_EXE_PATH_S, FIJI_SCRIPT_BASE_PATH_S, FFMPEG_EXE_PATH_S = \
map(lambda p: str(p.absolute()), [
CONVERT_EXE_PATH , MOGRIFY_EXE_PATH, XVFB_EXE_PATH , \
FIJI_EXE_PATH , FIJI_SCRIPT_BASE_PATH , FFMPEG_EXE_PATH
])
assert CONVERT_EXE_PATH.exists(), "ImageMagick's 'convert' not found! Install IM or fix the path."
assert MOGRIFY_EXE_PATH.exists(), "ImageMagick's 'mogrify' not found! Install IM or fix the path."
assert FFMPEG_EXE_PATH.exists(), "ffmpeg not found! Install ffmpeg or fix the path."
assert XVFB_EXE_PATH.exists(), "Xvfb not found! Install xvfb-run or fix the path."
assert FIJI_EXE_PATH.exists(), "Fiji not found! Install Fiji.app or fix the path."
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
def _group_paths_by(
files_paths: List[Path],
chunk_re: str,
) -> List[Tuple[int, List[Path]]]:
assert '<groupby>' in chunk_re
groupby_re = re.compile(chunk_re)
grouped_files_paths: Dict[int, List[Path]] = defaultdict(list)
for file_path in files_paths:
groupby_search = groupby_re.search(file_path.name)
assert groupby_search is not None
by = int(groupby_search.group('groupby'))
grouped_files_paths[by].append(file_path)
grouped_files_paths = {by: sorted(paths) for by, paths in grouped_files_paths.items()}
return list(sorted(grouped_files_paths.items(), key=itemgetter(0)))
def _prepare_flatfield_correction_images(
channels_info: pd.DataFrame,
image_shape: Tuple[int, int],
) -> Dict[int, NDArray[np.float64]]:
assert image_shape[0]*image_shape[1] > 1, "Only a stub of an image encountered."
ffc_profile_images = {}
for channel_number in channels_info.index:
flatfield_correction_params = channels_info.loc[channel_number]['Correction']
if flatfield_correction_params['Character'] == 'Null':
ffc_profile_image = np.ones(shape=image_shape)
else:
assert flatfield_correction_params['Character'] == 'NonFlat'
background_profile = flatfield_correction_params['Profile']
(width, height), (origin_x, origin_y), (scale_x, scale_y), coeffs_triangle = [
background_profile[s] for s in ('Dims', 'Origin', 'Scale', 'Coefficients')
]
yy, xx = np.meshgrid(np.arange(width), np.arange(height), indexing='ij')
xx = (xx - origin_x) * scale_x
yy = (yy - origin_y) * scale_y
ffc_profile_image = np.zeros(shape=image_shape)
for coeffs_row in coeffs_triangle:
for j, coeff in enumerate(coeffs_row):
i = len(coeffs_row) - 1 - j
ffc_profile_image += coeff * xx**i * yy**j
ffc_profile_images[channel_number] = ffc_profile_image
return ffc_profile_images
def _read_exported_image(
image_file_path: Path,
image_shape: Tuple[int, int] = (1, 1),
image_dtype: str = 'uint16',
n_attempts: int = 2 # work around occasional 'permission denied' from overloaded SMB servers
) -> NDArray[np.uint16]:
for _attempt_i in range(n_attempts):
if (image:= cv2.imread(image_file_path, cv2.IMREAD_UNCHANGED)) is not None:
return image
sleep(1 + random.choice(range(3)))
print(f"Error reading image file '{str(image_file_path.absolute())}'!")
return np.zeros(shape=image_shape, dtype=image_dtype)
def _flatfield_corrected(
image: NDArray[np.uint16],
profile_image: NDArray[np.float64],
) -> NDArray[np.uint16]:
assert image.dtype == 'uint16', 'Depth of an image subjected to flatfield correction != 16 bit!'
bit_depth = 16
ffced_image = image / profile_image
assert ffced_image.dtype == 'float64'
ffced_image = np.clip(ffced_image, 0, 2**bit_depth - 1)
return ffced_image.astype(np.uint16)
def correct_tiles(
well_id: str,
well_loc: WellLocation,
channels_info: pd.DataFrame,
images_layout: pd.DataFrame,
well_orig_image_files_paths: list,
tiles_folder_path: Path,
force: bool = False,
apply_flatfield_correction: bool = True,
output_file_compression: Literal['none', 'lzw', 'zip'] = 'none'
) -> None:
'''
Multiple single-channel, single-plane images get converted to a single multi-page image files.
'''
by = {
't': r'sk(?P<groupby>[0-9]+)',
'f': r'f(?P<groupby>[0-9]+)',
'p': r'p(?P<groupby>[0-9]+)',
'ch': r'-ch(?P<groupby>[0-9])',
}
tiff_write_opts = {
'photometric': tifffile.PHOTOMETRIC.MINISBLACK,
'compression': {
'none': tifffile.COMPRESSION.NONE,
'lzw': tifffile.COMPRESSION.LZW,
'zip': tifffile.COMPRESSION.DEFLATE,
}[output_file_compression],
'software': 'tifffile.py/maestro',
'metadata': None
}
tiles_folder_path.mkdir(exist_ok=True, parents=True)
# extract common image shape and data type
assert len(well_orig_image_files_paths) > 0
for image_path in well_orig_image_files_paths:
image = _read_exported_image(image_path)
image_shape, image_dtype = image.shape, image.dtype
if image_shape[0]*image_shape[1] != 1:
image_info = {'image_shape': image_shape, 'image_dtype': image_dtype}
break
# use image info to generate flatfield correction profiles
if apply_flatfield_correction:
ffc_profile_images = _prepare_flatfield_correction_images(channels_info, image_shape)
is_correcting_prefix = ''
else:
ffc_profile_images = None
is_correcting_prefix = 'non-'
# process all exported files for a current weel
# order of loops: T --> position --> Z --> C --> XY; nominally, DimensionOrder is XYCZT
image_paths_gby_timepoint = _group_paths_by(well_orig_image_files_paths, by['t'])
t_collection = \
tqdm(
image_paths_gby_timepoint,
desc=f"[{well_id}] {CORRTILES_FOLDER_BASE_NAME}: {is_correcting_prefix}correcting:",
**TQDM_STYLE
) if len(image_paths_gby_timepoint) > 1 else \
image_paths_gby_timepoint
for timepoint, t_paths in t_collection:
t_image_paths_gby_field = _group_paths_by(t_paths, by['f'])
f_collection = \
tqdm(
t_image_paths_gby_field,
desc=f"[{well_id}] {CORRTILES_FOLDER_BASE_NAME}: {is_correcting_prefix}correcting:",
**TQDM_STYLE
) if len(t_image_paths_gby_field) > 1 and len(image_paths_gby_timepoint) == 1 else \
t_image_paths_gby_field
for field, ft_paths in f_collection:
# assemble output image file path
fn = assemble_image_file_name(well_loc.row, well_loc.column, field, 1, 1, timepoint)
field_ix, field_iy = field_number_to_xy(fn, images_layout)
out_image_name = f"Img_t{timepoint - 1:04d}_x{field_ix}_y{field_iy}.tif"
out_image_file_path = tiles_folder_path / out_image_name
# maybe skip generation if the file already exists
if not force and out_image_file_path.exists():
continue
# generate all output file image frames
output_frames = []
for _plane, zft_img_paths in (ft_by_p := _group_paths_by(ft_paths, by['p'])):
for channel, czft_img_paths in (zft_by_ch := _group_paths_by(zft_img_paths, by['ch'])):
for orig_image_file_path in czft_img_paths:
image = _read_exported_image(orig_image_file_path, **image_info)
output_frames.append(
_flatfield_corrected(image, ffc_profile_images[channel])
if apply_flatfield_correction else image
)
# prepare output file OME metadata
ome_xml = tifffile.OmeXml()
extra_metadata = {
'Channel': {'Name': list(channels_info['Observable'])},
}
nz, nch, ny, nx = len(ft_by_p), len(zft_by_ch), image_shape[0], image_shape[1]
ome_xml.addimage(
name = f"Corrected tiles from timepoint: {timepoint}, field: {field}",
dtype=image_dtype,
shape=(nz, nch, ny, nx),
storedshape=(nz*nch, 1, 1, ny, nx, 1),
axes='ZCYX',
**extra_metadata
)
description = ome_xml.tostring()
# write out all image frame to an output file
with tifffile.TiffWriter(out_image_file_path, ome=False) as tiff_writer:
for frame in output_frames:
tiff_writer.write(frame, description=description, **tiff_write_opts)
description = None
def _generate_fiji_stitching_script(script_file_path, **kwargs) -> None:
# Note: 'tile_overlap' is provided, so 'compute_overlap', 'subpixel_sampling' are not requested.
script_template = string.Template('''
setBatchMode(true);
function leftPad(n, width) {
s = "" + n;
while (lengthOf(s) < width) { s = "0" + s; }
return s;
}
ts = "t" + leftPad(${TIMEPOINT}, 4);
fileNamePattern = "Img_" + ts + "_x{x}_y{y}.tif";
run("Grid/Collection stitching", '''
'''"type=[Filename defined position] '''
'''order=[Defined by filename ] '''
'''grid_size_x=" + d2s(${N_FIELDS_X}, 0) + " '''
'''grid_size_y=" + d2s(${N_FIELDS_Y}, 0) + " '''
'''tile_overlap=${TILE_OVERLAP} '''
'''first_file_index_x=0 '''
'''first_file_index_y=0 '''
'''directory=[${TILES_FOLDER}] '''
'''file_names=" + fileNamePattern + " '''
'''output_textfile_name=stitching.txt '''
'''fusion_method=[Linear Blending] '''
'''regression_threshold=0.4 '''
'''max/avg_displacement_threshold=0.5 '''
'''absolute_displacement_threshold=0.75 '''
'''display_fusion '''
'''computation_parameters=[Save computation time (but use more RAM)] '''
'''image_output=[Fuse and display]"); '''
'''
selectWindow("Fused");
if (${DOWNSCALE}) {
run("Scale...", "x=0.5 y=0.5 interpolation=Bilinear average create title=FusedDown");
if (isOpen("Fused")) { close("Fused"); }
selectWindow("FusedDown");
}
// uncompressed by default; does not save OME metadata
//saveAs("Tiff", "${STITCHES_FOLDER}/Img_" + ts + ".tif");
// Bio-Formats has very inefficient compressors (names: LZW, zlib)
run("Bio-Formats Exporter", "save=[${STITCHES_FOLDER}/Img_" + ts + ".ome.tif] compression=Uncompressed");
File.rename("${STITCHES_FOLDER}/Img_" + ts + ".ome.tif", "${STITCHES_FOLDER}/Img_" + ts + ".tif");
if (${DOWNSCALE}) {
close("FusedDown");
} else {
close("Fused");
}
setBatchMode(false);
run("Quit");
''')
script = script_template.substitute(kwargs)
with open(script_file_path, 'w', encoding='UTF-8') as script_file:
print(script, file=script_file)
def stitch_tiles(
well_id: str,
n_fields_xy: tuple,
tiles_folder_path: Path,
stitches_folder_path: Path,
tile_overlap: float,
compression: Literal['none', 'lzw', 'deflate'],
downscale: bool = False,
force: bool = False,
require_no_zero_pixels_in_output_image: bool = True,
zero_pixels_in_output_image_retries_count: int = 5,
same_zero_pixels_counts_consecutively_for_early_exit: int = 2,
) -> None:
assert tiles_folder_path.exists(), \
f"Tiles folder '{tiles_folder_path.absolute()}' does not exist!"
assert tiles_folder_path.is_dir()
assert compression.lower() in ['none', 'lzw', 'deflate']
stitches_folder_path.mkdir(exist_ok=True, parents=True)
n_fields_x, n_fields_y = n_fields_xy
tile_images_paths = get_image_files_paths(tiles_folder_path)
tile_images_paths_grouped_by_timepoint = _group_paths_by(tile_images_paths,
r't(?P<groupby>[0-9]{4})')
if n_fields_x == n_fields_y == 1:
require_no_zero_pixels_in_output_image = False
zero_pixels_in_output_image_retries_count = 0
desc = (
f"[{well_id}] {STITCHES_FOLDER_BASE_NAME}: "
f"{'fijing:' if n_fields_x*n_fields_y>1 else 'copying:'}"
)
for timepoint, tile_images_paths in tqdm(tile_images_paths_grouped_by_timepoint, desc=desc,
**TQDM_STYLE):
dst_file_path = stitches_folder_path / f"Img_t{int(timepoint):04d}.tif"
if not force and dst_file_path.exists() and dst_file_path.stat().st_size > 0:
continue
src_tiles_folder = tile_images_paths[0].parent
if n_fields_x == n_fields_y == 1:
src_file_path = src_tiles_folder / f"Img_t{int(timepoint):04d}_x0_y0.tif"
assert src_file_path.exists()
shutil.copy(src_file_path, dst_file_path)
else:
n_trials_remaining = zero_pixels_in_output_image_retries_count
zero_pixel_counts = []
while n_trials_remaining > 0:
n_trials_remaining -= 1
fiji_script_path_s = FIJI_SCRIPT_BASE_PATH_S \
+ ''.join(random.choice(string.ascii_uppercase + string.digits)
for _ in range(12)) + '.ij1'
substitutions = {
'TIMEPOINT': timepoint,
'N_FIELDS_X': n_fields_x,
'N_FIELDS_Y': n_fields_y,
'TILES_FOLDER': str(src_tiles_folder.absolute()),
'STITCHES_FOLDER': str(stitches_folder_path.absolute()),
'TILE_OVERLAP': tile_overlap + EXTRA_TILE_OVERLAP,
'DOWNSCALE': str(downscale).lower(),
}
_generate_fiji_stitching_script(fiji_script_path_s, **substitutions)
xvfb_server_nums_currently_in_use = {
int(arg[1:])
for process in psutil.process_iter()
for arg in process.cmdline()
if arg.startswith(':')
if process.name() == 'Xvfb'
}
xvfb_server_num = random.choice(
list(XVFB_SERVER_NUMS - xvfb_server_nums_currently_in_use)
)
try:
# When using the ImageJ's `--headless` flag, the Bio-Formats Exporter fails.
cmd = [
XVFB_EXE_PATH_S, '--auto-servernum', f"--server-num={xvfb_server_num}",
FIJI_EXE_PATH_S, '-macro', fiji_script_path_s
]
sp.run(cmd, stdout=sp.DEVNULL, stderr=sp.DEVNULL, check=True, timeout=3600)
except sp.TimeoutExpired:
print('Fiji TIMED OUT while stitching!')
raise
except:
with open(fiji_script_path_s, 'r', encoding='utf-8') as f:
print(40*'- ')
print(f.read())
print(40*'- ')
raise
Path(fiji_script_path_s).unlink()
if require_no_zero_pixels_in_output_image:
reading_ok, dst_img = cv2.imreadmulti(dst_file_path, flags=cv2.IMREAD_UNCHANGED)
assert reading_ok
assert len(dst_img) > 0
zero_pixel_count = \
np.sum(dst_img == 0) if len(dst_img) == 1 else \
sum(np.sum(frame == 0) for frame in dst_img)
if zero_pixel_count == 0:
break
zero_pixel_counts.append(zero_pixel_count)
z = same_zero_pixels_counts_consecutively_for_early_exit
if len(zero_pixel_counts) >= z and len(set(zero_pixel_counts[-z:])) == 1:
break
else:
break
# ImageMagick's delfate compression is more efficient compared to the Bio-Formats Exporter
if compression != 'none':
if compression.lower() in ['deflate', 'zip', 'zlib']:
compression = 'zip'
dst_file_path_s = str(dst_file_path.absolute())
cmd = [MOGRIFY_EXE_PATH_S, '-compress', compression, dst_file_path_s]
sp.run(cmd, stdout=sp.DEVNULL, stderr=sp.DEVNULL, check=True)
def _assemble_imagemagick_crop_args(
image_files_paths: list,
downscale: bool
) -> List[str]:
min_width, min_height = 2*(sys.maxsize,)
for image_file_path in image_files_paths:
# width, height = cv2.imread(str(image_file_path.absolute()), cv2.IMREAD_UNCHANGED).shape
height, width = tifffile.TiffFile(image_file_path).pages[0].shape[0:2]
min_width = min(width, min_width)
min_height = min(height, min_height)
if downscale:
min_width //= 2
min_height //= 2
if min_width % 2:
min_width -= 1
if min_height % 2:
min_height -= 1
# just in case
min_width -= 2
min_height -= 2
return ['-crop', f"{min_width}x{min_height}+0+0"]
def _assemble_suffix(info: pd.DataFrame) -> str:
if len(info) > 1:
suffix = "-".join(f"{entries['Observable']}_{color}" for color, entries in info.iterrows())
elif len(info) == 1:
observable = info.iloc[0]['Observable']
suffix = f"{observable}"
else:
assert len(info) > 0
return suffix
def _intensity_range_arithmetics(obs_norm: str, obs_name: str) -> Tuple[str, str]:
# 'Normalization' means manual adjustment of the dynamic range of pixel intensities.
if pd.isna(obs_norm):
print(f"Warning: Missing normalization for observable '{obs_name}'! Assuming -0, *1.")
return ('0', '1.')
normalization_re1 = re.compile(r'-(?P<sub>[0-9]+)?'
r'\ *,\ *'
r'\*(?P<mul>(\d+(\.\d*)?)|(\.\d+))?')
if normalization_re1_match := normalization_re1.fullmatch(obs_norm):
return tuple(map(normalization_re1_match.group, ['sub', 'mul']))
normalization_re2 = re.compile(r'((?P<begin>(\d+(\.\d*)?)|(\.\d+))%)?'
r'\ *...\ *'
r'((?P<end>(\d+(\.\d*)?)|(\.\d+))%)?')
if normalization_re2_match := normalization_re2.fullmatch(obs_norm):
begin, end = map(float, map(normalization_re2_match.group, ['begin', 'end']))
return tuple(map(str, [int((begin/100.)*(2**16 - 1)), 100./(end - begin)]))
print("Cannot parse the normalization for observable '{obs_name}' ('obs_norm'?)! "
"Assuming -0, *1.")
return ('0', '1.')
def _derive_channels_composition(mixing_info: pd.DataFrame) -> dict:
# single_channel
if len(mixing_info) == 1 and mixing_info.index[0] == 'gray':
tiff_page, obs_norm = mixing_info[['TiffPage', 'Normalization']].iloc[0]
sub, mul = _intensity_range_arithmetics(obs_norm, mixing_info['Observable'].iloc[0])
return {'gray': (tiff_page, (sub, mul))}
# multi_channel
composition: Dict[str, List[tuple]] = {}
for component in 'RGB':
composition[component] = []
for color, (tiff_page, obs_norm) in mixing_info[['TiffPage', 'Normalization']].iterrows():
if component in COLOR_COMPONENTS[color]:
sub, mul = _intensity_range_arithmetics(obs_norm, color)
component_definition = (tiff_page, (sub, mul))
composition[component].append(component_definition)
return composition
def remix_channels(
well_id: str,
mixing_info: pd.DataFrame,
stitches_folder_path: Path,
well_remixes_folder_path: Path,
downscale: bool = False,
force: bool = False,
wells_info_for_annotation: pd.DataFrame | None = None,
is_part_of_timeseries: bool = False,
annotation_font_size: int = TEXT_ANNOTATIONS_DEFAULT_FONT_SIZE,
) -> None:
assert stitches_folder_path.exists() and stitches_folder_path.is_dir()
well_remixes_folder_path.mkdir(exist_ok=True, parents=True)
well_stitches_images_paths = get_image_files_paths(stitches_folder_path)
well_stitches_images_paths_grouped_by_timepoint = _group_paths_by(well_stitches_images_paths,
r't(?P<groupby>[0-9]{4})')
crop_args = _assemble_imagemagick_crop_args(well_stitches_images_paths, downscale)
suffix = _assemble_suffix(mixing_info)
composition = _derive_channels_composition(mixing_info)
if len(composition) == 1:
grayscale = True
composition_s = f"(gray) ≡ ({mixing_info.iloc[0]['Observable']})"
else:
grayscale = False
composition_s = ', '.join(map(lambda s: '~' if s == '' else s, [
'+'.join([
mixing_info[ mixing_info['TiffPage'] == cc[0] ]['Observable'].values[0]
for cc in composition[c]
])
for c in 'RGB'
]))
composition_s = f"(R, G, B) ≡ ({composition_s})"
for timepoint, stitches_image_path in tqdm(
well_stitches_images_paths_grouped_by_timepoint,
desc=f"[{well_id}] {REMIXES_FOLDER_BASE_NAME}: mixing {composition_s}:",
**TQDM_STYLE
):
assert len(stitches_image_path) == 1
stitches_image_path = stitches_image_path.pop()
rgb_overlay_file_path = well_remixes_folder_path / f"Img_t{int(timepoint):04}--{suffix}.png"
if not force and rgb_overlay_file_path.exists() and rgb_overlay_file_path.stat().st_size >0:
continue
source_image_path_s = str(stitches_image_path.absolute())
target_image_path_s = str(rgb_overlay_file_path.absolute())
cmd = [CONVERT_EXE_PATH_S]
if grayscale:
tiff_page, (sub, mul) = composition['gray']
cmd.append(f"{source_image_path_s}[{tiff_page}]")
cmd.extend(['-colorspace', 'gray'])
cmd.extend(['-evaluate', 'subtract', sub])
cmd.extend(['-evaluate', 'multiply', mul])
cmd.extend(['-set', 'colorspace', 'gray'])
else:
cmd.extend(['-background', 'black'])
used_component_channels = ''
for component in 'RGB':
n_source_channels = len(composition[component])
if n_source_channels == 0:
continue
assert n_source_channels < 3, \
f"""Too many source channels for the *{
{'R': 'red', 'G': 'green', 'B': 'blue'}[component]
}* component of the overlay!"""
used_component_channels += component
if n_source_channels == 2:
cmd.append('(')
for tiff_page, (sub, mul) in composition[component]:
cmd.append('(')
cmd.extend(['-evaluate', 'subtract', sub])
cmd.extend(['-evaluate', 'multiply', mul])
cmd.append(f"{source_image_path_s}[{tiff_page}]")
cmd.append(')')
if n_source_channels == 2:
cmd.extend(['-compose', 'plus', '-composite']) # IM cannot compose >2 images.
cmd.append(')')
cmd.extend(['-channel', used_component_channels])
cmd.extend(['-colorspace', 'RGB'])
cmd.append('-combine')
cmd.extend(['-depth', '8'])
cmd.extend(['-alpha', 'remove', '-alpha', 'off'])
if downscale:
cmd.extend(['-scale', '50%'])
cmd.extend(crop_args)
cmd.extend('-define png:compression-filter=0 ' # Empirically determined
'-define png:compression-level=9 ' # to give best compression
'-define png:compression-strategy=2'.split()) # ratio at a reasonable speed.
cmd.append(target_image_path_s)
sp.run(cmd, stdout=sp.DEVNULL, stderr=sp.DEVNULL, check=True)
if not wells_info_for_annotation is None:
well_info = wells_info_for_annotation[
wells_info_for_annotation['WellId'] == well_id
]
text = (' `\n\n' if is_part_of_timeseries else '') + '\n'.join([
f"{k.replace('WellId', 'WELL')}: {well_info.iloc[0].to_dict()[k]}"
for k in well_info.columns
])
cmd = [
'convert',
'-size', '1800x1200+0+0', 'xc:none',
'-font', 'Helvetica', '-pointsize', str(annotation_font_size),
'-stroke', 'gray', '-strokewidth', '2',
'-gravity', 'north-west',
'-annotate', '0', text,
'-background', 'none',
'-shadow', '1800x0+0+0', '+repage',
'-font', 'Helvetica', '-pointsize', str(annotation_font_size),
'-stroke', 'none', '-fill', 'LightGray',
'-gravity', 'north-west',
'-annotate', '0', text,
target_image_path_s, '+swap',
'-gravity', 'north-west',
'-geometry', f"+{annotation_font_size//4}+{annotation_font_size//4}",
'-composite',
target_image_path_s,
]
sp.run(cmd, check=True)
def _annotate_remixes_with_timestamps(
well_id,
well_remixes_folder_path: Path,
well_movies_folder_path: Path,
delta_t_secs: float,
obs_suffix: str,
force: bool = False,
annotation_font_size: int = TEXT_ANNOTATIONS_DEFAULT_FONT_SIZE,
) -> None:
remixes_image_files_paths = well_remixes_folder_path.glob(f"Img_t*--{obs_suffix}.png")
desc = f"[{well_id}] Movies: annotating mix '{obs_suffix}':"
for ti, path in enumerate(tqdm(sorted(remixes_image_files_paths), **TQDM_STYLE, desc=desc)):
time_min_i = int(ti*delta_t_secs/60)
time_min_s = f"{time_min_i // 60:02d}h {time_min_i % 60:02d}m"
p_annot = well_movies_folder_path / f"{path.stem}{TIMESTAMP_SUFFIX}{path.suffix}"
if not force and p_annot.exists():
continue
cmd = [
'convert',
'-size', '360x90', 'xc:none',
'-gravity', 'center',
'-font', 'Helvetica', '-pointsize', str(annotation_font_size),
'-stroke', 'gray', '-strokewidth', '2',
'-annotate', '0', time_min_s,
'-background', 'none',
'-shadow', '360x5+0+0', '+repage',
'-font', 'Helvetica', '-pointsize', str(annotation_font_size),
'-stroke', 'none', '-fill', 'LightGray',
'-annotate', '0', time_min_s,
str(path.absolute()), '+swap',
'-gravity', 'north-west',
'-geometry', f"+{annotation_font_size//2}+{annotation_font_size//4}",
'-composite',
str(p_annot.absolute())
]
sp.run(cmd, check=True)
def encode_movies(
well_id: str,
infos: List[pd.DataFrame],
delta_t: timedelta,
well_remixes_folder_path: Path,
well_movies_folder_path: Path,
realtime_speedup: int,
force: bool = False,
annotate_with_timestamp: bool = True,
annotation_font_size: int = TEXT_ANNOTATIONS_DEFAULT_FONT_SIZE,
force_annotation: bool = False,
clean_up_images_annotated_with_timestamp: bool = True,
) -> None:
assert delta_t is not None
delta_t_secs = delta_t.total_seconds()
movie_fps_s = f"{round(realtime_speedup)}/{round(delta_t_secs)}" # rational
movie_fps_i = round(realtime_speedup/delta_t_secs) # used for frequency of keyint insertion
movie_fps_i = max(movie_fps_i, 1)
well_movies_folder_path.mkdir(exist_ok=True, parents=True)
for obs_suffix in map(_assemble_suffix, infos):
movie_file_name = f"{well_id}--{obs_suffix}.mp4"
movie_file_path = well_movies_folder_path / movie_file_name
if not force and movie_file_path.exists() and movie_file_path.stat().st_size > 48:
print(f"[{well_id}] {MOVIES_FOLDER_BASE_NAME}: '{movie_file_name}' exists "
"(encoding skipped)")
continue
if annotate_with_timestamp:
_annotate_remixes_with_timestamps(well_id, well_remixes_folder_path,
well_movies_folder_path, delta_t_secs, obs_suffix,
force=force_annotation,
annotation_font_size=annotation_font_size)
source_image_files_folder_path = well_movies_folder_path
input_image_filename_pattern = f"Img_t%04d--{obs_suffix}{TIMESTAMP_SUFFIX}.png"
else:
source_image_files_folder_path = well_remixes_folder_path
input_image_filename_pattern = f"Img_t%04d--{obs_suffix}.png"
ffmpeg_opts_filters = FFMPEG_OPTS_FILTERS
example_image_path_s = str(next(source_image_files_folder_path.glob('*.png')))
example_image_shape = cv2.imread(example_image_path_s, cv2.IMREAD_UNCHANGED).shape
if max(example_image_shape) > 8192:
print("Warning: Images to be encoded are very large => halving movie width and height.")
ffmpeg_opts_filters.extend('-vf scale=trunc((iw/2)/2)*2:trunc((ih/2)/2)*2'.split())
cmd = [
FFMPEG_EXE_PATH_S,
*FFMPEG_OPTS_SILENCE,
'-r', movie_fps_s,
'-f', 'image2',
'-i', str((source_image_files_folder_path / input_image_filename_pattern).absolute()),
*ffmpeg_opts_filters,
*FFMPEG_OPTS_CODEC,
'-x264-params', f"keyint={3*movie_fps_i}:scenecut=0",
*FFMPEG_OPTS_QUALITY,
str(movie_file_path.absolute())
]
print(f"[{well_id}] {MOVIES_FOLDER_BASE_NAME}: encoding '{movie_file_name}' ", end='... ',
flush=True)
sp.run(cmd, check=True)
print('done')
if annotate_with_timestamp and clean_up_images_annotated_with_timestamp:
for path in well_movies_folder_path.glob(f"Img_t*--{obs_suffix}--timestamped.png"):
path.unlink()
def _place_image_files_in_their_respective_well_folders(
images_folder: Path,
abolish_internal_compression: bool = True,
tolerate_extra_files: bool = False,
retain_original_files: bool = False,
) -> List[Path]:
images_folder_path = Path(images_folder)
if not images_folder_path.exists():
print(f"Error: The source folder '{images_folder_path.absolute()}' does not exist!")
return []
if images_folder_path.resolve().name != EXPORTED_IMAGES_SUBFOLDER_NAME:
print("Error: The images folder argument should point to a folder named "
f"'{EXPORTED_IMAGES_SUBFOLDER_NAME}'!")
return []
# the index file is not required currently, but lack thereof is perceived suspicious
if get_images_index_file_path(images_folder_path.parent) is None:
print("Error: The images folder does not contain any index XML file!")
return []
files_paths = [
item for item in images_folder_path.iterdir()
if item.is_file() and not item.is_symlink()
]
image_files_paths = [
file_path for file_path in files_paths
if EXPORTED_IMAGE_FILE_NAME_RE.match(
re.sub('.orig$', '', file_path.name) # accepting both '*.tiff' and '*.tiff.orig'
)
]
# the folder is impure, refuse to continue just in case
if len(files_paths) != len(image_files_paths) + 1:
message_type, end_mark = ('Warning', '.') if tolerate_extra_files else ('Error', '!')
print(f"{message_type}: The source folder '{images_folder_path.absolute()}' "
f"appears to contain some extra files{end_mark}")
if not tolerate_extra_files:
return []
# -- build {(row, col): [list of all images of the well in the (row, col)]} --------------------
def extract_row_col_(path: Path) -> tuple:
image_name_match = EXPORTED_IMAGE_FILE_NAME_RE.search(path.name)
assert image_name_match is not None
return tuple(map(image_name_match.group, ['row', 'column']))
def assemble_well_folder_name_(row: str, col: str) -> str:
return f"{WELL_PREFIX_NAME}-{row}{col}"
wells_images: dict = {
extract_row_col_(image_path): []
for image_path in image_files_paths
}
for image_path in image_files_paths:
row, col = extract_row_col_(image_path)
wells_images[(row, col)].append(image_path)
# -- copy/move image files ---------------------------------------------------------------------
transfer_file = shutil.copy2 if retain_original_files else shutil.move
for (row, col), image_files in sorted(wells_images.items()):
dest_dir_path = images_folder_path / assemble_well_folder_name_(row, col)
if dest_dir_path.exists():
print(f"Warning: destination folder {dest_dir_path.absolute()} already exists!")
dest_dir_path.mkdir(exist_ok=False, parents=False)
desc = f"{EXPORTED_IMAGES_SUBFOLDER_NAME}/[{len(image_files)} images]" \
f" ⤚({transfer_file.__name__})→ " \
f"{EXPORTED_IMAGES_SUBFOLDER_NAME}/{dest_dir_path.name}:"
for image_file in tqdm(image_files, desc=desc, **TQDM_STYLE):
assert image_file.exists()
transfer_file(image_file, dest_dir_path)
if abolish_internal_compression:
image_file_path = dest_dir_path / image_file.name
assert image_file_path.exists(), f"File '{image_file_path}' disappeared!"
compress_args = ['-compress', 'none']
image_file_path_s = str(image_file_path.absolute())