Beispiel #1
0
    def test_get_region_dict(self):

        ts = large_image.getTileSource(
            os.path.join(utilities.externaldata('data/Easy1.png.sha512')))

        result = cli_utils.get_region_dict([-1, -1, -1, -1], 2000, ts)
        expected = {}
        assert result == expected, "Expected {}, got {}".format(
            expected, result)

        result = cli_utils.get_region_dict([100, 110, 250, 240], 500, ts)
        expected = dict(region=dict(left=100, top=110, width=250, height=240))
        assert result == expected, "Expected {}, got {}".format(
            expected, result)
Beispiel #2
0
    def test_get_region_dict(self):

        ts = large_image.getTileSource(os.path.join(TEST_DATA_DIR,
                                                    'Easy1.png'))

        result = cli_utils.get_region_dict([-1, -1, -1, -1], 2000, ts)
        expected = {}
        assert result == expected, "Expected {}, got {}".format(
            expected, result)

        result = cli_utils.get_region_dict([100, 110, 250, 240], 500, ts)
        expected = dict(region=dict(left=100, top=110, width=250, height=240))
        assert result == expected, "Expected {}, got {}".format(
            expected, result)
Beispiel #3
0
def main(args):

    # Read Input Image
    print('>> Reading input image')

    print(args.inputImageFile)

    ts = large_image.getTileSource(args.inputImageFile)

    im_input = ts.getRegion(format=large_image.tilesource.TILE_FORMAT_NUMPY,
                            **utils.get_region_dict(args.region,
                                                    args.maxRegionSize, ts))[0]

    # Create stain matrix
    print('>> Creating stain matrix')

    w = utils.get_stain_matrix(args)
    print(w)

    # Perform color deconvolution
    print('>> Performing color deconvolution')
    im_stains = htk_cd.color_deconvolution(im_input, w).Stains

    # write stain images to output
    print('>> Outputting individual stain images')

    print(args.outputStainImageFile_1)
    skimage.io.imsave(args.outputStainImageFile_1, im_stains[:, :, 0])

    print(args.outputStainImageFile_2)
    skimage.io.imsave(args.outputStainImageFile_2, im_stains[:, :, 1])

    print(args.outputStainImageFile_3)
    skimage.io.imsave(args.outputStainImageFile_3, im_stains[:, :, 2])
Beispiel #4
0
def main(args):
    utils.create_dask_client(args)
    ts = large_image.getTileSource(args.inputImageFile)
    make_label_image = getattr(args, 'outputLabelImage', None) is not None
    region = utils.get_region_dict(
        args.region,
        *(args.maxRegionSize, ts) if make_label_image else ()).get('region')
    ppc_params = ppc.Parameters(
        **{k: getattr(args, k)
           for k in ppc.Parameters._fields})
    results = ppc.count_slide(
        args.inputImageFile,
        ppc_params,
        region,
        args.tile_grouping,
        make_label_image,
    )
    if make_label_image:
        stats, label_image = results
        # Colorize label image.  Colors from the "coolwarm" color map
        color_map = np.empty((4, 3), dtype=np.uint8)
        color_map[ppc.Labels.NEGATIVE] = 255
        color_map[ppc.Labels.WEAK] = 60, 78, 194
        color_map[ppc.Labels.PLAIN] = 221, 220, 220
        color_map[ppc.Labels.STRONG] = 180, 4, 38
        # Cleverly index color_map
        label_image = color_map[label_image]
        try:
            skimage.io.imsave(args.outputLabelImage, label_image)
        except ValueError:
            # This is likely caused by an unknown extension, so try again
            altname = args.outputLabelImage + '.png'
            skimage.io.imsave(altname, label_image)
            os.rename(altname, args.outputLabelImage)
    else:
        stats, = results
    with open(args.returnParameterFile, 'w') as f:
        for k, v in zip(stats._fields, stats):
            f.write(f'{k} = {v}\n')
