/
measureobjectintensitydistribution.py
1559 lines (1180 loc) · 51.9 KB
/
measureobjectintensitydistribution.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
# coding=utf-8
import centrosome.cpmorphology
import centrosome.propagate
import centrosome.zernike
import matplotlib.cm
import numpy
import numpy.ma
import scipy.ndimage
import scipy.sparse
import cellprofiler.gui.help.content
import cellprofiler.image
import cellprofiler.measurement
import cellprofiler.module
import cellprofiler.object
import cellprofiler.preferences
import cellprofiler.setting
import cellprofiler.workspace
MeasureObjectIntensityDistribution_Magnitude_Phase = cellprofiler.gui.help.content.image_resource(
"MeasureObjectIntensityDistribution_Magnitude_Phase.png"
)
MeasureObjectIntensityDistribution_Edges_Centers = cellprofiler.gui.help.content.image_resource(
"MeasureObjectIntensityDistribution_Edges_Centers.png"
)
__doc__ = """
MeasureObjectIntensityDistribution
==================================
**MeasureObjectIntensityDistribution** measures the spatial distribution of
intensities within each object.
Given an image with objects identified, this module measures the
intensity distribution from each object’s center to its boundary within
a set of bins, i.e., rings that you specify.
|MeasureObjectIntensityDistribution_image0|
The distribution is measured from the center of the object, where the
center is defined as the point farthest from any edge. The numbering of bins is
from 1 (innermost) to *N* (outermost), where *N* is the number of bins
you specify. Alternatively, if primary objects exist within
the object of interest (e.g., nuclei within cells), you can choose the
center of the primary objects as the center from which to measure the
radial distribution. This might be useful in cytoplasm-to-nucleus
translocation experiments, for example. Note that the ring widths are
normalized per-object, i.e., not necessarily a constant width across
objects.
|MeasureObjectIntensityDistribution_image1|
|
============ ============ ===============
Supports 2D? Supports 3D? Respects masks?
============ ============ ===============
YES NO YES
============ ============ ===============
See also
^^^^^^^^
See also **MeasureObjectIntensity** and **MeasureTexture**.
Measurements made by this module
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- *FracAtD:* Fraction of total stain in an object at a given radius.
- *MeanFrac:* Mean fractional intensity at a given radius; calculated
as fraction of total intensity normalized by fraction of pixels at a
given radius.
- *RadialCV:* Coefficient of variation of intensity within a ring,
calculated across 8 slices.
- *Zernike:* The Zernike features characterize the distribution of
intensity across the object. For instance, Zernike 1,1 has a high
value if the intensity is low on one side of the object and high on
the other. The ZernikeMagnitude feature records the rotationally
invariant degree magnitude of the moment and the ZernikePhase feature
gives the moment’s orientation.
.. |MeasureObjectIntensityDistribution_image0| image:: {MeasureObjectIntensityDistribution_Magnitude_Phase}
.. |MeasureObjectIntensityDistribution_image1| image:: {MeasureObjectIntensityDistribution_Edges_Centers}
""".format(
**{
"MeasureObjectIntensityDistribution_Magnitude_Phase": MeasureObjectIntensityDistribution_Magnitude_Phase,
"MeasureObjectIntensityDistribution_Edges_Centers": MeasureObjectIntensityDistribution_Edges_Centers,
}
)
C_SELF = "These objects"
C_CENTERS_OF_OTHER_V2 = "Other objects"
C_CENTERS_OF_OTHER = "Centers of other objects"
C_EDGES_OF_OTHER = "Edges of other objects"
C_ALL = [C_SELF, C_CENTERS_OF_OTHER, C_EDGES_OF_OTHER]
Z_NONE = "None"
Z_MAGNITUDES = "Magnitudes only"
Z_MAGNITUDES_AND_PHASE = "Magnitudes and phase"
Z_ALL = [Z_NONE, Z_MAGNITUDES, Z_MAGNITUDES_AND_PHASE]
M_CATEGORY = "RadialDistribution"
F_FRAC_AT_D = "FracAtD"
F_MEAN_FRAC = "MeanFrac"
F_RADIAL_CV = "RadialCV"
F_ALL = [F_FRAC_AT_D, F_MEAN_FRAC, F_RADIAL_CV]
FF_SCALE = "%dof%d"
FF_OVERFLOW = "Overflow"
FF_GENERIC = "_%s_" + FF_SCALE
FF_FRAC_AT_D = F_FRAC_AT_D + FF_GENERIC
FF_MEAN_FRAC = F_MEAN_FRAC + FF_GENERIC
FF_RADIAL_CV = F_RADIAL_CV + FF_GENERIC
FF_ZERNIKE_MAGNITUDE = "ZernikeMagnitude"
FF_ZERNIKE_PHASE = "ZernikePhase"
MF_FRAC_AT_D = "_".join((M_CATEGORY, FF_FRAC_AT_D))
MF_MEAN_FRAC = "_".join((M_CATEGORY, FF_MEAN_FRAC))
MF_RADIAL_CV = "_".join((M_CATEGORY, FF_RADIAL_CV))
OF_FRAC_AT_D = "_".join((M_CATEGORY, F_FRAC_AT_D, "%s", FF_OVERFLOW))
OF_MEAN_FRAC = "_".join((M_CATEGORY, F_MEAN_FRAC, "%s", FF_OVERFLOW))
OF_RADIAL_CV = "_".join((M_CATEGORY, F_RADIAL_CV, "%s", FF_OVERFLOW))
"""# of settings aside from groups"""
SETTINGS_STATIC_COUNT = 3
"""# of settings in image group"""
SETTINGS_IMAGE_GROUP_COUNT = 1
"""# of settings in object group"""
SETTINGS_OBJECT_GROUP_COUNT = 3
"""# of settings in bin group, v1"""
SETTINGS_BIN_GROUP_COUNT_V1 = 1
"""# of settings in bin group, v2"""
SETTINGS_BIN_GROUP_COUNT_V2 = 3
SETTINGS_BIN_GROUP_COUNT = 3
"""# of settings in heatmap group, v4"""
SETTINGS_HEATMAP_GROUP_COUNT_V4 = 7
SETTINGS_HEATMAP_GROUP_COUNT = 7
"""Offset of center choice in object group"""
SETTINGS_CENTER_CHOICE_OFFSET = 1
A_FRAC_AT_D = "Fraction at Distance"
A_MEAN_FRAC = "Mean Fraction"
A_RADIAL_CV = "Radial CV"
MEASUREMENT_CHOICES = [A_FRAC_AT_D, A_MEAN_FRAC, A_RADIAL_CV]
MEASUREMENT_ALIASES = {
A_FRAC_AT_D: MF_FRAC_AT_D,
A_MEAN_FRAC: MF_MEAN_FRAC,
A_RADIAL_CV: MF_RADIAL_CV,
}
class MeasureObjectIntensityDistribution(cellprofiler.module.Module):
module_name = "MeasureObjectIntensityDistribution"
category = "Measurement"
variable_revision_number = 5
def create_settings(self):
self.images = []
self.objects = []
self.bin_counts = []
self.heatmaps = []
self.image_count = cellprofiler.setting.HiddenCount(self.images)
self.object_count = cellprofiler.setting.HiddenCount(self.objects)
self.bin_counts_count = cellprofiler.setting.HiddenCount(self.bin_counts)
self.heatmap_count = cellprofiler.setting.HiddenCount(self.heatmaps)
self.wants_zernikes = cellprofiler.setting.Choice(
"Calculate intensity Zernikes?",
Z_ALL,
doc="""\
This setting determines whether the intensity Zernike moments are
calculated. Choose *{Z_NONE}* to save computation time by not
calculating the Zernike moments. Choose *{Z_MAGNITUDES}* to only save
the magnitude information and discard information related to the
object’s angular orientation. Choose *{Z_MAGNITUDES_AND_PHASE}* to
save the phase information as well. The last option lets you recover
each object’s rough appearance from the Zernikes but may not contribute
useful information for classifying phenotypes.
|MeasureObjectIntensityDistribution_image0|
.. |MeasureObjectIntensityDistribution_image0| image:: {MeasureObjectIntensityDistribution_Magnitude_Phase}
""".format(
**{
"Z_NONE": Z_NONE,
"Z_MAGNITUDES": Z_MAGNITUDES,
"Z_MAGNITUDES_AND_PHASE": Z_MAGNITUDES_AND_PHASE,
"MeasureObjectIntensityDistribution_Magnitude_Phase": MeasureObjectIntensityDistribution_Magnitude_Phase,
}
),
)
self.zernike_degree = cellprofiler.setting.Integer(
"Maximum zernike moment",
value=9,
minval=1,
maxval=20,
doc="""\
(*Only if "{wants_zernikes}" is "{Z_MAGNITUDES}" or "{Z_MAGNITUDES_AND_PHASE}"*)
This is the maximum radial moment that will be calculated. There are
increasing numbers of azimuthal moments as you increase the radial
moment, so higher values are increasingly expensive to calculate.
""".format(
**{
"wants_zernikes": self.wants_zernikes.text,
"Z_MAGNITUDES": Z_MAGNITUDES,
"Z_MAGNITUDES_AND_PHASE": Z_MAGNITUDES_AND_PHASE,
}
),
)
self.add_image_button = cellprofiler.setting.DoSomething(
"", "Add another image", self.add_image
)
self.spacer_1 = cellprofiler.setting.Divider()
self.add_object_button = cellprofiler.setting.DoSomething(
"", "Add another object", self.add_object
)
self.spacer_2 = cellprofiler.setting.Divider()
self.add_bin_count_button = cellprofiler.setting.DoSomething(
"", "Add another set of bins", self.add_bin_count
)
self.spacer_3 = cellprofiler.setting.Divider()
self.add_heatmap_button = cellprofiler.setting.DoSomething(
"",
"Add another heatmap display",
self.add_heatmap,
doc="""\
Press this button to add a display of one of the radial distribution
measurements. Each radial band of the object is colored using a
heatmap according to the measurement value for that band.
""",
)
self.add_image(can_remove=False)
self.add_object(can_remove=False)
self.add_bin_count(can_remove=False)
def add_image(self, can_remove=True):
group = cellprofiler.setting.SettingsGroup()
if can_remove:
group.append("divider", cellprofiler.setting.Divider(line=False))
group.append(
"image_name",
cellprofiler.setting.ImageNameSubscriber(
"Select an image to measure",
cellprofiler.setting.NONE,
doc="Select the image whose intensity distribution you want to measure.",
),
)
if can_remove:
group.append(
"remover",
cellprofiler.setting.RemoveSettingButton(
"", "Remove this image", self.images, group
),
)
self.images.append(group)
def add_object(self, can_remove=True):
group = cellprofiler.setting.SettingsGroup()
if can_remove:
group.append("divider", cellprofiler.setting.Divider(line=False))
group.append(
"object_name",
cellprofiler.setting.ObjectNameSubscriber(
"Select objects to measure",
cellprofiler.setting.NONE,
doc="Select the objects whose intensity distribution you want to measure.",
),
)
group.append(
"center_choice",
cellprofiler.setting.Choice(
"Object to use as center?",
C_ALL,
doc="""\
There are three ways to specify the center of the radial measurement:
- *{C_SELF}:* Use the centers of these objects for the radial
measurement.
- *{C_CENTERS_OF_OTHER}:* Use the centers of other objects for the
radial measurement.
- *{C_EDGES_OF_OTHER}:* Measure distances from the edge of the other
object to each pixel outside of the centering object. Do not include
pixels within the centering object in the radial measurement
calculations.
For example, if measuring the radial distribution in a Cell object, you
can use the center of the Cell objects (*{C_SELF}*) or you can use
previously identified Nuclei objects as the centers
(*{C_CENTERS_OF_OTHER}*).
|MeasureObjectIntensityDistribution_image1|
.. |MeasureObjectIntensityDistribution_image1| image:: {MeasureObjectIntensityDistribution_Edges_Centers}
""".format(
**{
"C_SELF": C_SELF,
"C_CENTERS_OF_OTHER": C_CENTERS_OF_OTHER,
"C_EDGES_OF_OTHER": C_EDGES_OF_OTHER,
"MeasureObjectIntensityDistribution_Edges_Centers": MeasureObjectIntensityDistribution_Edges_Centers,
}
),
),
)
group.append(
"center_object_name",
cellprofiler.setting.ObjectNameSubscriber(
"Select objects to use as centers",
cellprofiler.setting.NONE,
doc="""\
*(Used only if “{C_CENTERS_OF_OTHER}” are selected for centers)*
Select the object to use as the center, or select *None* to use the
input object centers (which is the same as selecting *{C_SELF}* for the
object centers).
""".format(
**{"C_CENTERS_OF_OTHER": C_CENTERS_OF_OTHER, "C_SELF": C_SELF}
),
),
)
if can_remove:
group.append(
"remover",
cellprofiler.setting.RemoveSettingButton(
"", "Remove this object", self.objects, group
),
)
self.objects.append(group)
def add_bin_count(self, can_remove=True):
group = cellprofiler.setting.SettingsGroup()
if can_remove:
group.append("divider", cellprofiler.setting.Divider(line=False))
group.append(
"wants_scaled",
cellprofiler.setting.Binary(
"Scale the bins?",
True,
doc="""\
Select *{YES}* to divide the object radially into the number of bins
that you specify.
Select *{NO}* to create the number of bins you specify based on
distance. For this option, you will be asked to specify a maximum
distance so that each object will have the same measurements (which
might be zero for small objects) and so that the measurements can be
taken without knowing the maximum object radius before the run starts.
""".format(
**{"YES": cellprofiler.setting.YES, "NO": cellprofiler.setting.NO}
),
),
)
group.append(
"bin_count",
cellprofiler.setting.Integer(
"Number of bins",
4,
2,
doc="""\
Specify the number of bins that you want to use to measure the
distribution. Radial distribution is measured with respect to a series
of concentric rings starting from the object center (or more generally,
between contours at a normalized distance from the object center). This
number specifies the number of rings into which the distribution is to
be divided. Additional ring counts can be specified by clicking the *Add
another set of bins* button.""",
),
)
group.append(
"maximum_radius",
cellprofiler.setting.Integer(
"Maximum radius",
100,
minval=1,
doc="""\
Specify the maximum radius for the unscaled bins. The unscaled binning method creates the number of
bins that you specify and creates equally spaced bin boundaries up to the maximum radius. Parts of
the object that are beyond this radius will be counted in an overflow bin. The radius is measured
in pixels.
""",
),
)
group.can_remove = can_remove
if can_remove:
group.append(
"remover",
cellprofiler.setting.RemoveSettingButton(
"", "Remove this set of bins", self.bin_counts, group
),
)
self.bin_counts.append(group)
def get_bin_count_choices(self, pipeline=None):
choices = []
for bin_count in self.bin_counts:
nbins = str(bin_count.bin_count.value)
if nbins != choices:
choices.append(nbins)
return choices
def add_heatmap(self):
group = cellprofiler.setting.SettingsGroup()
if len(self.heatmaps) > 0:
group.append("divider", cellprofiler.setting.Divider(line=False))
group.append(
"image_name",
MORDImageNameSubscriber(
"Image",
doc="""\
The heatmap will be displayed with measurements taken using this image. The setting will let you
choose from among the images you have specified in "Select image to measure".
""",
),
)
group.image_name.set_module(self)
group.append(
"object_name",
MORDObjectNameSubscriber(
"Objects to display",
doc="""\
The objects to display in the heatmap. You can select any of the
objects chosen in "Select objects to measure".""",
),
)
group.object_name.set_module(self)
group.append(
"bin_count",
cellprofiler.setting.Choice(
"Number of bins",
self.get_bin_count_choices(),
choices_fn=self.get_bin_count_choices,
),
)
def get_number_of_bins(module=self, group=group):
if len(module.bin_counts) == 1:
return module.bin_counts[0].bin_count.value
return int(group.bin_count.value)
group.get_number_of_bins = get_number_of_bins
group.append(
"measurement",
cellprofiler.setting.Choice(
"Measurement", MEASUREMENT_CHOICES, doc="The measurement to display."
),
)
group.append(
"colormap",
cellprofiler.setting.Colormap(
"Color map",
doc="""\
The color map setting chooses the color palette that will be
used to render the different values for your measurement. If you
choose "gray", the image will label each of the bins with the
actual image measurement.""",
),
)
group.append(
"wants_to_save_display",
cellprofiler.setting.Binary(
"Save display as image?",
False,
doc="""\
This setting allows you to save the heatmap display as an image that can
be output using the **SaveImages** module. Choose *{YES}* to save the
display or *{NO}* if the display is not needed.
""".format(
**{"YES": cellprofiler.setting.YES, "NO": cellprofiler.setting.NO}
),
),
)
group.append(
"display_name",
cellprofiler.setting.ImageNameProvider(
"Output image name",
"Heatmap",
doc="""\
*(Only used if “Save display as image?” is “{YES}”)*
This setting names the heatmap image so that the name you enter here can
be selected in a later **SaveImages** or other module.
""".format(
**{"YES": cellprofiler.setting.YES}
),
),
)
group.append(
"remover",
cellprofiler.setting.RemoveSettingButton(
"", "Remove this heatmap display", self.heatmaps, group
),
)
self.heatmaps.append(group)
def validate_module(self, pipeline):
images = set()
for group in self.images:
if group.image_name.value in images:
raise cellprofiler.setting.ValidationError(
"{} has already been selected".format(group.image_name.value),
group.image_name,
)
images.add(group.image_name.value)
objects = set()
for group in self.objects:
if group.object_name.value in objects:
raise cellprofiler.setting.ValidationError(
"{} has already been selected".format(group.object_name.value),
group.object_name,
)
objects.add(group.object_name.value)
bins = set()
for group in self.bin_counts:
if group.bin_count.value in bins:
raise cellprofiler.setting.ValidationError(
"{} has already been selected".format(group.bin_count.value),
group.bin_count,
)
bins.add(group.bin_count.value)
def settings(self):
result = [
self.image_count,
self.object_count,
self.bin_counts_count,
self.heatmap_count,
self.wants_zernikes,
self.zernike_degree,
]
for x in (self.images, self.objects, self.bin_counts, self.heatmaps):
for settings in x:
temp = settings.pipeline_settings()
result += temp
return result
def visible_settings(self):
result = [self.wants_zernikes]
if self.wants_zernikes != Z_NONE:
result.append(self.zernike_degree)
for settings in self.images:
result += settings.visible_settings()
result += [self.add_image_button, self.spacer_1]
for settings in self.objects:
temp = settings.visible_settings()
if settings.center_choice.value == C_SELF:
temp.remove(settings.center_object_name)
result += temp
result += [self.add_object_button, self.spacer_2]
for settings in self.bin_counts:
result += [settings.wants_scaled, settings.bin_count]
if not settings.wants_scaled:
result += [settings.maximum_radius]
if settings.can_remove:
result += [settings.remover]
result += [self.add_bin_count_button, self.spacer_3]
for settings in self.heatmaps:
if hasattr(settings, "divider"):
result.append(settings.divider)
if settings.image_name.is_visible():
result.append(settings.image_name)
if settings.object_name.is_visible():
result.append(settings.object_name)
if len(self.bin_counts) > 1:
result.append(settings.bin_count)
result += [
settings.measurement,
settings.colormap,
settings.wants_to_save_display,
]
if settings.wants_to_save_display:
result.append(settings.display_name)
result.append(settings.remover)
result += [self.add_heatmap_button]
return result
def prepare_settings(self, setting_values):
image_count, objects_count, bin_counts_count, heatmap_count = [
int(x) for x in setting_values[:4]
]
for sequence, add_fn, count in (
(self.images, self.add_image, image_count),
(self.objects, self.add_object, objects_count),
(self.bin_counts, self.add_bin_count, bin_counts_count),
(self.heatmaps, self.add_heatmap, heatmap_count),
):
while len(sequence) > count:
del sequence[-1]
while len(sequence) < count:
add_fn()
def run(self, workspace):
header = (
"Image",
"Objects",
"Bin # (innermost=1)",
"Bin count",
"Fraction",
"Intensity",
"COV",
)
stats = []
d = {}
for image in self.images:
for o in self.objects:
for bin_count_settings in self.bin_counts:
stats += self.do_measurements(
workspace,
image.image_name.value,
o.object_name.value,
o.center_object_name.value
if o.center_choice != C_SELF
else None,
o.center_choice.value,
bin_count_settings,
d,
)
if self.wants_zernikes != Z_NONE:
self.calculate_zernikes(workspace)
if self.show_window:
workspace.display_data.header = header
workspace.display_data.stats = stats
workspace.display_data.heatmaps = []
for heatmap in self.heatmaps:
heatmap_img = d.get(id(heatmap))
if heatmap_img is not None:
if self.show_window or heatmap.wants_to_save_display:
labels = workspace.object_set.get_objects(
heatmap.object_name.get_objects_name()
).segmented
if self.show_window:
workspace.display_data.heatmaps.append((heatmap_img, labels != 0))
if heatmap.wants_to_save_display:
colormap = heatmap.colormap.value
if colormap == matplotlib.cm.gray.name:
output_pixels = heatmap_img
else:
if colormap == cellprofiler.setting.DEFAULT:
colormap = cellprofiler.preferences.get_default_colormap()
cm = matplotlib.cm.ScalarMappable(cmap=colormap)
output_pixels = cm.to_rgba(heatmap_img)[:, :, :3]
output_pixels[labels == 0, :] = 0
parent_image = workspace.image_set.get_image(
heatmap.image_name.get_image_name()
)
output_img = cellprofiler.image.Image(
output_pixels, parent_image=parent_image
)
img_name = heatmap.display_name.value
workspace.image_set.add(img_name, output_img)
def display(self, workspace, figure):
header = workspace.display_data.header
stats = workspace.display_data.stats
n_plots = len(workspace.display_data.heatmaps) + 1
n_vert = int(numpy.sqrt(n_plots))
n_horiz = int(numpy.ceil(float(n_plots) / n_vert))
figure.set_subplots((n_horiz, n_vert))
figure.subplot_table(0, 0, stats, col_labels=header)
idx = 1
sharexy = None
for heatmap, (heatmap_img, mask) in zip(
self.heatmaps, workspace.display_data.heatmaps
):
heatmap_img = numpy.ma.array(heatmap_img, mask=~mask)
if heatmap_img is not None:
title = "{} {} {}".format(
heatmap.image_name.get_image_name(),
heatmap.object_name.get_objects_name(),
heatmap.measurement.value,
)
x = idx % n_horiz
y = int(idx / n_horiz)
colormap = heatmap.colormap.value
if colormap == cellprofiler.setting.DEFAULT:
colormap = cellprofiler.preferences.get_default_colormap()
if sharexy is None:
sharexy = figure.subplot_imshow(
x,
y,
heatmap_img,
title=title,
colormap=colormap,
normalize=False,
vmin=numpy.min(heatmap_img),
vmax=numpy.max(heatmap_img),
colorbar=True,
)
else:
figure.subplot_imshow(
x,
y,
heatmap_img,
title=title,
colormap=colormap,
colorbar=True,
normalize=False,
vmin=numpy.min(heatmap_img),
vmax=numpy.max(heatmap_img),
sharexy=sharexy,
)
idx += 1
def do_measurements(
self,
workspace,
image_name,
object_name,
center_object_name,
center_choice,
bin_count_settings,
dd,
):
"""Perform the radial measurements on the image set
workspace - workspace that holds images / objects
image_name - make measurements on this image
object_name - make measurements on these objects
center_object_name - use the centers of these related objects as
the centers for radial measurements. None to use the
objects themselves.
center_choice - the user's center choice for this object:
C_SELF, C_CENTERS_OF_OBJECTS or C_EDGES_OF_OBJECTS.
bin_count_settings - the bin count settings group
d - a dictionary for saving reusable partial results
returns one statistics tuple per ring.
"""
bin_count = bin_count_settings.bin_count.value
wants_scaled = bin_count_settings.wants_scaled.value
maximum_radius = bin_count_settings.maximum_radius.value
image = workspace.image_set.get_image(image_name, must_be_grayscale=True)
objects = workspace.object_set.get_objects(object_name)
labels, pixel_data = cellprofiler.object.crop_labels_and_image(
objects.segmented, image.pixel_data
)
nobjects = numpy.max(objects.segmented)
measurements = workspace.measurements
heatmaps = {}
for heatmap in self.heatmaps:
if (
heatmap.object_name.get_objects_name() == object_name
and image_name == heatmap.image_name.get_image_name()
and heatmap.get_number_of_bins() == bin_count
):
dd[id(heatmap)] = heatmaps[
MEASUREMENT_ALIASES[heatmap.measurement.value]
] = numpy.zeros(labels.shape)
if nobjects == 0:
for bin_index in range(1, bin_count + 1):
for feature in (F_FRAC_AT_D, F_MEAN_FRAC, F_RADIAL_CV):
feature_name = (feature + FF_GENERIC) % (
image_name,
bin_index,
bin_count,
)
measurements.add_measurement(
object_name,
"_".join([M_CATEGORY, feature_name]),
numpy.zeros(0),
)
if not wants_scaled:
measurement_name = "_".join(
[M_CATEGORY, feature, image_name, FF_OVERFLOW]
)
measurements.add_measurement(
object_name, measurement_name, numpy.zeros(0)
)
return [(image_name, object_name, "no objects", "-", "-", "-", "-")]
name = (
object_name
if center_object_name is None
else "{}_{}".format(object_name, center_object_name)
)
if name in dd:
normalized_distance, i_center, j_center, good_mask = dd[name]
else:
d_to_edge = centrosome.cpmorphology.distance_to_edge(labels)
if center_object_name is not None:
#
# Use the center of the centering objects to assign a center
# to each labeled pixel using propagation
#
center_objects = workspace.object_set.get_objects(center_object_name)
center_labels, cmask = cellprofiler.object.size_similarly(
labels, center_objects.segmented
)
pixel_counts = centrosome.cpmorphology.fixup_scipy_ndimage_result(
scipy.ndimage.sum(
numpy.ones(center_labels.shape),
center_labels,
numpy.arange(
1, numpy.max(center_labels) + 1, dtype=numpy.int32
),
)
)
good = pixel_counts > 0
i, j = (
centrosome.cpmorphology.centers_of_labels(center_labels) + 0.5
).astype(int)
ig = i[good]
jg = j[good]
lg = numpy.arange(1, len(i) + 1)[good]
if center_choice == C_CENTERS_OF_OTHER:
#
# Reduce the propagation labels to the centers of
# the centering objects
#
center_labels = numpy.zeros(center_labels.shape, int)
center_labels[ig, jg] = lg
cl, d_from_center = centrosome.propagate.propagate(
numpy.zeros(center_labels.shape), center_labels, labels != 0, 1
)
#
# Erase the centers that fall outside of labels
#
cl[labels == 0] = 0
#
# If objects are hollow or crescent-shaped, there may be
# objects without center labels. As a backup, find the
# center that is the closest to the center of mass.
#
missing_mask = (labels != 0) & (cl == 0)
missing_labels = numpy.unique(labels[missing_mask])
if len(missing_labels):
all_centers = centrosome.cpmorphology.centers_of_labels(labels)
missing_i_centers, missing_j_centers = all_centers[
:, missing_labels - 1
]
di = missing_i_centers[:, numpy.newaxis] - ig[numpy.newaxis, :]
dj = missing_j_centers[:, numpy.newaxis] - jg[numpy.newaxis, :]
missing_best = lg[numpy.argsort(di * di + dj * dj)[:, 0]]
best = numpy.zeros(numpy.max(labels) + 1, int)
best[missing_labels] = missing_best
cl[missing_mask] = best[labels[missing_mask]]
#
# Now compute the crow-flies distance to the centers
# of these pixels from whatever center was assigned to
# the object.
#
iii, jjj = numpy.mgrid[0 : labels.shape[0], 0 : labels.shape[1]]