|
| 1 | +import os |
| 2 | + |
| 3 | +import imageio.v3 as imageio |
| 4 | +import napari |
| 5 | +import numpy as np |
| 6 | +import pandas as pd |
| 7 | + |
| 8 | +from scipy.ndimage import distance_transform_edt |
| 9 | +from skimage.measure import label |
| 10 | +from skimage.segmentation import watershed |
| 11 | + |
| 12 | + |
| 13 | +def simple_watershed(im, det, radius=8): |
| 14 | + """Use a simple watershed to create speheres. |
| 15 | + """ |
| 16 | + |
| 17 | + # Compute the distance to the detctions. |
| 18 | + seeds = np.zeros(im.shape, dtype="uint8") |
| 19 | + det_idx = tuple(det[ax].values for ax in ["axis-0", "axis-1", "axis-2"]) |
| 20 | + seeds[det_idx] = 1 |
| 21 | + distances = distance_transform_edt(seeds == 0, sampling=(3.0, 1.887779, 1.887779)) |
| 22 | + seeds = label(seeds) |
| 23 | + |
| 24 | + mask = distances < radius |
| 25 | + return watershed(distances, seeds, mask=mask), distances, seeds |
| 26 | + |
| 27 | + |
| 28 | +def complex_watershed(im, det, pred, radius=8): |
| 29 | + """More complex waterhsed in combination with network predictions. |
| 30 | +
|
| 31 | + WIP: this does not work well yet. |
| 32 | + """ |
| 33 | + fg_pred = pred[0] |
| 34 | + # bd_pred = pred[2] |
| 35 | + |
| 36 | + _, seeds, distances = simple_watershed(im, det, radius=radius) |
| 37 | + |
| 38 | + # Ensure everything within five 8 micron of a center is foreground |
| 39 | + fg = np.logical_or(fg_pred > 0.5, distances > radius) |
| 40 | + |
| 41 | + # TODO find a good hmap! |
| 42 | + hmap = distances |
| 43 | + |
| 44 | + # Watershed. |
| 45 | + seg = watershed(hmap, markers=seeds, mask=fg, compactness=5) |
| 46 | + return seg, distances, seeds |
| 47 | + |
| 48 | + |
| 49 | +def main(): |
| 50 | + root = "la-vision-sgn-new/detections-v1" |
| 51 | + im = imageio.imread(os.path.join(root, "LaVision-M04_crop_2580-2266-0533_PV.tif")) |
| 52 | + det = pd.read_csv(os.path.join(root, "LaVision-M04_crop_2580-2266-0533_PV.csv")) |
| 53 | + # pred = imageio.imread(os.path.join(root, "LaVision-M04_crop_2580-2266-0533_PRED.tif")) |
| 54 | + |
| 55 | + seg, distances, seeds = simple_watershed(im, det, radius=12) |
| 56 | + # This does not yet work well. |
| 57 | + # seg, distances, seeds = complex_watershed(im, det, pred) |
| 58 | + |
| 59 | + v = napari.Viewer() |
| 60 | + v.add_image(im) |
| 61 | + v.add_image(distances, visible=False) |
| 62 | + v.add_labels(seeds, visible=False) |
| 63 | + # v.add_image(pred, visible=False) |
| 64 | + v.add_points(det, visible=False) |
| 65 | + v.add_labels(seg) |
| 66 | + napari.run() |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + main() |
0 commit comments