-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetSTMbufs.py
executable file
·1933 lines (1717 loc) · 64.8 KB
/
getSTMbufs.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 parseSTM as ps
import imageio
from skimage.filters import gaussian, threshold_otsu
from skimage.exposure import rescale_intensity
import numpy as np
from myImageToolset import (
normalize_img,
imreg,
crop_image_set,
destripe_by_wavelet_svd,
)
from os.path import split, join
import pystripe as stripe
from detrend2d import subtract_plane
import argparse
from skimage.feature import register_translation, match_template
from scipy.ndimage import shift
import matplotlib as mpl
import cv2
from scipy.ndimage import zoom
from skimage.color import rgb2gray
import copy
import matplotlib
import pywt
from scipy import fftpack
from os import remove
from skimage.measure import compare_ssim
import matplotlib.ticker as mtick
from skimage.morphology import remove_small_objects
from skimage.segmentation import clear_border
# matplotlib.use("MacOSX")
import matplotlib.pyplot as plt
plt.ioff()
def _parseargs():
parser = argparse.ArgumentParser(
description="Extract image buffers from Lyding STM file\n\n",
epilog="Developed by Huy Nguyen, Gruebele-Lyding Groups\n"
"University of Illinois at Urbana-Champaign\n",
)
parser.add_argument(
"input",
nargs="*",
type=str,
help="Contact [email protected] for information about Lyding STM file format",
)
parser.add_argument(
"--buffers",
"-b",
help="Specific buffers to extract",
type=int,
required=True,
nargs="*",
)
parser.add_argument("--logfile", help="Movie log file", type=str)
parser.add_argument("--frames", help="Number of movie frames", type=int)
parser.add_argument(
"--register",
"-r",
help="Translationally register the image set to the first input file.",
action="store_true",
)
parser.add_argument(
"--colormap",
"-c",
help="Colormap to use for the lock-in buffers",
type=str,
default="gray_r",
)
parser.add_argument(
"--destripe",
"-s",
help="Attempt to remove stripes from the buffers (helpful for topography)",
action="store_true",
)
parser.add_argument(
"--gauss",
"-g",
help="Specify a sigma if a Gaussian filtering operation on the images are desired.",
type=float,
default=None,
)
parser.add_argument(
"--lockin",
"-l",
help="Lock-in values (in order of sensitivity, expand, offset) for the X and Y buffers. For now, this option is ignored",
nargs=3,
type=float,
default=None,
)
parser.add_argument(
"--movie",
"-m",
help="Create a movie out of the STM files in the order of inputs (will register images by default, but remember to omit register flag when having movie flag on)",
action="store_true",
)
parser.add_argument(
"--stretch-contrast",
"-e",
help="Specify the percentile to stretch image contrast",
required=False,
nargs=2,
type=float,
default=None,
)
parser.add_argument(
"--filenames",
"-f",
help="Replace original filenames with a set of specified names",
nargs="*",
default=None,
type=str,
)
parser.add_argument(
"--textcolor",
"-t",
help="Textcolor for annotation of movies. Support black and white",
default="white",
type=str,
)
parser.add_argument(
"--normalize",
"-n",
help="Normalize the series of images by the first image.",
action="store_true",
)
parser.add_argument(
"--secondarySet",
"-a",
help="Whether to use topographic set as to align when registering images (movies and regular)",
action="store_true",
)
parser.add_argument(
"--svd",
"-q",
help="Perform SVD on the movie series and plot the weight of U matrix against time. Please specify an integer smaller than the minimum dimension of the frame.",
type=int,
)
parser.add_argument(
"--level",
"-z",
help="Maximum level up to which wavelet decomposition (image destriping) works.",
type=int,
default=None,
)
parser.add_argument(
"--wavelet",
"-w",
help="Mother wavelet to use for wavelet decomposition (image destriping).",
type=str,
default="sym7",
)
parser.add_argument(
"--level-svd",
"-x",
help="Maximum level up to which wavelet decomposition (wavelet svd) works.",
type=int,
default=None,
)
parser.add_argument(
"--wavelet-svd",
"-y",
help="Mother wavelet to use for wavelet decomposition (wavelet svd).",
type=str,
default="sym7",
)
parser.add_argument(
"--route2", help="Use the wavelet svd method", action="store_true"
)
parser.add_argument(
"--foreground",
action="store_true",
help="If on, extract svd from foreground (using Otsu thresholding) only",
)
parser.add_argument(
"--background",
action="store_true",
help="If on, extract svd from background (using Otsu thresholding) only",
)
args = parser.parse_args()
return args
def lockin_value(x, sensitivity, expand, offset):
return (x / expand / 10000 + offset) * sensitivity
def wavelet_filter_1d(arr, wavelet_type="db3", level=3, threshold_mode="soft"):
arr = np.array(arr).flatten()
coeffs = pywt.wavedec(arr, wavelet_type, level=level)
approx = coeffs[0]
detail = coeffs[1:]
# coeffs[1:] = [
# pywt.threshold(coeff, np.std(coeff) * 3, mode=threshold_mode)
# for coeff in coeffs[1:]
# ]
coeffs_filt = [approx]
for nlevel in detail:
fdetail = fftpack.rfft(nlevel)
# b, a = signal.butter(6, 0.1, btype="low")
# fdetail = signal.filtfilt(b, a, fdetail, padlen=5)
fdetail = pywt.threshold(
fdetail, np.std(fdetail) * 3, mode=threshold_mode
)
coeffs_filt.append(fftpack.irfft(fdetail))
return pywt.waverec(coeffs_filt, wavelet_type)
def wavelet_filter_3d(array3d, wavelet="db3", level=3):
array3d = np.array(array3d)
out = np.apply_along_axis(
wavelet_filter_1d, 0, array3d, wavelet, level, "soft"
)
if out.shape[0] == array3d.shape[0] + 1:
out = out[:-1]
return out
def read_img(path, buf, with_right_unit=False):
stmfile = ps.STMfile(path)
if with_right_unit:
out = stmfile.get_height_buffers([buf])[buf]
else:
out = normalize_img(
stmfile.get_buffers([buf])[buf],
0,
2 ** 16 - 1,
from_vmin=-32768,
from_vmax=32767,
)
return out
def get_bufset(paths, bufs, with_right_unit=False):
out = {}
for buf in bufs:
out[buf] = np.array([read_img(path, buf, with_right_unit=with_right_unit) for path in paths])
return out
def img_process(img, buf, gauss=None):
"""Will preserve the dtype of the np array and won't normalize min max"""
# out = np.copy(img)
out = copy.deepcopy(img)
if buf < 3:
out = subtract_plane(out)
if gauss is not None:
out = gaussian(out, sigma=gauss)
return out.astype("float")
def img_post_process(
img, destripe=False, wavelet="sym10", level=None, sc=None
):
"""Will return a 16-bit image. For now, buf is a placeholder to make other process easier."""
# out = np.copy(img)
out = copy.deepcopy(img)
out = normalize_img(out, 0, 2 ** 16 - 1).astype("uint16")
if destripe:
out = stripe.filter_streaks(
out, sigma=[20, 20], level=level, wavelet=wavelet
)
# img = rescale_intensity(
# img, in_range=(np.percentile(img, 0.3), np.percentile(img, 99.7))
# )
if sc is not None:
out = np.clip(
out, np.percentile(out, sc[0]), np.percentile(out, sc[1])
)
out = normalize_img(out, 0, 2 ** 16 - 1).astype("uint16")
return out
def img_post_process2(
img, destripe=False, wavelet="sym7", level=None, sc=None
):
"""Perform image processing to remove the stripes and stretch constrast,
if necessary. Output will be a 16-bit image normalized to (0, 2**16-1)
Arguments:
img {numpy.2darray} -- Image to be destriped
Keyword Arguments:
destripe {bool} -- Destripe Image or not (default: {False})
wavelet {str} -- PyWavelet's discrete wavelet to be used for destriping (default: {sym7})
level {int} -- Maximum level of wavelet decomposition (default: {maximum level determined
by pywt.dwt_max_level})
sc {(float, float)} -- tuple of floats that specify the lower and
upper percentiles of img intensity to stretch contrast(default: {None})
Returns:
numpy.2darray -- Post-processed array of img. dtype=uint16
"""
# out = np.copy(img)
out = copy.deepcopy(img)
if destripe:
out = destripe_by_wavelet_svd(out, wavelet=wavelet, level=level)
# img = rescale_intensity(
# img, in_range=(np.percentile(img, 0.3), np.percentile(img, 99.7))
# )
if sc is not None:
out = np.clip(
out, np.percentile(out, sc[0]), np.percentile(out, sc[1])
)
# out = normalize_img(out, 0, 2 ** 16 - 1).astype("uint16")
return out
def img_process_set(imset, bufs, gauss=None):
""" Specific routine for processing the image subset of data type: imset -> {buf#1: [img1, img2, ...], buf#2: [img1, img2, ...]}
# <-- subset -->
"""
# out = imset.copy()
out = {}
for buf in bufs:
out[buf] = np.array([img_process(im, buf, gauss) for im in imset[buf]])
return out
def img_process_set2(imset, gauss=None):
"""Specific routine for processing the full image set of data type: imset -> {buf#1: [img1, img2, ...], buf#2: [img1, img2, ...]}
"""
# out = np.copy(imset).item()
out = {}
for key in imset:
out[key] = np.array([img_process(im, key, gauss) for im in imset[key]])
return out
def img_post_process_set(
imset, bufs, destripe=False, wavelet="sym7", level=None, sc=None
):
"""Specific routine for processing the image subset of data type: imset -> {buf#1: [img1, img2, ...], buf#2: [img1, img2, ...]}
# <-- subset -->
"""
out = {}
for buf in bufs:
out[buf] = np.array(
[
img_post_process(
im, destripe=destripe, wavelet=wavelet, level=level, sc=sc
)
for im in imset[buf]
]
)
return out
def img_post_process_set2(
imset, destripe=False, wavelet="sym7", level=None, sc=None
):
"""Specific routine for processing the full image set of data type: imset -> {buf#1: [img1, img2, ...], buf#2: [img1, img2, ...]}"""
# out = np.copy(imset).item()
out = {}
for key in imset:
out[key] = np.array(
# [
# img_post_process(im, destripe=destripe, sc=sc)
# for im in imset[key]
# ]
[
img_post_process2(
im, destripe=destripe, wavelet=wavelet, level=level, sc=sc
)
for im in imset[key]
]
)
return out
def normalize_set_to_uint16(imset):
out = {}
for key in imset:
out[key] = np.array(
[
normalize_img(im, 0, 2 ** 16 - 1).astype("uint16")
for im in imset[key]
]
)
return out
def register_bufferset(imset, bufs, secondarySet=None, filter=False):
# out = np.copy(imset).item()
out = copy.deepcopy(imset)
filtered_set = img_post_process_set(out, bufs, destripe=True, sc=None)
for buf in bufs:
if filter:
out[buf] = np.array(
imreg(
out[buf],
secondarySet=filtered_set[buf],
upsample_factor=100,
)
)
else:
out[buf] = np.array(
imreg(out[buf], secondarySet=secondarySet, upsample_factor=100)
)
return out
def register_bufferset2(imset, secondarySet=None, filter=False):
# out = np.copy(imset).item()
out = copy.deepcopy(imset)
filtered_set = img_post_process_set2(out, destripe=True)
for buf in out:
if filter:
out[buf] = np.array(
imreg(
out[buf],
secondarySet=filtered_set[buf],
upsample_factor=100,
)
)
else:
out[buf] = np.array(
imreg(out[buf], secondarySet=secondarySet, upsample_factor=100)
)
return out
def zoom_buffer_set(imset):
"""Increase the DPI of the images by 6 times"""
# out = np.copy(imset).item()
out = copy.deepcopy(imset)
for key in out:
out[key] = np.array(
[zoom(im, zoom=6, order=0, mode="constant") for im in out[key]]
)
return out
def annotate_image(img, text, textcolor="black", sc=(1, 99)):
"""The annotation will return an image of the same dtype"""
# out = np.copy(img)
out = copy.deepcopy(img)
dtype = out.dtype
if dtype.kind == "u":
mn = 0
mx = 2 ** (dtype.itemsize * 8) - 1
else:
mn = -2 ** (dtype.itemsize * 7)
mx = 2 ** (dtype.itemsize * 7) - 1
# out = np.uint16(normalize_img(out, 0, 2 ** 16 - 1))
# out = np.uint16(out)
# img = np.uint16(img)
org = (int(0.08 * out.shape[0]), int(0.12 * out.shape[1]))
# # coordinates = (int(0.4 * new_imset[0].shape[0]), int(0.12 * new_imset[0].shape[1]))
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = np.min(out.shape) / (80 / 0.3)
coordinates = (org[0], org[1])
# 3 for " ps"
if textcolor == "black":
fontColor = (mn, mn, mn)
elif textcolor == "white":
fontColor = (mx, mx, mx)
# fontColor = (2 ** 16 - 1, 2 ** 16 - 1, 2 ** 16 - 1)
lineType = 3
thickness = 1
cv2.putText(
out, text, coordinates, font, fontScale, fontColor, lineType, thickness
)
out = rgb2gray(out)
# if sc is not None:
# sc = list(sc)
# out = np.clip(
# out, np.percentile(out, sc[0]), np.percentile(out, sc[1])
# )
# out = np.uint16(normalize_img(out, 0, 2 ** 16 - 1))
# out = np.uint16(out)
return out
def annotate_imset(imset, textlist, textcolor="black", sc=(1, 99)):
"""imset is a list of images, unlike the other routines. The annotation will return a normalized uint16 image"""
assert len(textlist) == len(
imset
), "Image set and textlist have different lengths."
new_imset = []
# imset_cp = np.copy(imset)
imset_cp = copy.deepcopy(imset)
for i in range(len(textlist)):
new_imset.append(
annotate_image(imset_cp[i], textlist[i], textcolor, sc)
)
return np.array(new_imset)
def annotate_bufset(bufset, textlist, textcolor="black", sc=(1, 99)):
# out = np.copy(bufset).item()
out = copy.deepcopy(bufset)
for key in out:
out[key] = annotate_imset(out[key], textlist, textcolor, sc)
return out
def fit_colormap(img, cmap="gray_r"):
"""The colormap fit will return a uint16 image"""
# out = np.copy(img)
out = copy.deepcopy(img)
cm = mpl.cm.get_cmap(cmap, 2 ** 16)
out = normalize_img(out, 0, 1)
# out = out / (2**16-1)
out = np.uint16(cm(out) * (2 ** 16 - 1))
return out
def fit_colormap_to_imset(imset, cmap="gray_r"):
"""imset is a list of images, unlike the other routines. The colormap fit will return a uint16 image"""
new_imset = []
# imset_cp = np.copy(imset)
imset_cp = copy.deepcopy(imset)
mx = imset_cp.max()
cm = mpl.cm.get_cmap(cmap, 2 ** 16)
for img in imset_cp:
# img = img.astype("float") / mx
# new_imset.append(np.uint16(cm(img) * (2**16-1)))
new_imset.append(fit_colormap(img, cmap))
return np.array(new_imset)
def fit_colormap_to_bufset(bufset, lockin_map="gray_r"):
# out = np.copy(bufset).item()
out = copy.deepcopy(bufset)
for key in out:
if key < 3:
out[key] = fit_colormap_to_imset(out[key], "afmhot")
else:
out[key] = fit_colormap_to_imset(out[key], lockin_map)
return out
def pad_imset(imset):
# imset_cp = np.copy(imset)
imset_cp = copy.deepcopy(imset)
shapes = np.array([[im.shape[0], im.shape[1]] for im in imset_cp])
max_i = shapes[:, 0].max()
max_j = shapes[:, 1].max()
new_imset = []
for im in imset_cp:
im = np.pad(
im,
pad_width=(
(
int((max_i - im.shape[0]) / 2),
int((max_i - im.shape[0]) / 2)
+ int((max_i - im.shape[0]) % 2),
),
(
int((max_j - im.shape[1]) / 2),
int((max_j - im.shape[1]) / 2)
+ int((max_j - im.shape[1]) % 2),
),
),
mode="reflect",
)
new_imset.append(im)
return np.array(new_imset)
def rescale_image(im, scale):
"""Scaling factor must be greater than or equal to 1."""
assert scale >= 1, "Scaling factor must be greater than or equal to 1."
# out = np.copy(im)
out = copy.deepcopy(im)
old_shape = out.shape
out = zoom(out, scale, order=0)
new_shape = out.shape
i_0 = int((new_shape[0] - old_shape[0]) / 2)
i_1 = int((new_shape[0] - old_shape[0]) / 2) + old_shape[0] + 1
j_0 = int((new_shape[1] - old_shape[1]) / 2)
j_1 = int((new_shape[1] - old_shape[1]) / 2) + old_shape[1] + 1
out = out[i_0:i_1, j_0:j_1]
return out
def get_src_data(paths, buffers, gauss=None, sec=False, with_right_unit=False):
"""To prepare the different set of images for the user's options.
Purpose is to break up the main function."""
# Get the buffer_set in the form buffer_set -> {buf#1: [img1, img2, ...], buf#2: [img1, img2, ...]}
buffer_set_raw = get_bufset(paths, bufs=buffers, with_right_unit=with_right_unit)
# Get the topographic images for registration, if sec is not None
topos = get_bufset(paths, bufs=[1]) # dict
topos = img_process_set2(topos, gauss=None) # dict
topos = img_post_process_set2(topos, destripe=True, sc=(2, 98))[1] # array
# Hardcoding for one example: 08_24_19 (Movie 16)
# for key in buffer_set_raw:
# i = int(0.4 * buffer_set_raw[key][0].shape[0])
# j = int(0.6 * buffer_set_raw[key][0].shape[1])
# buffer_set_raw[key] = [
# im[i : im.shape[0], 0:j] for im in buffer_set_raw[key]
# ]
# Hardcoding for one example: 09_13_19 (Movie 26)
# All but tip change
# for key in buffer_set_raw:
# buffer_set_raw[key] = np.array(
# [im[15:, :] for im in buffer_set_raw[key]]
# )
# left dot
# for key in buffer_set_raw:
# buffer_set_raw[key] = np.array(
# [im[40:76, 6:50] for im in buffer_set_raw[key]]
# )
# right dot
# for key in buffer_set_raw:
# buffer_set_raw[key] = np.array(
# [im[43:82, 57:] for im in buffer_set_raw[key]]
# )
# topos = np.array([im[40:76, 6:50] for im in topos])
# topos = np.array([im[43:82, 57:] for im in topos])
# Random gold surface (for background)
# for key in buffer_set_raw:
# buffer_set_raw[key] = np.array(
# [im[77:, :] for im in buffer_set_raw[key]]
# )
# topos = np.array([im[77:, :] for im in topos])
# Hardcoding for one example: 10_05_19 (Movie 31)
# for key in buffer_set_raw:
# i = int(0.4 * buffer_set_raw[key][0].shape[0])
# j = int(0.6 * buffer_set_raw[key][0].shape[1])
# buffer_set_raw[key] = [im[i:, :j] for im in buffer_set_raw[key]]
# Hardcoding for one example: 10_06_19 (Movie 32)
# for key in buffer_set_raw:
# i = int(0.3 * buffer_set_raw[key][0].shape[0])
# j = int(0.5 * buffer_set_raw[key][0].shape[1])
# buffer_set_raw[key] = [im[i:, j:] for im in buffer_set_raw[key]]
# Hardcoding for one example: 10_07_19 (Movie 33)
# for key in buffer_set_raw:
# buffer_set_raw[key] = [im[33:88, 10:80] for im in buffer_set_raw[key]]
# topos = np.array([im[33:88, 10:80] for im in topos])
# Hardcoding for one example: 10_08_19 (Movie 34)
# for key in buffer_set_raw:
# i = int(0.5 * buffer_set_raw[key][0].shape[0])
# j = int(0.4 * buffer_set_raw[key][0].shape[1])
# buffer_set_raw[key] = [im[:i, j:] for im in buffer_set_raw[key]]
# Hardcoding for one example: 10_09_19 (Movie 36)
# for key in buffer_set_raw:
# buffer_set_raw[key] = [im[26:75, :83] for im in buffer_set_raw[key]]
# topos = np.array([im[26:75, :83] for im in topos])
# Hardcoding for one example: 10_21_19 (Movie 42, Part 2)
# for key in buffer_set_raw:
# buffer_set_raw[key] = [im[12:, 5:45] for im in buffer_set_raw[key]]
# topos = np.array([im[12:, 5:45] for im in topos])
buffer_set_processed = img_process_set2(buffer_set_raw, gauss=gauss)
# Register the images
if sec:
reg_buffer_set = register_bufferset2(
buffer_set_processed, secondarySet=topos
)
else:
reg_buffer_set = register_bufferset2(buffer_set_processed, filter=True)
return buffer_set_raw, buffer_set_processed, reg_buffer_set, topos
def standardize_data(bufset):
bufset = copy.deepcopy(bufset)
for (key, val) in bufset.items():
# testing
# val = [(img - img.mean()) / img.std() for img in val]
val = np.array(val)
bufset[key] = (val - val.mean()) / val.std()
return bufset
def get_normalized_buffer_set(reg_buffer_set):
"""Put in a sorted registered buffer set to get the normalized set"""
# src = np.copy(reg_buffer_set).item()
src = copy.deepcopy(reg_buffer_set)
out = {}
for key in src:
out[key] = np.array(
[src[key][i] - src[key][0] for i in range(1, len(src[key]))]
)
# out[key] = np.array(
# [
# compare_ssim(src[key][0], src[key][i], full=True)[1]
# for i in range(1, len(src[key]))
# ]
# )
return out
def get_svd(reg_buffer_set, svd_num=10, ds=False):
"""Return an svd dictionary: {buf: [ [svd image set], U, D, V, svd_num ]"""
assert isinstance(svd_num, int), "svd num must be integer"
# src = np.copy(reg_buffer_set).item()
src = copy.deepcopy(reg_buffer_set)
src = img_post_process_set2(src, destripe=ds, sc=None)
src = zoom_buffer_set(src)
for key in src:
svd_arr = np.array(src[key])
U, D, V = np.linalg.svd(svd_arr)
d_rec = (U[:, :, :svd_num] * D[:, None, :svd_num]) @ V[
:, :svd_num, :
] # @ = matrix mult.
weight_perc = [
np.sum(D[i, :svd_num] ** 2) / np.sum(D[i] ** 2)
for i in range(D.shape[0])
]
accu = np.mean(weight_perc)
stdev = np.std(weight_perc)
print(f"Average SVD reconstruction accuracy: {accu}")
print(f"Standard deviation: {stdev}")
src[key] = [d_rec, U, D, V, svd_num]
return src
def get_svd2(reg_buffer_set, svd_num=10, ds=False, wavelet="sym7", level=None):
"""Return an svd dictionary: {buf: [ [svd image set], U, D, V, svd_num ]. get_svd2 differs from get_svd in that it flatten the image stack into a matrix in which a row = an image"""
assert isinstance(svd_num, int), "svd num must be integer"
# src = np.copy(reg_buffer_set).item()
src = copy.deepcopy(reg_buffer_set)
src = img_post_process_set2(
src, destripe=ds, sc=None, wavelet=wavelet, level=level
)
src = zoom_buffer_set(src)
for key in src:
svd_arr = np.array(src[key])
svd_arr_rs = svd_arr.reshape(
(svd_arr.shape[0], svd_arr.shape[1] * svd_arr.shape[2])
)
U, D, V = np.linalg.svd(svd_arr_rs, full_matrices=False)
# d_rec = np.dot(
# U[:, :svd_num], np.dot(np.diag(D[:svd_num]), V[:svd_num, :])
# ) # @ = matrix mult.
# d_rec = U[:, :svd_num] @ np.diag(D[:svd_num]) @ V[:svd_num, :]
d_rec = U[:, 1:svd_num] @ np.diag(D[1:svd_num]) @ V[1:svd_num, :]
# d_rec = U[:, 1:] @ np.diag(D[1:]) @ V[1:, :]
d_rec = d_rec.reshape(
(svd_arr.shape[0], svd_arr.shape[1], svd_arr.shape[2])
)
# weight_perc = np.sum(D[0] ** 2) / np.sum(D ** 2)
# accu = np.mean(weight_perc)
# stdev = np.std(weight_perc)
# print(f"U0 weight: {weight_perc}")
# print(f"Standard deviation: {stdev}")
V = V.reshape((V.shape[0], svd_arr.shape[1], svd_arr.shape[2]))
src[key] = [d_rec, U, D, V, svd_num]
return src
def get_wavelet_svd(
reg_buffer_set, wavelet="sym7", level=None, svdnum=None, mode="symmetric"
):
# assert isinstance(svdnum, int), "svd num must be integer"
src = copy.deepcopy(reg_buffer_set)
src = zoom_buffer_set(src)
for key in src:
svd_arr = np.array(src[key])
svd_arr_rs = svd_arr.reshape(
(svd_arr.shape[0], svd_arr.shape[1] * svd_arr.shape[2])
)
coeffs = pywt.wavedec2(
svd_arr_rs, wavelet=wavelet, level=level, mode=mode
)
approx = coeffs[0]
detail = coeffs[1:]
coeffs_filt = [approx]
for nthlevel in detail:
ch, cv, cd = nthlevel
fcv = fftpack.rfft(cv)
# print(cv.shape)
# print(fcv.shape)
U, D, V = np.linalg.svd(fcv, full_matrices=False)
if svdnum is None:
svdnum = int(0.25 * np.min(fcv.shape))
# fcv_filt = np.dot(
# np.matrix(U[:, svdnum:]),
# np.dot(np.diag(D[svdnum:]), np.matrix(V[svdnum:, :])),
# )
fcv_filt = U[:, svdnum:] @ np.diag(D[svdnum:]) @ V[svdnum:, :]
cv_filt = fftpack.irfft(fcv_filt)
coeffs_filt.append((ch, cv_filt, cd))
svd_arr_filt = pywt.waverec2(coeffs_filt, wavelet=wavelet, mode=mode)
print("past wavelet_svd reconstruction")
svd_arr_filt = np.array(svd_arr_filt)
print(svd_arr_filt.shape)
print(svd_arr.shape)
try:
svd_arr_filt = svd_arr_filt[:-1].reshape(
(svd_arr.shape[0], svd_arr.shape[1], svd_arr.shape[2])
)
except ValueError:
svd_arr_filt = svd_arr_filt.reshape(
(svd_arr.shape[0], svd_arr.shape[1], svd_arr.shape[2])
)
u, d, v = np.linalg.svd(
svd_arr_filt.reshape(
(
svd_arr_filt.shape[0],
svd_arr_filt.shape[1] * svd_arr_filt.shape[2],
)
),
full_matrices=False,
)
v = v.reshape(
(v.shape[0], svd_arr_filt.shape[1], svd_arr_filt.shape[2])
)
print("past 2nd svd")
print("past reshape")
src[key] = [svd_arr_filt, u, d, v, svdnum]
return src
def plot_svd(t, buf, U, D, V, svd_num, normalized=False, fg=None, bg=None):
"""A = UDV^T. All matrices have this property. I used this for my pump-probe analysis"""
# With the function get_svd2, all image pixels are decomposed with time. We have:
# A(time, location) = U(time, time) * D(time, location) * V(location,location)
# U: relates time to "features" (broad term, some kind of concepts)
# V: relates the location to the concepts
# By plotting U column vectors with most weights, we can conceptualize how the "features" change against time.
suffix = ""
if normalized:
suffix += "_normalized"
if fg is not None:
suffix += "_fg"
elif bg is not None:
suffix += "_bg"
fig, ax = plt.subplots()
for i in range(svd_num):
ax.cla()
# ax.minorticks_on()
ax.plot(t, U[:, i])
ax.set_xscale("symlog")
ax.set_xlabel("Time, ps")
# ax.set_xlabel("Bias voltage")
ax.set_ylabel(f"U{i}")
xlog_tic = mtick.LogLocator(base=10, subs=(0.2, 0.4, 0.6, 0.8))
ax.xaxis.set_minor_locator(xlog_tic)
ax.xaxis.set_minor_formatter(mtick.NullFormatter())
print(f"Weight of U{i}: {D[i]**2 / np.sum(D**2)}")
fig.savefig(
f"U{i}_buf{buf}{suffix}_vs_time.eps",
bbox_inches="tight",
# pil_kwargs={"compression": "tiff_deflate"},
)
plt.close(fig)
# Spatial components: V
V_towrite = np.array(V)
V_towrite = np.clip(
V_towrite, np.percentile(V_towrite, 1), np.percentile(V_towrite, 99)
)
V_towrite = normalize_img(V_towrite, 0, 2 ** 8 - 1).astype("uint8")
textlist = [""]
textlist.extend(
[
f"Weight: {(1e6 * val):.1f} ppm"
for val in (D ** 2 / np.sum(D ** 2))
][1:]
)
V_towrite = annotate_imset(V_towrite, textlist)
imageio.mimwrite(f"V_buf{buf}{suffix}_vs_time.mov", V_towrite, fps=2)
# Movie of each component, up to svd_num
V_reshaped = V.reshape((V.shape[0], V.shape[1] * V.shape[2]))
print(V_reshaped.shape)
for i in range(svd_num):
component = (
D[i] * np.atleast_2d(U[:, i]).T @ np.atleast_2d(V_reshaped[i, :])
)
component = component.reshape((V.shape[0], V.shape[1], V.shape[2]))
component = np.clip(
component,
np.percentile(component, 1),
np.percentile(component, 99),
)
component = normalize_img(component, 0, 2 ** 8 - 1).astype("uint8")
component = annotate_imset(component, [f"{val} ps" for val in t])
imageio.mimwrite(
f"Component_{i}_buf{buf}_{suffix}.mov", component, fps=2
)
def save_movie_with_matplotlib(
reg_buf, num_fn, normalize=False, svd=False, cmap="gray_r"
):
reg_buf_cp = copy.deepcopy(reg_buf)
suffix = ""
if svd:
suffix += "_svd"
if normalize:
suffix += "_normalized"
for key in reg_buf_cp:
# clim = [np.percentile(reg_buf_cp[key], 2), np.percentile(reg_buf_cp[key], 98)]
clim = [np.min(reg_buf_cp[key]), np.max(reg_buf_cp[key])]
fig, ax = plt.subplots()
fig.tight_layout()
# ax.set_axis_off()
frame_list = []
savename = f"./Movie_buf{key}{suffix}.mov"
for frame in reg_buf_cp[key]:
ax.cla()
ax.axis("off")
im = ax.imshow(frame, cmap=cmap)
im.set_clim(clim)
fig.savefig(
"./temp.eps",
bbox_inches="tight",
pad_inches=0,
# pil_kwargs={"compression": "tiff_lzw"},
)
frame_list.append(imageio.imread("./temp.eps"))
imageio.mimwrite(savename, frame_list, fps=2)
remove("./temp.eps")
plt.close(fig)
def save_movie_and_frame(reg_buf, num_fn, normalize=False, svd=False):
# reg_buf_cp = np.copy(reg_buf).item()
reg_buf_cp = copy.deepcopy(reg_buf)
reg_buf_cp = {
key: normalize_img(val, 0, 2 ** 8 - 1).astype("uint8")
for (key, val) in reg_buf_cp.items()
}
suffix = ""
if svd:
suffix += "_svd"
if normalize:
suffix += "_normalized"
for key in reg_buf_cp:
# write the movies
savename = f"./Movie_buf{key}{suffix}.mov"
imageio.mimwrite(savename, reg_buf_cp[key], fps=2)
# write the frames: Very messy, enable when needed
# [
# imageio.imwrite(
# f"./frame_buf{key}_{num_fn[i]}{suffix}.tiff",
# reg_buf[key][i],
# format="TIFF-FI",
# )
# for i in range(len(reg_buf_cp[key]))
# ]
def get_inputs_and_filenames_from_logfile(logfile, frames):
info = []
for line in reversed(list(open(logfile, "r"))):
info.append(line.rstrip())
inputs = [inf.split(",")[0].strip() for inf in info[:frames]]
inputs = list(reversed(inputs))
fn = [inf.split(",")[1].strip() for inf in info[:frames]]
fn = list(reversed(fn))
return inputs, fn
def create_movies(reg_buffer_set, args, fg=None, bg=None):
"""Create movies out of the registered src data (that hasn't been altered to image form."""
paths = args.input
buffers = args.buffers
logfile = args.logfile
frames = args.frames
register = args.register
cmap = args.colormap
ds = args.destripe
gauss = args.gauss
lockin = args.lockin
movie = args.movie
sc = args.stretch_contrast
fn = args.filenames
textcolor = args.textcolor
normalize = args.normalize
sec = args.secondarySet
svd_num = args.svd