-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcell_segmentation.py
More file actions
executable file
·1519 lines (1165 loc) · 61.8 KB
/
cell_segmentation.py
File metadata and controls
executable file
·1519 lines (1165 loc) · 61.8 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
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 10:09:41 2015
@author: keriabermudez
"""
import cv2
import numpy as np
from skimage import feature,segmentation,filters
from scipy import ndimage
from scipy.spatial import distance
import mahotas as mh
from skimage.measure import regionprops
from sklearn.neighbors import NearestNeighbors
from pandas import DataFrame
from skimage.feature import blob_dog, blob_log
from scipy.spatial import distance
from math import sqrt
from skimage.filters import threshold_otsu
from pandas import Series
import matplotlib as mpl
import matplotlib.pyplot as plt
import io
import base64
from IPython.display import HTML
from skimage import img_as_ubyte,color,exposure
from skimage import io as sio
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
"""Series of functions to segment cells or nuclei"""
font = cv2.FONT_HERSHEY_SIMPLEX
def remove_regions(segmented_image, area, size='smaller'):
"""Removes regions that are smaller than the area, or greater and equal to the area
----------
segmented_image:(N, M) ndarray
Segmented image or labled image
area: int
Area of cuttoff
Returns
-------
segmented_image: (N, M) ndarray
"""
if len(np.unique(segmented_image)) >2:
labeled_image = segmented_image
else:
labeled_image, num_objects= mh.label(segmented_image, np.ones((3,3), bool))
if size == 'smaller':
for region in regionprops(labeled_image):
if region.area < area: #less than mean area - std or greater than
for coord in region.coords:
segmented_image[coord[0],coord[1]] = 0
return segmented_image
else:
for region in regionprops(labeled_image):
if region.area >= area: #less than mean area - std or greater than
for coord in region.coords:
segmented_image[coord[0],coord[1]] = 0
return segmented_image
def kmeans_img(cl1, K):
"""Uses the kmeans clustering algorithm to separate the images in K intensities
----------
cl1:(N, M) ndarray
Intensity image
K: int
number of K intensities you wan to divide the image
Returns
-------
segmented_image: (N, M) ndarray
"""
Z = cl1.reshape((-1))
# convert to np.float32
Z = np.float32(Z)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((cl1.shape))
center = np.sort(center, axis = 0)
center = center[::-1]
return res2, center
def watershedsegment(thresh,smooth_distance = True,kernel = 3,min_dist=10):
"""Uses the watershed segmentation algorithm to separate cells or nuclei in K intensities
----------
thresh:(N, M) ndarray
Segmented image
smooth_distance: bool
If distances will be smoothed
kernel: int
Kernel size for smoothing the distances map
Returns
-------
labeled_image: (N, M) ndarray
The label image will have each cell or nuclei labled with a number
"""
distances = mh.distance(thresh)
if smooth_distance:
distance = ndimage.gaussian_filter(distances, kernel)
else:
distance = distances
maxima = feature.peak_local_max(distance, indices=False, exclude_border=False, min_distance=min_dist)
surface = distance.max() - distance
spots, t = mh.label(maxima)
areas, lines = mh.cwatershed(surface, spots, return_lines=True)
labeled_clusters, num_clusters= mh.label(thresh, np.ones((3,3), bool))
joined_labels = segmentation.join_segmentations(areas, labeled_clusters)
labeled_nucl = joined_labels * thresh
for index, intensity in enumerate(np.unique(labeled_nucl)):
labeled_nucl[labeled_nucl == intensity] = index
return labeled_nucl
def enhance_blur(img, enhance = True, blur = True, kernel = 61):
"""Uses the watershed segmentation algorithm to sperate cells or nuclei in K intensities
----------
img: (N, M) ndarray
RGB image
enhance: bool
If the image will be enhanced using the CLAHE (Contrast Limited Adaptive Histogram Equalization) from OpenCV
blur: bool
If the image will be blurred using the gaussian blur
kernel: int
Kernel size of the gaussian blur
n_intensities: int
Number of intensities you want to segment. If you want to segment into two intensities Otsu is used
If the intensities are greater than 2, then kmeans_img function is used to segment
Returns
-------
cl1: (N, M) ndarray
enhanced image
gaussian_blur_cl1: (N, M) ndarray
blurred image
segmented: (N, M) ndarray
segmented images
centers: int or list of int
Thresholds or centers for the kmeans
"""
if enhance:
clahe = cv2.createCLAHE() # tileGridSize=(8,8)
cl1 = clahe.apply(img)
else:
cl1 = img.copy()
if blur:
gaussian_blur_cl1 = cv2.GaussianBlur(cl1,(kernel,kernel),0, 0)
else:
gaussian_blur_cl1 = cl1.copy()
return gaussian_blur_cl1
def enhance_blur_segment(img,enhance = True, blur = True, kernel = 61, n_intensities = 2):
"""Uses the watershed segmentation algorithm to sperate cells or nuclei in K intensities
----------
img: (N, M) ndarray
RGB image
enhance: bool
If the image will be enhanced using the CLAHE (Contrast Limited Adaptive Histogram Equalization) from OpenCV
blur: bool
If the image will be blurred using the gaussian blur
kernel: int
Kernel size of the gaussian blur
n_intensities: int
Number of intensities you want to segment. If you want to segment into two imatensities Otsu is used
If the intensities are greater than 2, then kmeans_img function is used to segement
Returns
-------
cl1: (N, M) ndarray
enhanced image
gaussian_blur_cl1: (N, M) ndarray
blurred image
segmented: (N, M) ndarray
segmented images
centers: int or list of int
Thresholds or centers for the kmeans
"""
if enhance:
clahe = cv2.createCLAHE() # tileGridSize=(8,8)
cl1 = clahe.apply(img)
else:
cl1 = img.copy()
if blur:
gaussian_blur_cl1 = cv2.GaussianBlur(cl1,(kernel,kernel),0, 0)
else:
gaussian_blur_cl1 = cl1.copy()
if n_intensities == 2:
if(gaussian_blur_cl1.dtype == 'uint8'):
centers, segmented = cv2.threshold(gaussian_blur_cl1,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
else:
centers = filters.threshold_otsu(gaussian_blur_cl1)
segmented = gaussian_blur_cl1 > centers
elif n_intensities > 2:
segmented, centers = kmeans_img(gaussian_blur_cl1, n_intensities)
else:
print ('intensity colors neeed to be 2 or greater')
return (cl1, gaussian_blur_cl1, segmented, centers)
def draw_blob_log(intensity_image,color_image,with_labels = False, max_sigma=8, min_sigma=4,num_sigma=30,threshold=.02,overlap=0.7,color_blobs = (0,0,255),width =1 ):
""" Identifies blobs in intensity image using the scikit image blob_log function, and then draws blobs in color image
-------
intensity_image: (N, M) ndarray
Image where you want to detect the blobs
color_image: (N, M, 3) ndarray
RGB image were you want to draw the blobs
min_sigma: float, optional
The minimum standard deviation for Gaussian Kernel. Keep this low to detect smaller blobs.
max_sigma: float, optional
The maximum standard deviation for Gaussian Kernel. Keep this high to detect larger blobs.
num_sigma: int, optional
The number of intermediate values of standard deviations to consider between min_sigma and max_sigma.
color_blobs: tuple, optional
Color of the blobs. Example: (0,255,0)
width: int, optional
Width of line of blobs
Returns
-------
color_image: (N, M,3) ndarray
RGB image with blobs drawn
"""
blobs = blob_log(intensity_image, max_sigma, min_sigma,num_sigma,threshold,overlap)
try:
blobs[:, 2] = blobs[:, 2] * sqrt(2)
n_label = 0
for blob in blobs:
y, x, r = blob
cv2.circle(color_image, (int(x),int(y)), int(r),color_blobs , width)
if with_labels:
cv2.putText(color_image,str(n_label),(int(x),int(y)),font,1,color_blobs,width,cv2.LINE_AA)
n_label += 1
except:
print(len(blobs))
return color_image
def blob_log_measure(track_image,intensity_image, max_sigma=8, min_sigma=4,num_sigma=30,threshold=.02,overlap=0.7):
""" Identifies blobs in intensity image using the scikit image blob_log function, and then outputs a dataframe table with the positions of the blobs
-------
track_image: (N, M) ndarray
Image where you want to detect the blobs
intensity_image: (N, M) ndarray
Image where you want to measure the intesnity of the blobs
min_sigma: float, optional
The minimum standard deviation for Gaussian Kernel. Keep this low to detect smaller blobs.
max_sigma: float, optional
The maximum standard deviation for Gaussian Kernel. Keep this high to detect larger blobs.
num_sigma: int, optional
The number of intermediate values of standard deviations to consider between min_sigma and max_sigma.
Returns
-------
positions: pandas Dataframe
Table with the center coordinates and labels for the blobs. The columns are the following: ['x_col','y_row','r','track_window']
"""
positions = []
blobs = blob_log(track_image, max_sigma, min_sigma,num_sigma,threshold,overlap)
if len(blobs) > 0 :
blobs[:, 2] = blobs[:, 2] * sqrt(2)
for blob in blobs:
y_row, x_col, r = blob
position = []
position.append(x_col)
position.append(y_row)
position.append(r)
x0 = x_col - r
y0 = y_row - r
if x0 < 0:
x0 = 0
if y0 < 0:
y0 = 0
track_window = (int(x0), int(y0), int(r*2), int(r*2))
position.append(track_window)
mask = np.zeros_like(intensity_image)
cv2.circle(mask, (int(x_col),int(y_row)), int(r),255 , -1)
mean_intensity = intensity_image[mask > 0].mean()
position.append(mean_intensity)
positions.append(position)
positions = DataFrame(positions, columns = ['x_col','y_row','r','track_window','mean_intensity'])
return positions
else:
return []
def draw_blob_dog(intensity_image,color_image,with_labels = False, max_sigma=8, min_sigma=4,num_sigma=30,threshold=.02,overlap=0.7,color_blobs = (0,0,255),width =1 ):
""" Identifies blobs in intensity image using the scikit image blob_dog function, and then draws blobs in color image
-------
intensity_image: (N, M) ndarray
Image where you want to detect the blobs
color_image: (N, M, 3) ndarray
RGB image were you want to draw the blobs
min_sigma: float, optional
The minimum standard deviation for Gaussian Kernel. Keep this low to detect smaller blobs.
max_sigma: float, optional
The maximum standard deviation for Gaussian Kernel. Keep this high to detect larger blobs.
num_sigma: int, optional
The number of intermediate values of standard deviations to consider between min_sigma and max_sigma.
color_blobs: tuple
Color of the blobs. Example: (0,255,0)
width: int
Width of line of blobs
Returns
-------
color_image: (N, M,3) ndarray
RGB image with blobs drawn
"""
blobs = blob_dog(intensity_image, max_sigma, min_sigma,num_sigma,threshold,overlap)
blobs[:, 2] = blobs[:, 2] * sqrt(2)
n_label = 0
for blob in blobs:
y, x, r = blob
cv2.circle(color_image, (int(x),int(y)), int(r),color_blobs , width)
if with_labels:
cv2.putText(color_image,str(n_label),(int(x),int(y)),font,1,color_blobs,width,cv2.LINE_AA)
n_label += 1
return color_image
def draw_contours(labeled,color_image,with_labels= False, color = (255,0,0),width = 1 ):
"""Draws contours based on labeled image
-------
color_blobs: tuple
Color of the blobs. Example: (0,255,0)
width: int, optional
Width of line of blobs
Returns
-------
color_image: (N, M,3) ndarray
RGB image with blobs drawn
"""
contours, hierarchy = cv2.findContours(np.int32(labeled),cv2.RETR_FLOODFILL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(color_image, contours, -1, color, width)
if with_labels:
for region in regionprops(labeled):
(min_row, min_col, max_row, max_col) = region.bbox
label = int(region.label)-1
cv2.putText(color_image,str(region.label),(int(min_col),int(min_row)),font,1,255,width,cv2.LINE_AA)
return color_image
def regions_measure(labeled,intensity_image):
"""Creates a DataFrame of the positions and measurements of the regions based on a labeled image"""
positions =[]
for region in regionprops(labeled,intensity_image):
position = []
y0, x0, y1, x1 = region.bbox #(min_row, min_col, max_row, max_col)
r = (x1-x0)/2.0
y_row = region.centroid[0]
x_col = region.centroid[1]
position.append(x_col)
position.append(y_row)
position.append(r)
track_window = (x0, y0, x1-x0, y1-y0)
position.append(track_window)
position.append(region.mean_intensity)
positions.append(position)
positions = DataFrame(positions, columns = ['x_col','y_row','r','track_window','mean_intensity'])
return positions
def create_video (path, name, zstack_color,fps = 2):
"""Creates an mp4v video from zstack and saves in the path"""
fourcc2 = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') # note the lower case
vout2 = cv2.VideoWriter(path+name+'.mov',fourcc2,fps,zstack_color.shape[1:3],True)
zstack_color_bgr = np.zeros_like(zstack_color)
zstack_color_bgr[:,:,:,0] = zstack_color[:,:,:,2].copy()
zstack_color_bgr[:,:,:,1] = zstack_color[:,:,:,1].copy()
zstack_color_bgr[:,:,:,2] = zstack_color[:,:,:,0].copy()
success = vout2.open(path+name+'.mov',fourcc2,fps,zstack_color_bgr.shape[1:3],True)
#vout2 = cv2.VideoWriter(path+name+'.mov',fourcc2,fps,zstack_color_bgr.shape[1:3],True)
#print success
for frame in list(range(zstack_color_bgr.shape[0])):
new_frame = zstack_color_bgr[frame]
vout2.write(new_frame)
vout2.release()
def jupyter_video(fname):
video = io.open(fname, 'r+b').read()
encoded = base64.b64encode(video)
HTML(data='''<video alt="test" controls>
<source src="data:video/mp4;base64,{0}" type="video/mp4" />
</video>'''.format(encoded.decode('ascii')))
def video_to_tif(path,index):
"""Reads video and retuns tif
"""
cap = cv2.VideoCapture(path)
rows = int(cap.get(4))
columns = int(cap.get(3))
frames = int(cap.get(7))
tif_image = np.zeros((frames,rows, columns), dtype = np.uint8)
i = 0
while(cap.isOpened()):
ret, frame = cap.read()
if ret:
tif_image[i] = frame[:,:,index].copy()
i += 1
if i == frames:
break
cap.release()
return tif_image
def find_track_window_object(bool_image, window_mask, orig_image, window_area, prev_object_area, ws_smooth, ws_kernal, ws_dist):
#segment and watershed to get objects in thresholded image
#identify object that overlaps largest area of the tracking window
#calculate mean intensity of object *limited to tracking window*
#returns mean intensity, bbox of object
#fill holes
bool_image = ndimage.morphology.binary_fill_holes(bool_image)
#label objects
labeled, number = mh.label(bool_image,np.ones((3,3), bool))
### for debugging ###
l1 = color.label2rgb(labeled,bg_label=0)
l1_=img_as_ubyte(l1)
#select region that covers the most % of tracking window
regions = regionprops(labeled,orig_image)
max_perc = 0
for i, region in enumerate(regions):
count = 0
for (row,col) in region.coords:
if(window_mask[row][col]):
count+= 1
if(max_perc < count/float(window_area)):
max_perc = count/float(window_area)
mean_intensity = region.mean_intensity
bbox = region.bbox
region_label = region.label
region_area = region.area
#check regions is not too big
if((prev_object_area == 0 and region_area > window_area) or #first case is the initial frame
(prev_object_area > 0 and region_area > prev_object_area*1.5)):
#print "*Watershed*"
#might have 2 cells touching as the region, try watershed
labeled_2 = watershedsegment(bool_image, ws_smooth, ws_kernal, ws_dist)
### for debugging ###
l2 = color.label2rgb(labeled_2,bg_label=0)
l2_=img_as_ubyte(l2)
#combine segmentations
labeled = segmentation.join_segmentations(labeled, labeled_2)
### for debugging ###
l3 = color.label2rgb(labeled,bg_label=0)
l3_=img_as_ubyte(l3)
#select region that covers the most % of tracking window
regions = regionprops(labeled,orig_image)
max_perc = 0
for i, region in enumerate(regions):
count = 0
for (row,col) in region.coords:
if(window_mask[row][col]):
count+= 1
if(max_perc < count/float(window_area)):
max_perc = count/float(window_area)
mean_intensity = region.mean_intensity
bbox = region.bbox
region_label = region.label
region_area = region.area
elif(prev_object_area > 0 and region_area*1.5 < prev_object_area):
#check region is not too small
#might have a low intensity object and need to try kmeans instead of otsu thresh
pass
#create mask with only the identified object
obj_mask = np.zeros_like(orig_image)
obj_mask[labeled == region_label] = np.iinfo(orig_image.dtype).max
return (obj_mask, mean_intensity, bbox)
class cell_tracking:
#initiate
"""Class for cell tracking """
def __init__(self,zstack, zstack_to_segment, zstack_color):
"""
zstack: (Z, N, M) ndarray
Intensity zstack where Z is the number of slices or frames
zstack_to_segment: (Z, N, M) ndarray where
Z is the number of slices or frames
zstack_color: An RGB Stack (Z, N, M, 3) ndarray where S is the number of slices or frames
"""
self.zstack = zstack.copy()
self.zstack_to_segment = zstack_to_segment.copy()
self.zstack_color = zstack_color.copy()
self.zstack_color_orig = zstack_color.copy()
#Parameters
self._enhance = None
self._blur = None
self._kernel = None
self._n_intensities = None
self._smooth_distance = None
self._distance_kernel = None
self._min_distance = None
#Parameters
self._max_sigma = None
self._min_sigma = None
self._num_sigma = None
self._threshold = None
self._overlap = None
#Parameters
self.segment_param = False
self.watershed_param = False
self.blob_param = False
self.positions_table = []
def set_segment_param(self,enhance = True, blur = True, kernel = 61, n_intensities = 2):
"""Segmentation parameters. Add them before using the function stack_enhance_blur_segment
enhance: bool
If the image will be enhanced using the CLAHE (Contrast Limited Adaptive Histogram Equalization) from OpenCV
blur: bool
If the image will be blurred using the gaussian blur
kernel: int
Kernel size of the gaussian blur
n_intensities: int
Number of intensities you want to segment. If you want to segment into two imatensities Otsu is used
If the intensities are greater than 2, then kmeans_img function is used to segement
"""
self._enhance = enhance
self._blur = blur
self._kernel = kernel
self._n_intensities = n_intensities
self.segment_param = True
def set_watershed_param(self,smooth_distance = True, kernel = 3, min_distance=10):
"""Watershed segmentation parameters. Add them before using the function stack_watershedsegment
smooth_distance: bool
If distances will be smoothed
kernel: int
Kernel size for smoothing the distances map
"""
self._smooth_distance = smooth_distance
self._distance_kernel = kernel
self._min_distance = min_distance
self.watershed_param = True
def set_blob_param(self,max_sigma,min_sigma,num_sigma, threshold, overlap):
"""Blob detection parameters. Add them before using any blob detection function """
self._max_sigma = max_sigma
self._min_sigma = min_sigma
self._num_sigma = num_sigma
self._threshold = threshold
self._overlap = overlap
self.blob_param = True
def stack_enhance_blur_segment(self):
"""Created stacks of enhanced, and segmented stacks"""
cl1_stack = np.zeros_like(self.zstack_to_segment)
gaussian_blur_cl1_stack = np.zeros_like(self.zstack_to_segment)
segmented_stack = np.zeros_like(self.zstack_to_segment)
for z_level in range(0,self.zstack_to_segment.shape[0]):
img = self.zstack_to_segment[z_level].copy()
cl1, gaussian_blur_cl1, segmented, centers = enhance_blur_segment(img,self._enhance,self._blur,self._kernel,self._n_intensities)
cl1_stack[z_level] = cl1
gaussian_blur_cl1_stack[z_level] = gaussian_blur_cl1
segmented_stack[z_level] = segmented
self.cl1_stack = cl1_stack
self.gaussian_blur_cl1_stack = gaussian_blur_cl1_stack
self.segmented_stack = segmented_stack
self.stack_blob = gaussian_blur_cl1_stack
#return (cl1_stack,gaussian_blur_cl1_stack,segmented_stack)
def stack_watershedsegment(self):
"""Creates labeled stack after watershed segmentation """
labeled_stack = np.zeros_like(self.segmented_stack)
for z_level in range(0,self.segmented_stack.shape[0]):
segmented = self.segmented_stack[z_level].copy()
labeled = watershedsegment(segmented,self._smooth_distance,self._distance_kernel)
labeled_stack[z_level]=labeled.copy()
self.labeled_stack = labeled_stack
#return labeled_stack
def create_table_blobs(self):
"""Creates DataFrame table of measurements of blobs. The columns are 'x_col','y_row','z','r','label','track_window','mean_intensity','median_intensity' """
n_label = 1
positions = []
for n in range(0,self.stack_blob.shape[0]):
img = self.stack_blob[n]
intensity_image = self.zstack[n]
blobs = blob_log(img, self._max_sigma, self._min_sigma,self._num_sigma,self._threshold,self._overlap)
if len(blobs) > 0:
blobs[:, 2] = blobs[:, 2] * sqrt(2)
for blob in blobs:
y_row, x_col, r = blob
position = []
position.append(x_col)
position.append(y_row)
position.append(n)
position.append(r)
position.append(0)
x0 = x_col - r
y0 = y_row - r
if x0 < 0:
x0 = 0
if y0 < 0:
y0 = 0
track_window = (int(x0), int(y0), int(r*2), int(r*2))
position.append(track_window)
mask = np.zeros_like(intensity_image)
cv2.circle(mask, (int(x_col),int(y_row)), int(r),255 , -1)
mean_intensity = intensity_image[mask > 0].mean()
median_intensity = np.median(intensity_image[mask > 0])
position.append(mean_intensity)
position.append(median_intensity)
n_label += 1
positions.append(position)
self.positions_table = DataFrame(positions, columns = ['x_col','y_row','z','r','label','track_window','mean_intensity','median_intensity'])
#self.positions = np.array(positions)
#return (self.positions, self.positions_table)
def create_table_regions(self):
"""Creates DataFrame table of measurements of regions. The columns are 'x_col','y_row','z','r','label','track_window','mean_intensity'"""
n_label = 1
positions = []
for n in range(0,self.labeled_stack.shape[0]):
labeled_slice = self.labeled_stack[n]
intensity_image = self.zstack[n]
for region in regionprops(labeled_slice, intensity_image):
position = []
y_row = region.centroid[0]
x_col = region.centroid[1]
y0, x0, y1, x1 = region.bbox #(min_row, min_col, max_row, max_col)
r = (x1-x0)/2
position.append(x_col)
position.append(y_row)
position.append(n)
position.append(r)
position.append(0)
track_window = (x0, y0, x1-x0, y1-y0)
position.append(track_window)
mean_intensity = region.mean_intensity
position.append(mean_intensity)
n_label += 1
positions.append(position)
self.positions_table = DataFrame(positions, columns = ['x_col','y_row','z','r','label','track_window','mean_intensity'])
#self.positions = np.array(positions)
#return (self.positions, self.positions_table)
def add_labels_table(self):
""" Adds the labels fo the cells based on the distances of the center
"""
positions = self.positions_table.ix[:,'x_col':'z'].as_matrix()
max_label = self.positions_table['label'].max()
# Loops through each zlevel
for z_level in range(0,self.positions_table.z.max()+1):
#create a table of only the posiitons in the zlevel
z_level_positions = self.positions_table[self.positions_table.z == z_level]
if z_level < self.positions_table.z.max() :
#create a table of the positions of the next zlevel
z_level_positions_other = self.positions_table[self.positions_table.z == z_level+1] #maybe change this
#fit the positions
positions = z_level_positions_other.ix[:,'x_col':'z'].as_matrix()
nbrs = NearestNeighbors().fit(positions)
# loop for each region in zlevel positions
for index in z_level_positions.index: # for each of the regions in the slice
region = z_level_positions.ix[index,'x_col':'z'].as_matrix()
region_label = z_level_positions.ix[index,'label']
if region_label == 0: # if region label is 0 then add 1
max_label+=1
region_label = max_label
self.positions_table.ix[index,'label'] = region_label # change the label
region_radius = z_level_positions.ix[index,'r'] # get radius
dist,indexes = nbrs.kneighbors(region.reshape(1,-1),1) #find in the next slice what is the closest center
if dist[0][0] > region_radius: #if the distance is greater than the radius continue
continue
elif len(dist) == 0:
continue
else:
location = indexes[0][0] #if not then add the label to that region as well
positions_table_index = z_level_positions_other.index[location]
self.positions_table.ix[positions_table_index,'label']= region_label
else: #last zlevel
for index in z_level_positions.index: # for each of the regions in the zlevel
region = z_level_positions.ix[index,'x_col':'z'].as_matrix()
region_label = z_level_positions.ix[index,'label']
if region_label == 0: # if region label is 0 then add 1
max_label+=1
self.positions_table.ix[index,'label'] = max_label
def filter_table(self,min_slices):
"""Function to remove labeled blobs or regions that are present in less than a minimum number of slices or frames
"""
table_positions = self.positions_table.copy()
for unique_label in np.unique(table_positions.label):
table_label = table_positions[table_positions.label == unique_label ]
if len(table_label) < min_slices:
table_positions = table_positions[table_positions.label != unique_label ]
self.positions_table = table_positions
def draw_labels(self, color = (0,0,255), with_blobs =True ,width = 2):
"""Draws labels and blobs/circles in the cells in the zstack_color """
for z_level in range(0,self.positions_table.z.max()+1):
z_level_positions = self.positions_table[self.positions_table.z == z_level]
zstack_slice = self.zstack_color[z_level]
for index in z_level_positions.index:
y_row = self.positions_table.ix[index,'y_row']
x_col = self.positions_table.ix[index,'x_col']
r = self.positions_table.ix[index,'r']
label = self.positions_table.ix[index,'label']
cv2.putText(zstack_slice,str(label),(int(x_col),int(y_row)),font,1,color,width,cv2.LINE_AA)
if with_blobs:
cv2.circle(zstack_slice, (int(x_col),int(y_row)), int(r),color , width)
def draw_contours(self, color_contours = (0,0,255), width = 2):
"""Draws the contours in the cells in the zstack_color """
for z_level in range(self.zstack_color.shape[0]):
labeled = self.labeled_stack[z_level]
color = self.zstack_color[z_level]
draw_contours(labeled,color,with_labels=False, color = (255,0,0) ,width = 1 )
def track_with_blob(self,min_slices = 2, color_blobs = (0,0,255), reset_drawing = False):
"""Function for tracking with blob detection. You need to set the segmentation parameters and the blob parameters before running.
It will created a table of the positions and measurments and will draw the labels in the zstack color image
"""
if len(self.positions_table) == 0:
if self.segment_param == True and self.blob_param == True:
self.stack_enhance_blur_segment()
self.create_table_blobs()
self.add_labels_table()
else:
print ("Set blob and segmentation parameters")
self.filter_table(min_slices)
if reset_drawing:
self.reset_drawing()
self.draw_labels(color= color_blobs)
def track_with_regions(self,color_contours = (255,0,0),color_labels = (255,0,0),min_slices = 10, reset_drawing = False):
"""Function for tracking with regions . You need to set the segmentation and watershed segmentation parameters before running.
It will created a table of the positions and measurments and will draw the labels in the zstack color image
"""
if self.segment_param == True and self.watershed_param == True:
self.stack_enhance_blur_segment()
self.stack_watershedsegment()
if len(self.positions_table) == 0:
self.create_table_regions()
self.add_labels_table()
self.filter_table(min_slices)
if reset_drawing:
self.reset_drawing()
self.draw_labels(color=color_labels, with_blobs= False)
self.draw_contours(color_contours=color_contours)
else:
print ("Set segmentation parameters")
def find_trajectories(self):
"""
Creates a table of the trajectories for each cell
"""
trajectories ={}
for label in self.positions_table['label'].unique():
table_label = self.positions_table[self.positions_table.label == label]
table_label = table_label.sort_values(by = 'z')
trajectory_matrix = table_label.ix[:, 'x_col':'y_row'].as_matrix()
#dist = distance.pdist(trajectory_matrix.T)
dist = 0
for index in range(0, len(trajectory_matrix)):
if index+1 < len(trajectory_matrix):
dist += distance.euclidean(trajectory_matrix[index],trajectory_matrix[index+1])
trajectories[label] = {'trajectory':trajectory_matrix, 'distance': dist ,'dist_per_frame' :dist/len(trajectory_matrix)}
table_trajectories =DataFrame(trajectories)
self.trajectories = table_trajectories
def draw_trajectories(self,color_trajectory = (255,0,0) , width = 2):
"""Draws the trajectories of each cell in the zstack_color. Make sure to run find_trajectories function"""
zstack_color = self.zstack_color
for label in self.positions_table['label'].unique():
table_label = self.positions_table[self.positions_table.label == label]
table_label = table_label.sort_values(by = 'z')
z_min = table_label.z.min()
zslice = zstack_color[z_min]
zslice_row = table_label[table_label['z'] == z_min]
center = zslice_row.ix[:,'x_col':'y_row'].as_matrix()
trajectory = center[0].astype('int64')
x = int(zslice_row.ix[:,'x_col'].values[0])
y = int(zslice_row.ix[:,'y_row'].values[0])
cv2.circle(zslice, (x,y), width, color_trajectory , -1)
for z in table_label.z.unique():
if z > z_min:
zslice = zstack_color[z]
zslice_row = table_label[table_label['z'] == z]
new_center = zslice_row.ix[:,'x_col':'y_row'].as_matrix()
new_center = new_center[0].astype('int64')
trajectory = np.vstack((trajectory,new_center))
cv2.polylines(zslice,[trajectory],False, color_trajectory,width)
else:
continue
def create_video(self, path, name, fps = 2):
"""Creates and saves the zstack_color as a mp4v video in the path """
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') # note the lower case
vout = cv2.VideoWriter()
zstack_color = self.zstack_color
zstack_color_bgr = np.zeros_like(zstack_color)
success = vout.open(path+name+'.mov',fourcc,fps,zstack_color_bgr.shape[1:3],True)
zstack_color_bgr[:,:,:,0] = zstack_color[:,:,:,2].copy()
zstack_color_bgr[:,:,:,1] = zstack_color[:,:,:,1].copy()
zstack_color_bgr[:,:,:,2] = zstack_color[:,:,:,0].copy()
for frame in list(range(self.zstack_color.shape[0])):
new_frame = zstack_color_bgr[frame]
vout.write(new_frame)
vout.release()
def reset_drawing(self):
"""Resets the drawing of the zstack_color"""
self.zstack_color = self.zstack_color_orig.copy()
def track_window_object(self, z, track_window, enhance_bool = True, blur_bool = True, kernel_size = 11):
"""
Function to track an object centered in the given track_window
Uses thresholding over the track_window pixels to identify the object
(The object that overlaps the largest % of pixels in the track_window will be identified)
The bbox of the identified object will be used in the next iteration of tracking
Mean intensity and position is saved for each frame
In addition, object contours and tracking window are marked on each frame
(in order to re-create a video of the tracking)
CamShift/MeanShift are not used, works with 16-bit images
"""
positions = []
x0 = track_window[0]