Exemplo n.º 1
0
def test_rectangle():
    fixture = get_fixture("subpixel_rectangle.roi")
    with fixture.open("rb") as f:
        rect = ijroi.read_roi(f)
    assert (rect == np.array([[5, 4], [5, 8], [10, 8], [10, 4]])).all()
    assert rect.dtype == np.float32

    fixture = get_fixture("integer_rectangle.roi")
    with fixture.open("rb") as f:
        rect = ijroi.read_roi(f)
    assert (rect == np.array([[5, 4], [5, 8], [10, 8], [10, 4]])).all()
    assert rect.dtype == np.int16
Exemplo n.º 2
0
def test_rectangle():
    fixture = get_fixture("subpixel_rectangle.roi")
    with fixture.open("rb") as f:
        rect = ijroi.read_roi(f)
    assert (rect == np.array([[5, 4], [5, 8], [10, 8], [10, 4]])).all()
    assert rect.dtype == np.float32

    fixture = get_fixture("integer_rectangle.roi")
    with fixture.open("rb") as f:
        rect = ijroi.read_roi(f)
    assert (rect == np.array([[5, 4], [5, 8], [10, 8], [10, 4]])).all()
    assert rect.dtype == np.int16
Exemplo n.º 3
0
def test_polygon():
    fixture = get_fixture("polygon_circle.roi")
    with fixture.open("rb") as f:
        circle = ijroi.read_roi(f)
    assert len(circle) == 100
    assert abs(circle[:, 1].mean()-10) < 0.01
    assert abs(circle[:, 0].mean()-15) < 0.01

    fixture = get_fixture("polygon_integer.roi")
    with fixture.open("rb") as f:
        polyint = ijroi.read_roi(f)
    assert len(polyint) == 3
    assert all(polyint[2, :] == [1, 10])
    assert polyint.dtype == np.int16
Exemplo n.º 4
0
def test_polygon():
    fixture = get_fixture("polygon_circle.roi")
    with fixture.open("rb") as f:
        circle = ijroi.read_roi(f)
    assert len(circle) == 100
    assert abs(circle[:, 1].mean()-10) < 0.01
    assert abs(circle[:, 0].mean()-15) < 0.01

    fixture = get_fixture("polygon_integer.roi")
    with fixture.open("rb") as f:
        polyint = ijroi.read_roi(f)
    assert len(polyint) == 3
    assert all(polyint[2, :] == [1, 10])
    assert polyint.dtype == np.int16
Exemplo n.º 5
0
def test_freehand_circle():
    fixture = get_fixture("freehand_circle.roi")
    with fixture.open("rb") as f:
        circle = ijroi.read_roi(f)
    assert len(circle) == 100
    assert abs(circle[:, 1].mean()-10) < 0.01
    assert abs(circle[:, 0].mean()-15) < 0.01
Exemplo n.º 6
0
def test_freehand_circle():
    fixture = get_fixture("freehand_circle.roi")
    with fixture.open("rb") as f:
        circle = ijroi.read_roi(f)
    assert len(circle) == 100
    assert abs(circle[:, 1].mean()-10) < 0.01
    assert abs(circle[:, 0].mean()-15) < 0.01
Exemplo n.º 7
0
def test_integer_freehand():
    fixture = get_fixture("freehand_integer.roi")
    with fixture.open("rb") as f:
        freehand = ijroi.read_roi(f)
    assert len(freehand) == 3
    assert all(freehand[2, :] == [1, 10])
    assert freehand.dtype == np.int16
Exemplo n.º 8
0
def test_float_point():
    fixture = get_fixture("float_point.roi")
    with fixture.open("rb") as f:
        point = ijroi.read_roi(f)
    assert point.ndim == 2
    assert abs(point[0,0] - 567.8) < 0.01
    assert abs(point[0,1] - 123.4) < 0.01
Exemplo n.º 9
0
def test_point():
    fixture = get_fixture("int_point.roi")
    with fixture.open("rb") as f:
        point = ijroi.read_roi(f)
    assert point.ndim == 2
    assert point[0,0] == 256
    assert point[0,1] == 128
Exemplo n.º 10
0
def test_point():
    fixture = get_fixture("int_point.roi")
    with fixture.open("rb") as f:
        point = ijroi.read_roi(f)
    assert point.ndim == 2
    assert point[0, 0] == 256
    assert point[0, 1] == 128
Exemplo n.º 11
0
def test_float_point():
    fixture = get_fixture("float_point.roi")
    with fixture.open("rb") as f:
        point = ijroi.read_roi(f)
    assert point.ndim == 2
    assert abs(point[0, 0] - 567.8) < 0.01
    assert abs(point[0, 1] - 123.4) < 0.01