def get_all_roi_masks_for_slide(
        input_img, input_ann, GTCODE_PATH, MASK_SAVEPATH, slide_name=None,
        verbose=True, monitorPrefix="", get_roi_mask_kwargs=dict()):
    """Parse annotations and saves ground truth masks for ALL ROIs.

    Get all ROIs in a single slide. This is a wrapper around get_roi_mask()
    which should be referred to for implementation details.

    Parameters
    -----------
    input_img : object
        input large image object
    input_ann : object
        input annotation object
    GTCODE_PATH : str
        path to the ground truth codes and information
        csv file. Refer to the docstring of get_roi_mask() for more info.
    MASK_SAVEPATH : str
        path to directory to save ROI masks
    slide_name (optional) : str
        If not given, it's inferred using a server request using girder client.
    verbose (optional) : bool
        Print progress to screen?
    monitorPrefix (optional) : str
        text to prepend to printed statements
    get_roi_mask_kwargs : dict
        extra kwargs for get_roi_mask()

    Returns
    --------
    list of strs
        save paths for ROIs

    """
    # read ground truth codes and information
    GTCodes = read_csv(GTCODE_PATH)
    GTCodes.index = GTCodes.loc[:, 'group']
    if any(GTCodes.loc[:, 'GT_code'] <= 0):
        raise Exception("All GT_code must be > 0")

    # get annotations for slide
    slide_annotations = input_ann

    # get bounding box information for all annotations
    element_infos = get_bboxes_from_slide_annotations(slide_annotations)

    # get indices of rois
    idxs_for_all_rois = _get_idxs_for_all_rois(
        GTCodes=GTCodes, element_infos=element_infos)

    savenames = []

    for roino, idx_for_roi in enumerate(idxs_for_all_rois):

        roicountStr = "%s: roi %d of %d" % (
            monitorPrefix, roino + 1, len(idxs_for_all_rois))

        # get roi mask and info
        ROI, roiinfo = get_roi_mask(
            slide_annotations=slide_annotations, element_infos=element_infos,
            GTCodes_df=GTCodes.copy(), idx_for_roi=idx_for_roi,
            monitorPrefix=roicountStr, **get_roi_mask_kwargs)

        ## make directory for the mask
        MASK_SAVEPATH_MASK = MASK_SAVEPATH + '/mask'
        # create folders if necessary
        for folder in [MASK_SAVEPATH_MASK, ]:
            try:
                os.mkdir(folder)
            except:
                pass

        # now save roi
        ROINAMESTR = "%s_left-%d_top-%d" % (
            slide_name, roiinfo['XMIN'], roiinfo['YMIN'])
        savename = os.path.join(MASK_SAVEPATH_MASK, ROINAMESTR + ".png")
        if verbose:
            print("%s: Saving %s\n" % (roicountStr, savename))
        imwrite(im=ROI, uri=savename)

        region = [roiinfo['XMIN'], roiinfo['YMIN'], roiinfo['BBOX_WIDTH'], roiinfo['BBOX_HEIGHT']]
        maxRegionSize = 5000

        ## make directory for the region
        MASK_SAVEPATH_REG = MASK_SAVEPATH + '/region'
        # create folders if necessary
        for folder in [MASK_SAVEPATH_REG, ]:
            try:
                os.mkdir(folder)
            except:
                pass

        #######save images
        im_input = input_img.getRegion(
            format=large_image.tilesource.TILE_FORMAT_NUMPY,
            **utils.get_region_dict(region, maxRegionSize, input_img))[0]

        ROINAMESTR1 = "%s_left-%d_top-%d" % (
            slide_name, roiinfo['XMIN'], roiinfo['YMIN'])
        savename1 = os.path.join(MASK_SAVEPATH_REG, ROINAMESTR1 + ".png")
        skimage.io.imsave(savename1, im_input)
        if verbose:
            print("%s: Saving %s\n" % (roicountStr, savename1))

        savenames.append(savename)

    return savenames