示例#1
0
def saveResult(save_path, nparray, polygons, source_dir_list, prefix=''):
    if not os.path.exists(save_path):
        os.makedirs(save_path)

    for (filename, image, poly) in zip(source_dir_list, nparray, polygons):
        imsave(
            os.path.join(save_path,
                         prefix + os.path.splitext(filename)[0] + '.tif'),
            image, polygons)
        export_imagej_rois(
            os.path.join(save_path, prefix + os.path.splitext(filename)[0]),
            poly['coord'])
示例#2
0
    def _predict_stardist(self, model, file, T, channel, prob_thresh,
                          nms_thresh, out_dir):

        axes = 'TCYX'
        # if T.ndim==3:
        #     timelapse = T
        if T.ndim == 4:
            timelapse = T[:, channel]
        else:
            raise ValueError(
                'Data has unexpected number of dimensions. Weird.')

        # normalise
        print(f'Normalizing each frame to run Stardist', flush=True)
        timelapse = np.stack(
            [normalize(frame, 1, 99.8) for frame in timelapse])
        print(
            f"Timelapse has axes {axes.replace('C','')} with shape {timelapse.shape}"
        )

        polygons = [
            model.predict_instances(frame,
                                    nms_thresh=nms_thresh,
                                    prob_thresh=prob_thresh)[1]
            for frame in tqdm(timelapse)
        ]

        if prob_thresh is None:
            prob_string = 'default'
        else:
            prob_string = f'{prob_thresh:.2f}'

        if nms_thresh is None:
            nms_string = 'default'
        else:
            nms_string = f'{nms_thresh:.2f}'

        roi_path = out_dir / f"{file.stem}_prob={prob_string}_nms={nms_string}"
        roi_path.parent.mkdir(parents=True, exist_ok=True)
        rois_python = Path(str(roi_path) + '.npz')
        rois_imagej = Path(str(roi_path) + '.zip')

        print(f'Saving ImageJ ROIs to {rois_imagej}')
        export_imagej_rois(str(rois_imagej),
                           [poly['coord'] for poly in polygons])

        print(f'Saving Python rois to {rois_python}')
        np.savez(
            str(rois_python),
            coord=[p['coord'] for p in polygons],
            points=[p['points'] for p in polygons],
            prob=[p['prob'] for p in polygons],
        )
示例#3
0
                                         flow_threshold=None,
                                         channels=channels,
                                         net_avg=net_avg)

for one_mask, image_file in zip(masks, image_files):
    polygons = []

    slices = find_objects(one_mask.astype(int))
    for i, si in enumerate(slices):
        if si is not None:
            coords = [[], []]
            sr, sc = si
            mask = (one_mask[sr, sc] == (i + 1)).astype(np.uint8)
            contours = cv.findContours(mask, cv.RETR_EXTERNAL,
                                       cv.CHAIN_APPROX_NONE)
            pvc, pvr = np.concatenate(contours[-2], axis=0).squeeze().T
            vr, vc = pvr + sr.start, pvc + sc.start
            coords[0] = vr
            coords[1] = vc

            #sub_polygons.append(coords)
            polygons.append(coords)

    roi_path = image_folder / 'rois' / (str(image_file.name) + '_rois')
    roi_path.parent.mkdir(exist_ok=True)

    print('    Exporting Polygons')
    export_imagej_rois(roi_path, [polygons])

print('Script Finished!')
示例#4
0
model = StarDist2D(None, name=model_name, basedir=model_folder)

# Read All Images
image_files = sorted(image_folder.glob('*.tif'))

# Normalize Images and predict
for image_file in image_files:
    print('Processing Image: ', str(image_file.name), '...')

    image = imread(str(image_file))
    if (is_norm_provided):
        norm = normalize_mi_ma(image, min, max)
    else:
        norm = normalize(image, 1, 99.8, axis=(0, 1))

    labels, polygons = model.predict_instances(norm,
                                               prob_thresh=prob_thresh,
                                               nms_thresh=nms_thresh)

    # Create a 'rois' folder inside the same directory and make sure that
    # the images are saved with the same name as the image (with extension), with suffix `_rois.zip`

    roi_path = image_folder / 'rois' / (str(image_file.name) + '_rois')
    roi_path.parent.mkdir(exist_ok=True)

    if (polygons['coord'].shape[0] > 0):
        print('Exporting Polygons')
        export_imagej_rois(roi_path, polygons['coord'])

print('Script Finished!')