Exemplo n.º 12
0
def test_integer_freehand():
    fixture = get_fixture("freehand_integer.roi")
    with fixture.open("rb") as f:
        freehand = ijroi.read_roi(f)
    assert len(freehand) == 3
    assert all(freehand[2, :] == [1, 10])
    assert freehand.dtype == np.int16
Exemplo n.º 13
0
def test_oval_points_center_diam():
    fixture = get_fixture("16x16_centered_spanning_oval.roi")
    with fixture.open("rb") as f:
        points = ijroi.read_roi(f)

    center, diam = ijroi.oval_points_center_diam(points)
    assert np.array_equal(center, np.array((8, 8)))
    assert diam == 16
 def parse_ij_roi(self, path, pixel_size):
     with open(path, "rb") as f:
         r = ijroi.read_roi(f)
     # extract top left and bottom right of roi
     # reorganise to make a list of x0, y0, x1, y1, id
     roi_df = pd.DataFrame([[r[0,1].astype('float'),r[0,0].astype('float'),\
             r[2,1].astype('float'),r[2,0].astype('float')]]) * pixel_size
     roi_df.columns = [
         'x0 [pixels]', 'y0 [pixels]', 'x1 [pixels]', 'y1 [pixels]'
     ]
     return roi_df
Exemplo n.º 15
0
def generate_roi_file():
    roi_files = glob.glob(os.path.join(ROI_DIR, '**/*.roi', recursive=True))
    with open(ROI_BBOX_FILE, 'w') as out:
        for roi_file in roi_files:
            with open(roi_file, "rb") as f:
                roi = ijroi.read_roi(f)
                out.write(
                    roi_file.replace("roi/", "").replace(".roi", ".jpg") +
                    ", ")
                out.write(", ".join(map(str, roi[0][::-1])) + ", ")
                out.write(", ".join(map(str, roi[2][::-1])) + ", ")
                out.write("cervix\n")
def import_ij_rois(basename, roipath):

    rois = []
    for filename in os.listdir(roipath):
        if ('.roi' in filename) and (basename in filename):
            fpath = os.path.join(roipath, filename)
            print('roi path: ', fpath)
            with open(fpath, "rb") as f:
                r = ijroi.read_roi(f)
            # extract top left and bottom right of roi
            # reorganise to make a list of x0, y0, x1, y1
            roi = [r[0,1].astype('float'),r[0,0].astype('float'),\
                    r[2,1].astype('float'),r[2,0].astype('float')]
            rois.append(roi)
            localisations
    return rois
Exemplo n.º 17
0
def _convert_from_roi(fname):
    """Convert a roi file to a numpy array [x, y, h, w].

    Parameters
    ----------
    fname : string
        If ends with `.roi`, we assume a full path is given

    """
    with open(fname, 'rb') as f:
        roi = ijroi.read_roi(f)
        top, left = roi[0]
        bottom, right = roi[2]
        height, width = bottom - top, right - left

        return np.array([top, left, height, width])
Exemplo n.º 18
0
    def get_polygons_ijroi(self, ij_rois_fp):
        """Short summary.

        Parameters
        ----------
        ij_rois_fp : str
            Filepath to an ImageJ ROI file


        Returns
        -------
        list
            Python list of polygon verteces as numpy arrays

        """
        fn, fe = os.path.splitext(ij_rois_fp)
        print(fe)
        if fe == '.zip':
            rois = ijroi.read_roi_zip(ij_rois_fp)
        if fe == '.roi':
            rois = ijroi.read_roi(open(ij_rois_fp, "rb"))
        polyallcoords = [poly[1] for poly in rois]
        self.polygons = polyallcoords
Exemplo n.º 19
0
    return im.size


if __name__ == '__main__':
    import sys
    from PIL import Image
    import ijroi

    TARGET_SIZE = (299, 299)

    if len(sys.argv) != 3:
        print(
            "Take a list of .roi files that were created over the original (non-resized non-cropped) dataset and fix them to fit our 299x299 dataset format."
        )
        print("Example usage:")
        print(
            " $ ls path/to/large/.rois | python3 roi.py path/to/folder/with/images target/path"
        )
        sys.exit()
    rois_to_fix = [roi.strip() for roi in sys.stdin]
    img_dir, output_dir = sys.argv[1:]

    for roi in rois_to_fix:
        base_name = roi[roi.rfind('/') + 1:-len('.roi')]
        with open(roi, "rb") as f:
            bb = ijroi.read_roi(f)
        original_dims = get_img_dims(img_dir + '/' + base_name + '.jpg')
        bb_resized = downsize_bb(bb, original_dims, TARGET_SIZE)
        with open(output_dir + '/' + base_name + '.roi', "wb+") as f:
            write_bb(f, bb_resized)
