-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbeatprofiler.py
More file actions
2320 lines (1997 loc) · 120 KB
/
beatprofiler.py
File metadata and controls
2320 lines (1997 loc) · 120 KB
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
# Last updated in 02/14/2024 by Youngbin Kim
import sys
import matplotlib
matplotlib.use('Agg') # Use a non-GUI backend to prevent GUI-related issues like segmentation faults
import matplotlib.pyplot as plt
import scipy as sp
from scipy import signal
import pandas as pd
import numpy as np
# scikit-video uses deprecated np variables
np.float = np.float64
np.int = np.int_
import glob
import os
import warnings
import bisect
from sklearn.preprocessing import minmax_scale
from sklearn.mixture import GaussianMixture
import yaml
import cv2
from matplotlib.patches import Rectangle
class Video():
'''
A class used to read videos and extract traces
Attributes
-----------
file_path : str
Path of the file or pycromanager folder
frame_rate : float
frame rate of video. optional if acq_mode is pycromanager or filetype is nd2
max_bpm : int
max beat rate for the cardiomyocytes. Used in calculate_mask if the method is fundamental. Also used in calculate_reference_frame for BFVideo to calculate minimum peak distance.
acq_mode : str
Must specify as 'pycromanager' for Pycromanager acquired tif stacks
otherwise, it should be None
name : str
Name of the video
mask : np.array
A boolean mask if you need to process a specifc ROI. Filled with True by default
shape is W x H
Methods
-------
calculate_mask() : np.array
2D boolean array of area that contain beating pixels W x H
'''
def __init__(self, file_path, frame_rate=None, max_bpm=360, acq_mode = None, low_ram=True, chunk_sec=5, name=None):
'''
Read the video and extracts/saves the frame rate
'''
self.name = name
self.max_bpm = max_bpm
self.trace = None
self.file_ext = os.path.splitext(file_path)[-1]
self.frame_rate = frame_rate
self.acq_mode = acq_mode
self.file_path = file_path
self.n_frames = 0
self.low_ram = low_ram
self.chunk_size = int(chunk_sec * self.frame_rate) # 5 second chunks for memory efficiency
if not self.file_ext and not self.acq_mode:
# folder was selected and acquisition type is not pycromanager
raise Exception("You must select a file rather than a folder if acq_mode is not pycromanager")
if self.acq_mode == 'pycromanager':
# pycromanager requires file_path to be the parent folder containing 'Full Resolution' folder
import tifffile
# if video is more than 4gb, pycromanager automatically splits it into multiple files
self.img_paths = np.array(glob.glob(os.path.join(self.file_path, "**/*.tif"), recursive=True))
self.img_paths = np.sort(self.img_paths)
#get n frames
length = 0
lengths = []
for file_path in self.img_paths:
with tifffile.TiffFile(file_path) as tif:
cur_length = len(tif.pages)
lengths.append(cur_length)
length += cur_length
self.n_frames = length
self.first_frame = tifffile.imread(self.img_paths[0], key=0)
# frame by frame reader used for low ram or tissue videos
def video_reader():
for file_path in self.img_paths:
with tifffile.TiffFile(file_path) as tif:
for frame in tif.pages:
yield frame.asarray()
self.video_reader = video_reader
if not self.low_ram and not isinstance(self, TissueVideo):
self.raw_video = tifffile.imread(self.img_paths[0])
for i in range(1, len(self.img_paths)):
self.raw_video = np.concatenate([self.raw_video, tifffile.imread(self.img_paths[i])])
# extract frame rate if not specified
if not self.frame_rate:
from pycromanager import Dataset
# extract metadata using pycromanager class
# because raw data handling is super slow we load the whole thing to RAM by calling np.asarray() (good for computational speed)
# while pycromanager loads into dask format, which loads each frame as needed (good for low RAM)
dataset = Dataset(self.file_path)
self.frame_rate = float(dataset.read_metadata(time=0)['Andor sCMOS Camera-FrameRate'])
elif self.file_ext == '.nd2':
from nd2reader import ND2Reader
nd2vid = ND2Reader(self.file_path)
self.n_frames = len(nd2vid)
self.first_frame = np.array(ND2Reader(self.file_path)[0])
# extract frame rate if not specified
if not self.frame_rate:
self.frame_rate = nd2vid.frame_rate
# frame by frame reader used for low ram or tissue videos
def video_reader():
n = 0
while n < self.n_frames:
yield nd2vid[n]
n +=1
self.video_reader = video_reader
if not self.low_ram and not isinstance(self, TissueVideo):
self.raw_video = np.array(nd2vid)
elif self.file_ext == '.tif':
import tifffile
with tifffile.TiffFile(self.file_path) as tif:
self.n_frames = len(tif.pages)
self.first_frame = tifffile.imread(self.file_path, key=0)
if self.first_frame.ndim > 2:
self.first_frame = self.first_frame.mean(axis=-1)
self.frame_rate = frame_rate
# frame by frame reader used for low ram or tissue videos
def video_reader():
with tifffile.TiffFile(self.file_path) as tif:
for frame in tif.pages:
frame_mono = frame.asarray()
if frame_mono.ndim > 2:
frame_mono = frame_mono.mean(axis=-1)
yield frame_mono
self.video_reader = video_reader
if not self.low_ram and not isinstance(self, TissueVideo):
self.raw_video = tifffile.imread(self.file_path)
if self.raw_video.ndim > 3:
self.raw_video = self.raw_video.mean(axis=-1)
else: # mp4, avi, etc. use skvideo to import
## need to set FFMPEG path for GUI version
import skvideo
if hasattr(sys, '_MEIPASS'):
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
skvideo.setFFmpegPath(os.path.join(base_path, "ffmpeg"))
import skvideo.io
ffmpegreader = skvideo.io.FFmpegReader(self.file_path)
self.n_frames = ffmpegreader.getShape()[0]
self.first_frame = skvideo.io.vread(self.file_path, num_frames=1).squeeze().mean(axis=-1)
self.frame_rate = frame_rate
# frame by frame reader used for low ram or tissue videos
# make video black and white
def video_reader():
ffmpegreader = skvideo.io.FFmpegReader(self.file_path)
generator = ffmpegreader.nextFrame()
for frame in generator:
yield frame.mean(axis=-1)
self.video_reader = video_reader
if not self.low_ram and not isinstance(self, TissueVideo):
self.raw_video = skvideo.io.vread(self.file_path).mean(axis=-1)
self.mask = np.full(self.first_frame.shape, True)
def __len__(self):
return self.n_frames
def calculate_mask(self, method=None, mask_file=None, invert=False, savefig=False, savefig_path=None, yolo_seg_model=None):
'''
Calculates and saves self.mask
Parameters
----------
method : str
Method used to calculate the mask
None uses all pixels.
'mean fft' is recommended for most fluorescent videos.
'dynamic range' is recommended for most brightfield videos and is best for speed.
'YOLOv8 segmentation' uses a deep learning model to automatically segment a mask for brightfield videos.
You may need to empirically find which method works best for your videos."
mask_file : str or None
path of the mask file if you want to use an existing mask file
invert : bool
mask detection is incorrectly inverted sometimes. to invert the mask, chagne this to True.
savefig : bool
boolean indicating whether mask should be exported to a file
savefig_path : str or None
file path of the mask image that will be exported if savefig is True
Returns
-------
self.mask : np.array
shape is W x H
'''
if not method:
return self.mask
if mask_file:
mask_img = plt.imread(mask_file)
if len(mask_img.shape()) > 2:
mask_img = mask_img.mean(axis=-1)
self.mask = mask_img.astype(bool)
return self.mask
if method not in ["dynamic range", "max fft", "mean fft", "fundamental", "YOLOv8 segmentation"]:
raise Exception("Invalid filter method. Must be one of 'dynamic range', 'max fft', 'mean fft', 'fundamental', or 'YOLOv8 segmentation'.")
# helper function used in low ram settings to process videos in chunks
def chunk_agg(fn, agg_fn, chunk_size):
i=0
agg_data = None
video_reader = self.video_reader()
if chunk_size > len(self):
video_chunk = np.zeros((len(self), *self.first_frame.shape))
for n in range(len(self)):
video_chunk[n] = next(video_reader)
agg_data = fn(video_chunk)
while i < len(self) and i+chunk_size <= len(self):
video_chunk = np.zeros((chunk_size, *self.first_frame.shape))
for n in range(chunk_size):
video_chunk[n] = next(video_reader)
test = fn(video_chunk)
if agg_data is None:
agg_data = fn(video_chunk)
else:
agg_data = agg_fn(agg_data, fn(video_chunk))
i += chunk_size
return agg_data
if method == "YOLOv8 segmentation":
from ultralytics import YOLO
mask_model = YOLO(yolo_seg_model)
# increase contrast on image before predicting to improve results
p2, p98 = np.percentile(self.first_frame, (2, 98))
img_clipped = np.clip(self.first_frame, p2, p98)
img_scaled = minmax_scale(img_clipped, feature_range=(0, 255))
frame = np.stack((img_scaled,)*3, axis=-1)
results = mask_model.predict(source=frame)
mask = cv2.resize(np.sum(results[0].masks.data.cpu().numpy(), axis=0), results[0].orig_shape[::-1])
self.mask = cv2.threshold(mask, thresh=0.5, maxval=1, type=cv2.THRESH_BINARY)[1]
elif method == "dynamic range":
# high dynamic range is more likely from active regions
if self.low_ram:
min_pix = chunk_agg(lambda x: np.min(x, axis=0), lambda x,y: np.min([x,y], axis=0), self.chunk_size)
max_pix = chunk_agg(lambda x: np.max(x, axis=0), lambda x,y: np.max([x,y], axis=0), self.chunk_size)
fullrange = max_pix - min_pix
else:
fullrange = np.max(self.raw_video,axis=0) - np.min(self.raw_video,axis=0)
gmm3 = GaussianMixture(n_components=2).fit(fullrange.reshape(-1,1))
labels3 = gmm3.predict(fullrange.reshape(-1,1)).reshape(self.first_frame.shape)
signal_group = np.argmax(gmm3.means_)
self.mask = labels3 == signal_group
elif method == "max fft":
# filter #1 is based on max fft amplitude
# the distribution is bimodal with the signal being the gaussian with the higher center
# noise tends to have lower max fft amplitude (but not always, which is why we have the invert option)
# sometimes this filter doesnt work too well if video is noisy (they are sometimes inverted or there are multiple peaks)
if self.low_ram:
sum_fft = chunk_agg(lambda x: np.abs(np.fft.fft(x, axis=0)), lambda x,y: np.sum([x,y],axis=0), self.chunk_size)
max_fft = np.max(sum_fft[1:,:,:], axis=0)
else:
max_fft = np.max(np.abs(np.fft.fft(np.array(self.raw_video), axis=0)[1:,:,:]), axis=0)
gmm = GaussianMixture(n_components=2).fit(max_fft.reshape(-1,1))
labels = gmm.predict(max_fft.reshape(-1,1)).reshape(self.first_frame.shape)
signal_group = np.argmax(gmm.means_)
self.mask = labels == signal_group
elif method == "mean fft":
# filter 1a is based on mean fft amplitude
if self.low_ram:
sum_fft = chunk_agg(lambda x: np.abs(np.fft.fft(x, axis=0)), lambda x,y: np.sum([x,y],axis=0), self.chunk_size)
mean_fft = np.mean(sum_fft, axis=0)
else:
mean_fft = np.mean(np.abs(np.fft.fft(np.array(self.raw_video), axis=0)), axis=0)
gmm1a = GaussianMixture(n_components=2).fit(mean_fft.reshape(-1,1))
labels1a = gmm1a.predict(mean_fft.reshape(-1,1)).reshape(self.first_frame.shape)
signal_group = np.argmax(gmm1a.means_)
self.mask = labels1a == signal_group
elif method == "fundamental":
# filter #2 is based on fundamental frequency of each pixel
# it filters wihtin the physiological range only (less than 360bpm)
# subtract average value by removing fft[0,:,:]. had to add back 1 because we truncated the array
if self.low_ram:
fft = chunk_agg(lambda x: np.abs(np.fft.fft(x, axis=0)), lambda x,y: np.sum([x,y],axis=0), self.chunk_size)
argmax_fft = np.argmax(sum_fft[1:,:,:], axis=0)+1
else:
fft = np.fft.fft(np.array(self.raw_video), axis=0)
argmax_fft = np.argmax(np.abs(fft[1:,:,:]), axis=0)+1
# not the best for noisy data
min_rr_frame = (self.max_bpm / 60) * len(fft) / self.frame_rate # for example, 250bpm is 4.17 Hz which is 240ms between beats. this * fps = min # frames between beats
labels2 = (argmax_fft < min_rr_frame) | (argmax_fft > np.max(fft)-min_rr_frame)
self.mask = labels2
# flip mask if invert
if invert:
self.mask = np.logical_not(self.mask)
# export mask if specified
if savefig is True:
self.save_mask(savefig_path)
self.area = self.mask.sum()
return self.mask
def save_mask(self, savefig_path):
assert savefig_path is not None, "savefig_path cannot be None if savefig is True"
os.makedirs(savefig_path, exist_ok=True)
plt.imsave(fname=os.path.join(savefig_path, self.name.replace("\\", "-")+" mask.png"),
arr=self.mask,
cmap="gray")
def downsample(arr, new_shape):
# crops a part of image if simple downsampling ratio is off
d_shape = [arr.shape[1] // new_shape[0], arr.shape[2] // new_shape[1]]
shape = (arr.shape[0],
new_shape[0], d_shape[0],
new_shape[1], d_shape[1])
return arr[:,:d_shape[0]*new_shape[0], :d_shape[1]*new_shape[1]].reshape(shape).mean(4).mean(2)
class BFVideo(Video):
'''
Child class of Video dedicated for brightfield videos
Read comments in Video to learn about inherited attributes and methods
Attributes
----------
reference_frame : np.array
Brightfield videos require a reference frame to subtract from to look at pixels that are deviating
frame shape is W x H
trace : np.array
trace from video calculated by averaging the
Methods
-------
calculate_trace(str reference) : np.array
calculates the reference frame by averaging frames of relaxed states
calculate_trace(str reference) : np.array
calculates average change in pixel intensity over time
using a reference frame as defined in initialization and updates self.trace
'''
def __init__(self, file_path, frame_rate=None, max_bpm=360, acq_mode = None, low_ram=True, chunk_sec=5, name=None):
super().__init__(file_path=file_path, frame_rate=frame_rate, max_bpm=360, acq_mode=acq_mode, low_ram=low_ram, chunk_sec=chunk_sec, name=name)
self.reference_frame = None
def calculate_reference_frame(self, prominence=0.5, rel_height=0.05):
'''
Calculates reference frame
1. analyze video with mean of first chunk as temp reference frame and identify peaks (most contracted state) - contractile peaks are pretty robust between different reference frame choices
2. Using the average of peaks as reference, find the inverted trace. Then find peaks to identify the relaxed states
3. select frames around the new peaks of the inverted trace according to the rel_height tolerance, and avg them as reference frame
Parameters
----------
prominence : float
Used to find peaks that have prominence greater than this value
rel_height : float
threshold to use when selecting frames for reference. Default is 0.05 meaning any points within 5% of the peak prominence is considered to be valleys (relaxed states) and averaged to find the reference frame
Returns
-------
self.reference_frame : np.array
shape is W x H
'''
### Step 1
n_frames = min(len(self), self.chunk_size)
if self.low_ram:
video_reader = self.video_reader()
temp_reference_frame = np.zeros_like(self.first_frame, dtype=float)
for _ in range(n_frames):
frame = next(video_reader) * self.mask
temp_reference_frame += frame / n_frames
video_reader = self.video_reader()
temp_trace = np.zeros(len(self))
for i in range(len(self)):
temp_trace[i] = np.mean(np.abs(next(video_reader)*self.mask - temp_reference_frame))
temp_trace = minmax_scale(temp_trace)
else:
masked_video = self.raw_video * self.mask
temp_reference_frame = np.mean(masked_video[:n_frames], axis=0)
temp_trace = minmax_scale(np.mean(np.abs(masked_video - temp_reference_frame), axis=(1,2)))
min_RR_index = 1 /(self.max_bpm / 60) * self.frame_rate
peaks, properties = sp.signal.find_peaks(temp_trace, distance = max(2,min_RR_index), prominence=prominence, width=0, rel_height =1)
### Step 2
# if no peaks use mean as reference
if len(peaks) == 0:
if self.low_ram:
video_reader = self.video_reader()
self.reference_frame = np.zeros_like(self.first_frame, dtype=float)
for _ in range(len(self)):
frame = next(video_reader) * self.mask
self.reference_frame += frame / n_frames
return self.reference_frame
else:
self.reference_frame = np.mean(self.raw_video, axis=0) * self.mask
return self.reference_frame
# otherwise, use the peaks as temp_reference 2
if self.low_ram:
video_reader = self.video_reader()
temp_reference_frame_2 = np.zeros_like(self.first_frame, dtype=float)
for i in range(len(self)):
if i in peaks:
temp_reference_frame_2 += next(video_reader) * self.mask / len(peaks)
else:
next(video_reader)
video_reader = self.video_reader()
temp_trace_2 = np.zeros(len(self))
for i in range(len(self)):
temp_trace_2[i] = np.mean(np.abs(next(video_reader)*self.mask - temp_reference_frame_2))
temp_trace_2 = minmax_scale(temp_trace_2)
else:
temp_reference_frame_2 = np.mean(masked_video[peaks],axis=0)
temp_trace_2 = minmax_scale(np.mean(np.abs(masked_video - temp_reference_frame_2), axis=(1,2)))
### Step 3
valleys, valley_properties = sp.signal.find_peaks(temp_trace_2, distance = max(2,min_RR_index), prominence=min(prominence, 0.3), width=0, rel_height=rel_height)
reference_indices = np.array([])
for i in range(len(valleys)):
left_i, right_i = np.ceil(valley_properties['left_ips'][i]).astype(int), np.floor(valley_properties['right_ips'][i]).astype(int)
reference_indices = np.append(reference_indices, range(left_i, right_i+1))
# get rid of negative indices and drop duplicates
# make into integer type
reference_indices = np.unique(reference_indices[reference_indices > 0]).astype(int)
if self.low_ram:
video_reader = self.video_reader()
self.reference_frame = np.zeros_like(self.first_frame, dtype=float)
for i in range(len(self)):
if i in reference_indices:
self.reference_frame += next(video_reader) * self.mask / len(reference_indices)
else:
next(video_reader)
else:
self.reference_frame = np.mean(masked_video[reference_indices], axis=0)
## edge case for when there are no valleys found: revert to mean calculation
if np.isnan(self.reference_frame).sum() > 0:
if self.low_ram:
video_reader = self.video_reader()
self.reference_frame = np.zeros_like(self.first_frame, dtype=float)
for _ in range(len(self)):
self.reference_frame = next(video_reader) * self.mask / len(self)
else:
self.reference_frame = np.mean(self.raw_video, axis=0)
# # for debugging
# print(self.name)
# plt.plot(temp_trace)
# plt.scatter(peaks, temp_trace[peaks], label="peaks")
# plt.scatter(valleys, temp_trace[valleys], label="valleys")
# plt.scatter(reference_indices, temp_trace[reference_indices], label="reference_frames")
# plt.legend()
# plt.show()
# plt.plot(temp_trace_2)
# plt.scatter(peaks, temp_trace_2[peaks], label="peaks")
# plt.scatter(valleys, temp_trace_2[valleys], label="valleys")
# plt.scatter(reference_indices, temp_trace_2[reference_indices], label="reference_frames")
# plt.legend()
# plt.show()
return self.reference_frame
def calculate_trace(self, reference = "auto", ref_frame_range = [0,20], reference_frame=None, grid=False):
'''
Calculates pixel intensity changes using a user defined reference baseline frame
Parameters
----------
reference : str
Method for selecting baseline frame.
'mean' averages all frames in the video and uses that as baseline frame
'range' averages defined range of frames and uses that as baseline frame. The frame index range is defined in parameter 'frames'
'auto' automatic calculation of reference frame. See calculate_reference_frame for more description
'manual' manual input of reference frame
ref_frame_range : list
Only required if reference is 'range'. Frame range to calculate the baseline frame. The cardiomyocytes should be relaxed in this range.
ref_frames should be 2 element integer list
reference_frame : np.array or None
only used when reference is 'manual'
grid : tuple or None
if you want to analyze each grid independently (e.g. downsampling or binning), you can input the shape of the output array here
tuple must be 2 element integers smaller than video dimensions
Return
------
self.trace : np.array
Calculated cardiac contractility trace based on pixel intensity changes
'''
if reference == "auto":
self.calculate_reference_frame()
elif reference == "mean":
if self.low_ram:
video_reader = self.video_reader()
self.reference_frame = np.zeros_like(self.first_frame, dtype=float)
for _ in range(len(self)):
self.reference_frame = next(video_reader) * self.mask / len(self)
else:
self.reference_frame = np.mean(self.raw_video, axis=0)
elif reference == "range":
if self.low_ram:
video_reader = self.video_reader()
self.reference_frame = np.zeros_like(self.first_frame, dtype=float)
for i in range(0,ref_frame_range[1]):
if i >= ref_frame_range[0]:
self.reference_frame = next(video_reader) * self.mask / (ref_frame_range[1]-ref_frame_range[0])
else:
next(video_reader)
else:
self.reference_frame = np.mean(self.raw_video[ref_frame_range[0]:ref_frame_range[1]], axis=0)
elif reference == "manual":
self.reference_frame = reference_frame
else:
raise Exception("Reference type must be 'mean' or 'range'")
fraction_masked = np.sum(self.mask) / self.mask.size
if self.low_ram:
video_reader = self.video_reader()
self.trace = np.zeros(len(self))
for i in range(len(self)):
self.trace[i] = np.mean(np.abs(next(video_reader) - self.reference_frame) * self.mask) / fraction_masked
else:
self.trace = np.mean(np.abs((self.raw_video - self.reference_frame) * self.mask), axis=(1,2)) / fraction_masked
# if grid:
# self.grid_trace = super().downsample(np.abs(self.raw_video - self.reference_frame), grid)
# return self.grid_trace
return self.trace
class FluoVideo(Video):
'''
Child class of Video dedicated for fluorescent videos
Read comments in Video to learn about inherited attributes and methods
Methods
-------
calculate_trace() : np.array
calculates average pixel intensity over time and updates self.trace
shape is F
calculate_mask() : np.array
calculates average pixel intensity over time and updates self.trace
shape is W x H
'''
def __init__(self, file_path, frame_rate=None, max_bpm=360, acq_mode = None, low_ram=True, chunk_sec=5, name=None):
super().__init__(file_path=file_path, frame_rate=frame_rate, max_bpm=360, acq_mode=acq_mode, low_ram=low_ram, chunk_sec=chunk_sec, name=name)
def calculate_trace(self, grid=False):
'''
Calculates average pixel intensity over time
Parameters
----------
use_mask : bool
boolean indicating whether mask/region of interest should be used to calculate the trace
grid : tuple or None
if you want to analyze each grid independently (e.g. downsampling or binning), you can input the shape of the output array here
tuple must be 2 element integers smaller than video dimensions
Return
------
self.trace : np.array
Calculated cardiac contractility trace based on pixel intensity changes
'''
fraction_masked = np.sum(self.mask) / self.mask.size
if self.low_ram:
video_reader = self.video_reader()
self.trace = np.zeros(len(self))
for i in range(len(self)):
self.trace[i] = np.mean(next(video_reader) * self.mask) / fraction_masked
else:
self.trace = np.mean(self.raw_video * self.mask, axis=(1,2)) / fraction_masked
# if grid:
# if use_mask:
# # downsample the mask to rescale the trace properly
# mask_scaler = super().downsample(np.reshape(self.mask, [1,*self.mask.shape]), grid).reshape(grid)
# self.grid_trace = super().downsample(masked, grid) / mask_scaler
# else:
# self.grid_trace = super().downsample(masked, grid)
# return self.grid_trace
return self.trace
class TissueVideo(Video):
'''
Child class of Video dedicated for tissue videos to extract force and displacement
Read comments in Video to learn about inherited attributes and methods
Attributes
----------
reference_frame : np.array
Brightfield videos require a reference frame to subtract from to look at pixels that are deviating
frame shape is W x H
trace : np.array
trace from video calculated by averaging the
Methods
-------
calculate_trace(str reference) : np.array
calculates the reference frame by averaging frames of relaxed states
calculate_trace(str reference) : np.array
calculates average change in pixel intensity over time
using a reference frame as defined in initialization and updates self.trace
'''
def __init__(self, file_path, frame_rate=None, max_bpm=360, acq_mode = None, low_ram=True, name=None):
# always low_ram for tissue videos because speed is equivalent
super().__init__(file_path=file_path, frame_rate=frame_rate, max_bpm=360, acq_mode=acq_mode, low_ram=True, name=name)
self.center = np.zeros((len(self), 2, 2),dtype=np.float32) # opencv requires float32
self.bbox = None
self.width_coord = None
self.width = None
self.area = None
self.resting_dist = None
def autodetect_pillars(self, yolo_model, frame_i=0):
'''
Calculates reference frame
1. analyze video with mean as temp reference frame and identify peaks (most contracted state) - contractile peaks are pretty robust between different reference frame choices
2. Using the average of peaks as reference, find the inverted trace. Then find peaks to identify the relaxed states
3. select frames around the new peaks of the inverted trace according to the rel_height tolerance, and avg them as reference frame
Parameters
----------
prominence : float
Used to find peaks that have prominence greater than this value
rel_height : float
threshold to use when selecting frames for reference. Default is 0.05 meaning any points within 5% of the peak prominence is considered to be valleys (relaxed states) and averaged to find the reference frame
Returns
-------
self.reference_frame : np.array
shape is W x H
'''
# 1. use yolo for first frame to get center and bounding box
self.bbox = np.zeros((2, 4))
# increase contrast on image before predicting to improve results
p2, p98 = np.percentile(self.first_frame, (2, 98))
img_clipped = np.clip(self.first_frame, p2, p98)
img_scaled = minmax_scale(img_clipped, feature_range=(0, 255))
frame = np.stack((img_scaled,)*3, axis=-1)
results = yolo_model.predict(source=frame)
# to do if 0 or 1 boxes are detected
if len(results[0].boxes.xyxy) < 2:
raise Exception("Less the 2 pillars are detected.")
# opencv xywh format is different from yolo. opencv xy is top left, but yolo xy is center
# self.bbox is in (x1,y1,x2,y2) format where x1, y1 is the coord for the TOP LEFT (NOT center) and x2, y2 is the coord for the bottom right
if results[0].boxes.xywh[0,0] > results[0].boxes.xywh[1,0]:
self.center[0, 0] = results[0].boxes.xywh[1, :2].cpu()
self.center[0, 1] = results[0].boxes.xywh[0, :2].cpu()
self.bbox[0] = results[0].boxes.xyxy[1].cpu()
self.bbox[1] = results[0].boxes.xyxy[0].cpu()
else:
self.center[0, 0] = results[0].boxes.xywh[0, :2].cpu()
self.center[0, 1] = results[0].boxes.xywh[1, :2].cpu()
self.bbox[0] = results[0].boxes.xyxy[0].cpu()
self.bbox[1] = results[0].boxes.xyxy[1].cpu()
return self.bbox
def autodetect_points2track(self, n=9):
assert (self.bbox is not None), "self.bbox must be defined"
assert self.bbox.shape == (2,4), "self.bbox must have a shape of (2,4)"
# 2. find good features in each pillar head to track using ShiTomasi method
# increase contrast on image before predicting to improve results
p2, p98 = np.percentile(self.first_frame, (2, 98))
img_clipped = np.clip(self.first_frame, p2, p98)
frame_mono = minmax_scale(img_clipped, feature_range=(0, 255)).astype(np.uint8)
# define masks for each pillar head
mask1 = np.zeros_like(frame_mono)
x1, x2, y1, y2 = np.array([self.bbox[0,0], self.bbox[0,2], self.bbox[0,1], self.bbox[0,3]]).astype(int)
mask1[y1:y2,x1:x2] = 255
mask2 = np.zeros_like(frame_mono)
x1, x2, y1, y2 = np.array([self.bbox[1,0], self.bbox[1,2], self.bbox[1,1], self.bbox[1,3]]).astype(int)
mask2[y1:y2,x1:x2] = 255
# find points to track within mask (pillar head bounding box)
self.points1 = cv2.goodFeaturesToTrack(frame_mono, maxCorners=n, qualityLevel=0.1, minDistance=10, blockSize=5, mask=mask1).reshape(-1,2)
self.points2 = cv2.goodFeaturesToTrack(frame_mono, maxCorners=n, qualityLevel=0.1, minDistance=10, blockSize=5, mask=mask2).reshape(-1,2)
# find offset for each point
self.offset1 = self.points1 - self.center[0, 0]
self.offset2 = self.points2 - self.center[0, 1]
return self.points1, self.points2
def grid_points2track(self, n=9):
assert (self.bbox is not None), "self.bbox must be defined"
assert self.bbox.shape == (2,4), "self.bbox must have a shape of (2,4)"
sqrt_n = int(np.sqrt(n))
spacing1 = ((self.bbox[0,2:] - self.bbox[0,:2])/(sqrt_n+1)).astype(int)
spacing2 = ((self.bbox[1,2:] - self.bbox[1,:2])/(sqrt_n+1)).astype(int)
# Create an array of x and y coordinates for a nxn grid
x = np.linspace(1, sqrt_n, sqrt_n)
y = np.linspace(1, sqrt_n, sqrt_n)
X, Y = np.meshgrid(x, y)
self.points1 = np.vstack([X.ravel(), Y.ravel()]).T * spacing1 + self.bbox[0,:2]
self.points2 = np.vstack([X.ravel(), Y.ravel()]).T * spacing2 + self.bbox[1,:2]
# find offset for each point
self.offset1 = self.points1 - self.center[0, 0]
self.offset2 = self.points2 - self.center[0, 1]
return self.points1, self.points2
def calculate_trace(self, bounding_box, anchor_method="auto", n=25, window_size=30, savevid=False, savevid_path=None):
'''
Calculates pixel intensity changes using a user defined reference baseline frame
Parameters
----------
method : str
Method for tracking movement of defined area or points
'optical flow' : fast and accurate method for tracking points using Lucas Kanade sparse optical flow method in opencv
'corr tracker' : slower but accurate method for tracking bounding box using dlib's correlation tracker (variant of MOSSE)
bounding_box : str or np.array
Method for selecting anchor points to track.
'pt_file_path' uses YOLOv8 model to detect anchor bounding box
'csv_file_path' first column should be the same name as self.name. Format is (x1,y1,w1,h1,x2,y2,w2,h2)
np.array with shape 2x4 uses pixel coordinates to define bounding boxes. Format is (x1,y1,w,h) for each box
anchor_method : str
Method for selecting anchor points to track.
'auto' uses ShiTomasi method in opencv to identify n best points to track for each bounding box
'grid' calculates coordinates for n points in a grid fashion (sqrt_n x sqrt_n) around the center of the bounding box. if n is not a perfect square, it rounds down to the nearest one
None is used when method doesnt need anchor points to track (dlib correlation tracker method)
n: int
number of points for each anchor to use to track
Return
------
self.trace : np.array
Calculated cardiac contractility trace based on pixel intensity changes
'''
# define bounding box to track distance between
if type(bounding_box) == np.array:
# bounding box is in xywh format. xy indicates top left.
assert(bounding_box.shape == (2,4)), "Shape of bounding box array must be (2,4)."
self.bbox = bounding_box
self.center[0] = self.bbox[:,:2] + self.bbox[:,2:] / 2
self.bbox[:,2:] += self.bbox[:,:2]
elif bounding_box[-3:] == ".pt":
from ultralytics import YOLO
model = YOLO(bounding_box)
self.autodetect_pillars(model, frame_i=0)
elif bounding_box[-4:] == ".csv":
# bounding box csv is in xywh format. xy indicates top left.
self.bbox = pd.read_csv(bounding_box, index_col=0, dtype={0: str}).loc[self.name].to_numpy().reshape(2,4)
self.center[0] = self.bbox[:,:2] + self.bbox[:,2:] / 2
self.bbox[:,2:] += self.bbox[:,:2]
else:
raise Exception("bounding_box must be a YOLOv8 .pt model, a bounding box .csv file, or (2,4) numpy array.")
if anchor_method == "auto":
self.autodetect_points2track(n=n)
elif anchor_method == "grid":
self.grid_points2track(n=n)
else:
raise Exception("Invalid 'anchor_method'. Must be either 'auto' or 'grid'.")
# create points array to track these points shape (t: number of frames, n:number of points for each pillar x 2, x/y:2)
points = np.zeros((len(self), (len(self.points1)+len(self.points2)), 2), dtype=np.float32)
points[0] = np.concatenate((self.points1, self.points2))
# increase contrast on image before predicting to improve results
p2, p98 = np.percentile(self.first_frame, (2, 98))
img_clipped = np.clip(self.first_frame, p2, p98)
img_scaled = minmax_scale(img_clipped, feature_range=(0, 255)).astype(np.uint8)
video_reader = self.video_reader()
next(video_reader)
old_frame = np.stack((img_scaled,)*3, axis=-1)
# Loop through frames in stack
for i in range(1, len(self)):
# Get current frame
unprocessed = next(video_reader)
p2, p98 = np.percentile(unprocessed, (2, 98))
img_clipped = np.clip(unprocessed, p2, p98)
img_scaled = minmax_scale(img_clipped, feature_range=(0, 255)).astype(np.uint8)
new_frame = np.stack((img_scaled,)*3, axis=-1)
points[i],status,err = cv2.calcOpticalFlowPyrLK(old_frame,
new_frame,
prevPts=points[0].reshape(1,-1,2),
nextPts=None,
criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,
100, 0.001),
winSize=(window_size,window_size),
maxLevel=4,
)
displacement1 = points[:,:len(self.points1), :] - points[0,:len(self.points1), :]
displacement2 = points[:,len(self.points1):, :] - points[0,len(self.points1):, :]
# Steps to remove noisy points (poorly tracked points)
# 1. minmax_scale each point and calculate the std.
# 2. remove points that are outliers of the std distribution
norm_disp1 = [minmax_scale(np.linalg.norm(displacement1[:,pt_i],axis=1)) for pt_i in range(displacement1.shape[1])]
norm_disp2 = [minmax_scale(np.linalg.norm(displacement2[:,pt_i],axis=1)) for pt_i in range(displacement2.shape[1])]
std1 = np.std(norm_disp1, axis=1)
std2 = np.std(norm_disp2, axis=1)
def find_outliers_iqr(data):
"""
Identifies outliers in a dataset using the IQR method.
Returns a list of indices corresponding to the outlier values.
"""
quartiles = np.percentile(data, [25, 75])
iqr = quartiles[1] - quartiles[0]
lower_bound = quartiles[0] - 1.5 * iqr
upper_bound = quartiles[1] + 1.5 * iqr
outlier_indices = []
for i, x in enumerate(data):
if x < lower_bound or x > upper_bound:
outlier_indices.append(i)
return outlier_indices
to_drop1 = find_outliers_iqr(std1)
to_drop2 = find_outliers_iqr(std2)
displacement1 = np.delete(displacement1, to_drop1, axis=1)
displacement2 = np.delete(displacement2, to_drop2, axis=1)
#shape (#frames,#points,2)
#self.tracked_points = points
self.tracked_points = np.delete(points, np.append(to_drop1, np.array(to_drop2)+len(self.points1)).astype(int), axis=1)
self.points1 = np.delete(self.points1, to_drop1, axis=0)
self.points2 = np.delete(self.points2, to_drop2, axis=0)
self.center[:, 0] = np.mean(displacement1 + self.center[0, 0], axis=1)
self.center[:, 1] = np.mean(displacement2 + self.center[0, 1], axis=1)
self.trace = np.linalg.norm(self.center[:,0] - self.center[:,1], axis=1)
self.resting_dist = self.trace.max()
if savevid:
self.save_labeled_video(savevid_path)
return self.trace
def calculate_width(self, mask=None, anchor_centers=None, savefig=False, savefig_path=None):
# 1. find midpoint and the slope of the line connecting the two pillar heads
# 2. use the negative reciprocal and the midpoint to find the equation for the perpendicular line intersecting the midpoint
# 3. find the min and max points and increment by 1 for the axis with larger increments
# 4. fill the values in for those points in a dataframe
# 5. find the longest consecutive 1 in the frame, which we assume to be the tissue length
if not mask:
assert not self.mask.all(), "Mask is not defined."
mask = self.mask
if not anchor_centers:
anchor_centers = self.center[0]
# make sure that self.center[0] is initialized
assert not (anchor_centers == 0).all(), "Center points at t=0 are not initialized."
[x1, y1], [x2, y2] = anchor_centers
# find the slope of the perpendicular line
perp_slope = -(x2-x1)/(y2-y1)
# find the midpoint
midpoint_x, midpoint_y = (x1+x2)/2, (y1+y2)/2
# create the perpendicular line between (x1, y1) and (x2, y2)
line = lambda y: midpoint_x + 1/perp_slope*(y-midpoint_y)
# find the edge points
min_y = 0
min_x = line(min_y)
# if min_x is out of bounds, min_x must be 0
if min_x < 0:
min_x = 0
min_y = midpoint_y + perp_slope*(min_x-midpoint_x)
max_y = mask.shape[0]
max_x = line(max_y)
# if max_x is out of bounds, max_x must be the x maximum
if max_x > mask.shape[1]:
max_x = 0
max_y = midpoint_y + perp_slope*(max_x-midpoint_x)
line_pixel = pd.DataFrame()
# if perp_slope has magnitude>1 we can increment y by 1, but if its' <1, we should increment by m
if abs(perp_slope) > 1:
line_pixel['Y'] = np.arange(min_y, max_y, 1)
else:
line_pixel['Y'] = np.arange(min_y, max_y, abs(m))
line_pixel['X'] = line_pixel['Y'].apply(line)
# check if each X, Y coordinate is background or tissue
line_pixel["tissue"] = line_pixel.apply(lambda row: mask[int(row['Y']), int(row['X'])] == 1,axis=1)
def find_longest_consecutive_tissue(df):
# returns np.array of shape 2x4 ((x1,y1), (x2,y2)) containing the coordinates of points marking tissue width
df = line_pixel.copy()
# Resetting the index to create a column
df.reset_index(inplace=True)
# check if next one is different from current
dfBool = df['tissue'] != df['tissue'].shift()
# cumsum only changes when the tissue type is different from next
dfCumsum = dfBool.cumsum()
# grouping by cumsum allows you to separate the line_pixel by tissue or background
groups = df.groupby(dfCumsum)
# for g in groups: print(g)
# groupcounts gets the min and max index of each contiguous segment and its type
groupCounts = groups.agg({'index':['count', 'min', 'max'], 'tissue':'first'})
groupCounts.columns = groupCounts.columns.droplevel()
#print('\n', groupCounts, '\n')
# we don't care about background. just tissues
groupCounts = groupCounts[groupCounts["first"]]
maxCount = groupCounts[groupCounts['count'] == groupCounts['count'].max()]
#print(maxCount, '\n')
if maxCount.empty:
return [None,None,None,None]
else:
maxCount = maxCount.iloc[0]
return np.array([df.loc[int(maxCount["min"]), ["X", "Y"]], df.loc[int(maxCount["max"]), ["X", "Y"]]], dtype=int).flatten()
width_x1, width_y1, width_x2, width_y2 = find_longest_consecutive_tissue(line_pixel)
self.width_coord = np.array([[width_x1, width_y1], [width_x2, width_y2]])
self.width = np.linalg.norm(self.width_coord[0] - self.width_coord[1])
# export if specified
if savefig is True:
self.save_labeled_tissue(savefig_path)
return self.width
# def save_labeled_tissue(self, savefig_path):
# assert savefig_path is not None, "savefig_path cannot be None if savefig is True"
# plt.imshow(self.first_frame, cmap="gray")
# plt.imshow(self.mask, alpha=0.5, cmap="copper")
# if self.width_coord is not None:
# plt.plot(self.width_coord[:,0], self.width_coord[:,1], color="cyan", label="tissue width")
#
# if self.bbox is not None:
# #add rectangle
# plt.gca().add_patch(Rectangle(self.bbox[0, :2],width=(self.bbox[0, 2]-self.bbox[0, 0]),height=(self.bbox[0, 3]-self.bbox[0, 1]),
# edgecolor='#BB5566',
# facecolor='none',
# lw=1))
#
# plt.gca().add_patch(Rectangle(self.bbox[1, :2],width=(self.bbox[1, 2]-self.bbox[1, 0]),height=(self.bbox[1, 3]-self.bbox[1, 1]),