Exemplo n.º 20
0
def load_ij_roi(filename):
    import ijroi
    with open(filename, "rb") as fh:
        return ijroi.read_roi(fh).astype(int)
def ROI2binaryimage(input_folder,output_folder,size):

    compstruct = scipy.ndimage.generate_binary_structure(2, 2) # Mask for image dilation.
    normal_color = 4294901760 # Stroke color (chosen by me) for normal cells.
    stressed_color = 4278255360 # Stroke color (chosen by me) for stressed cells.

    # Create the result folders if they don't exist.
    # In the outputfolder as given to ROI2binaryimage, a folder is created named
    # 'Manual_segmentation_results'. In this folder, two subfolders are created;
    # 'Original_images' as well as 'Manual_segmentation'.
    if not(os.path.isdir(os.path.join(output_folder, "Manual_segmentation_results"))):
        os.makedirs(os.path.join(output_folder, "Manual_segmentation_results"))
        os.makedirs(os.path.join(output_folder, "Manual_segmentation_results",
                                 "Original_images"))
        os.makedirs(os.path.join(output_folder, "Manual_segmentation_results",
                                 "Manual_segmentations"))

    # Ignoring hidden folders such as .DS_store in Mac, find folders for images + rois.
    for folder in [p for p in os.listdir(input_folder) if not(p.startswith('.'))]:

        blank = np.zeros(size, dtype=np.int8)  # The image size
        canvas = [np.copy(blank), np.copy(blank)]  # Prep for background.
        overlap = [np.copy(blank), np.copy(blank)]  # Prep for the later overlapping images.

        # Find the original image and save it to the new location; also save its name.
        for image in [i for i in os.listdir(os.path.join(input_folder, folder)) if i
                .endswith('.tif')]:
            if not (np.all(size == list(np.asarray(misc.imread(os.path.join(input_folder,folder,image))).shape))):
                raise ValueError("Given/assumed size doesn't match image size")
            original_image_name = image
            shutil.copy2((os.path.join(input_folder, folder, image)),
                         (os.path.join(output_folder, "Manual_segmentation_results",
                                       "Original_images", image)))


        notif = original_image_name[0:-4]

        # Find all the .roi files in 'Roiset' and work with them.
        for file in [f for f in os.listdir(os.path.join(
                input_folder, folder, "Roiset")) if f.endswith('.roi')]:
            temp_canvas = [np.copy(blank),np.copy(blank)]

            with open((os.path.join(input_folder, folder, "Roiset", file)),"rb") as f:
                [roi,roi_color] = ijroi.read_roi(f)

            # Determine whether the points are valid (the roi has to fit in the given 'size')
            valid = np.logical_and(np.min(roi, axis=1) >= 0, roi[:,0] < size[0], roi[:,1] < size[1])
            valid_roi = roi[valid]
            x = valid_roi[:,0]
            y = valid_roi[:,1]


            # Differentiate between the normal and stressed cell rois.
            rr, cc = skimage.draw.polygon(x,y)
            if roi_color == normal_color:
                q = 0
            if roi_color == stressed_color:
                q = 1

            # Add roi to the image.
            canvas[q][rr,cc] = 1
            temp_canvas[q][rr,cc] = 1

            # Determine the overlap by adding the dilated version of the cell to the overlap file.
            # (This is to ensure the cells do not 'touch' as well as do not 'overlap').
            temp_canvas[q] = scipy.ndimage.binary_dilation(  # Dilate cell in all directions.
                temp_canvas[q], structure=compstruct).astype(temp_canvas[q].dtype)
            overlap[q] = overlap[q] + temp_canvas[q]


        # If there is an overlap of different cells, that area is set to 0.
        for ax in np.arange(size[0]):
            for ay in np.arange(size[1]):
                for i in range(len(overlap)):
                    if overlap[i][ax,ay] > 1:
                        canvas[i][ax,ay] = 0

        background = np.array([1 - np.clip((canvas[0]+canvas[1]), 0, 1)], ndmin=3, dtype=np.int8)

        image = np.array([canvas[0], canvas[1]])

        result = np.concatenate([background, image], axis=0)
        result = skimage.util.img_as_ubyte(result)

        imsave(os.path.join(output_folder, "Manual_segmentation_results",'Manual_segmentations',
            (notif + '.tif')), result)
    return None
Exemplo n.º 22
0
def ROI2binaryimage(input_folder, output_folder, size):

    compstruct = scipy.ndimage.generate_binary_structure(
        2, 2)  # Mask for image dilation.
    normal_color = 4294901760  # Stroke color (chosen by me) for normal cells.
    stressed_color = 4278255360  # Stroke color (chosen by me) for stressed cells.

    # Create the result folders if they don't exist.
    # In the outputfolder as given to ROI2binaryimage, a folder is created named
    # 'Manual_segmentation_results'. In this folder, two subfolders are created;
    # 'Original_images' as well as 'Manual_segmentation'.
    if not (os.path.isdir(
            os.path.join(output_folder, "Manual_segmentation_results"))):
        os.makedirs(os.path.join(output_folder, "Manual_segmentation_results"))
        os.makedirs(
            os.path.join(output_folder, "Manual_segmentation_results",
                         "Original_images"))
        os.makedirs(
            os.path.join(output_folder, "Manual_segmentation_results",
                         "Manual_segmentations"))

    # Ignoring hidden folders such as .DS_store in Mac, find folders for images + rois.
    for folder in [
            p for p in os.listdir(input_folder) if not (p.startswith('.'))
    ]:

        blank = np.zeros(size, dtype=np.int8)  # The image size
        canvas = [np.copy(blank), np.copy(blank)]  # Prep for background.
        overlap = [np.copy(blank),
                   np.copy(blank)]  # Prep for the later overlapping images.

        # Find the original image and save it to the new location; also save its name.
        for image in [
                i for i in os.listdir(os.path.join(input_folder, folder))
                if i.endswith('.tif')
        ]:
            if not (np.all(size == list(
                    np.asarray(
                        misc.imread(os.path.join(input_folder, folder,
                                                 image))).shape))):
                raise ValueError("Given/assumed size doesn't match image size")
            original_image_name = image
            shutil.copy2(
                (os.path.join(input_folder, folder, image)),
                (os.path.join(output_folder, "Manual_segmentation_results",
                              "Original_images", image)))

        notif = original_image_name[0:-4]

        # Find all the .roi files in 'Roiset' and work with them.
        for file in [
                f for f in os.listdir(
                    os.path.join(input_folder, folder, "Roiset"))
                if f.endswith('.roi')
        ]:
            temp_canvas = [np.copy(blank), np.copy(blank)]

            with open((os.path.join(input_folder, folder, "Roiset", file)),
                      "rb") as f:
                [roi, roi_color] = ijroi.read_roi(f)

            # Determine whether the points are valid (the roi has to fit in the given 'size')
            valid = np.logical_and(
                np.min(roi, axis=1) >= 0, roi[:, 0] < size[0],
                roi[:, 1] < size[1])
            valid_roi = roi[valid]
            x = valid_roi[:, 0]
            y = valid_roi[:, 1]

            # Differentiate between the normal and stressed cell rois.
            rr, cc = skimage.draw.polygon(x, y)
            if roi_color == normal_color:
                q = 0
            if roi_color == stressed_color:
                q = 1

            # Add roi to the image.
            canvas[q][rr, cc] = 1
            temp_canvas[q][rr, cc] = 1

            # Determine the overlap by adding the dilated version of the cell to the overlap file.
            # (This is to ensure the cells do not 'touch' as well as do not 'overlap').
            temp_canvas[
                q] = scipy.ndimage.binary_dilation(  # Dilate cell in all directions.
                    temp_canvas[q],
                    structure=compstruct).astype(temp_canvas[q].dtype)
            overlap[q] = overlap[q] + temp_canvas[q]

        # If there is an overlap of different cells, that area is set to 0.
        for ax in np.arange(size[0]):
            for ay in np.arange(size[1]):
                for i in range(len(overlap)):
                    if overlap[i][ax, ay] > 1:
                        canvas[i][ax, ay] = 0

        background = np.array([1 - np.clip((canvas[0] + canvas[1]), 0, 1)],
                              ndmin=3,
                              dtype=np.int8)

        image = np.array([canvas[0], canvas[1]])

        result = np.concatenate([background, image], axis=0)
        result = skimage.util.img_as_ubyte(result)

        imsave(
            os.path.join(output_folder, "Manual_segmentation_results",
                         'Manual_segmentations', (notif + '.tif')), result)
    return None
Exemplo n.º 23
0
import ijroi
import numpy as np

rootDir = '/Users/yanzhexu/Desktop/Research/GBM/aCGH_whole_tumor_maps_for_Neuro-Onc_dataset/CEFSL_slices_only/slice22/ROI for +C_3D_AXIAL_IRSPGR_Fast_IM-0005-0022.roi'

with open(rootDir, "rb") as file:
    roi = ijroi.read_roi(file)

print isinstance(roi, np.ndarray)