Ejemplo n.º 1
0
    def test_not_existing_file(self):
        """
        Opening of not existing image.

        Checks if slideio throws RuntimeError
        exception during opening of not existing file.
        """
        image_path = "missing_file.png"
        with pytest.raises(RuntimeError):
            slideio.open_slide(image_path, "AFI")
Ejemplo n.º 2
0
    def test_not_existing_file(self):
        """
        Opening of not existing image.

        slideio shall throw RuntimeError
        exception during opening of not existing image.
        """
        image_path = "missing_file.png"
        with pytest.raises(RuntimeError):
            slideio.open_slide(image_path, "GDAL")
Ejemplo n.º 3
0
    def test_corrupted_image(self):
        """
        Raise an error for corrupted images.

        Tries to open and read a corrupted image.
        slideio shall raise an exception.
        """
        # Image to test
        image_path = get_test_image_path("czi", "corrupted.czi")
        with pytest.raises(RuntimeError):
            slideio.open_slide(image_path, "CZI")
Ejemplo n.º 4
0
    def test_core_not_existing_driver(self):
        """
        Test for calling of not-existing driver.

        Checks if slideio throws RuntimeError
        exception during opening of not existing file.
        """
        image_path = get_test_image_path(
            "GDAL", "img_2448x2448_3x8bit_SRC_RGB_ducks.png")
        with pytest.raises(RuntimeError):
            slideio.open_slide(image_path, "AAAA")
Ejemplo n.º 5
0
    def test_jpegxr_rgb_regression(self):
        """
        Regression test for rgb jpegxr compressed image.

        Read the block from a slide and compares it
        with a reference image. The reference image
        is obtained by reading of the same region
        by the slideo and saving it as png file.
        """
        image_name = "jxr-rgb-5scenes.czi"
        folder = "czi"
        driver = "CZI"
        ext = ".png"
        # Image to test
        image_path = get_test_image_path(folder, image_name)
        rect = (4000, 2000, 1000, 800)
        new_size = (250, 200)
        scene_index = 2
        # export_image_region(folder,
        #                    image_name, driver, scene_index,
        #                    rect, new_size, ext
        #                    )
        slide = slideio.open_slide(image_path, driver)
        scene = slide.get_scene(scene_index)

        for channel_index in range(scene.num_channels):
            image_raster = scene.read_block(rect,
                                            new_size,
                                            channel_indices=[channel_index])
            regr_image_path = get_regression_image_path(
                folder, image_name, scene_index, channel_index, rect, ext)
            reference_image = cv.imread(regr_image_path, cv.IMREAD_UNCHANGED)
            self.assertTrue(np.array_equal(image_raster, reference_image))
Ejemplo n.º 6
0
    def test_jpegxr_rgb_resample_block(self):
        """
        Read a block of rgb jpegxr compressed image.

        Read the block from a slide and compares it
        with a reference image.
        """
        # Image to test
        image_path = get_test_image_path("czi", "jxr-rgb-5scenes.czi")
        # Reference channel images
        ref_image_paths = get_test_image_path(
            "czi",
            "jxr-rgb-5scenes/jxr-rgb-5scenes_s3_x2500_y3000_w400_h600.png")

        scaling_params = {1.0: 0.99, 1.5: 0.94, 2.0: 0.92, 3.0: 0.85}

        reference_image = cv.imread(ref_image_paths)
        slide = slideio.open_slide(image_path, "CZI")
        scene = slide.get_scene(3)
        # check accuracy of resizing for different scale coeeficients
        for resize_cof, thresh in scaling_params.items():
            new_size = (int(round(reference_image.shape[1] / resize_cof)),
                        int(round(reference_image.shape[0] // resize_cof)))
            reference_raster = cv.resize(reference_image, new_size)
            image_raster = scene.read_block((2500, 3000, 400, 600),
                                            size=new_size,
                                            channel_indices=[0, 1, 2])
            scores_cf = cv.matchTemplate(reference_raster, image_raster,
                                         cv.TM_CCOEFF_NORMED)[0][0]
            self.assertLess(thresh, scores_cf)
Ejemplo n.º 7
0
    def test_readblock_png8bit_with(self):
        """
        8 bit png image.

        Reads 8b png images and checks the raster.
        by calculation of raster statistics for
        specific rectangles
        """
        image_path = get_test_image_path(
            "gdal",
            "img_1024x600_3x8bit_RGB_color_bars_CMYKWRGB.png"
            )
            
        with slideio.open_slide(image_path, "GDAL") as slide:
            self.assertTrue(slide is not None)
            with slide.get_scene(0) as scene:
                block_rect = (260, 500, 100, 100)
                # read 3 channel block
                raster = scene.read_block(block_rect)
                mean, stddev = cv.meanStdDev(raster)
                self.assertEqual(mean[0], 255)
                self.assertEqual(stddev[0], 0)
                self.assertEqual(mean[1], 255)
                self.assertEqual(stddev[1], 0)
                self.assertEqual(mean[2], 0)
                self.assertEqual(stddev[2], 0)
                # read one channel block
                raster = scene.read_block(block_rect, channel_indices=[1])
                mean, stddev = cv.meanStdDev(raster)
                self.assertEqual(mean[0], 255)
                self.assertEqual(stddev[0], 0)
Ejemplo n.º 8
0
    def test_jpegxr_16b_read_block(self):
        """
        Read a block of jpegxr compressed 16 bit image.

        Reads a block from a slide and compares it
        with a block read by czifile package.
        Small deviations can be explained by different
        order in processing of tiles. Czi file contains
        overlapped tiles. Rasters can be slightly different
        in the overlapped areas (depends of tile order).
        """
        # Image to test
        image_path = get_test_image_path("czi", "jxr-16bit-4chnls.czi")
        slide = slideio.open_slide(image_path, "CZI")
        self.assertTrue(slide is not None)
        scene = slide.get_scene(0)
        self.assertTrue(scene is not None)
        image_raster = scene.read_block()
        reference_raster = np.transpose(
            czi.imread(image_path)[0, 0, 0, :, :, :, 0], (1, 2, 0))
        image_raster = image_raster[:, :, 0]
        reference_raster = reference_raster[:, :, 0]
        # calculate square normed errors
        scores_sq = cv.matchTemplate(reference_raster.astype(np.float32),
                                     image_raster.astype(np.float32),
                                     cv.TM_SQDIFF_NORMED)[0][0]
        # call structural difference score
        scores_cf = cv.matchTemplate(reference_raster.astype(np.float32),
                                     image_raster.astype(np.float32),
                                     cv.TM_CCOEFF_NORMED)[0][0]
        self.assertLess(0.99, scores_cf)
        self.assertLess(scores_sq, 0.002)
Ejemplo n.º 9
0
def export_priv_image_region(folder, image_name, driver, scene_index, rect,
                             size, ext):
    """
    Export a region of an image for regression tests.

    The function extracts region from an image scene
    and saves multiple images channel by channel
    to a folder with the same name for a regression test.
    """
    image_path = get_priv_test_image_path(folder, image_name)
    slide = slideio.open_slide(image_path, driver)
    scene = slide.get_scene(scene_index)
    num_channels = scene.num_channels
    for channel_index in range(num_channels):
        image_raster = scene.read_block(rect,
                                        size=size,
                                        channel_indices=[channel_index])
        regr_image_name = generate_priv_regression_image_name(
            image_name, scene_index, channel_index, rect, ext)
        regr_image_path = get_priv_test_image_path(folder, regr_image_name)
        # check if we have to create a folder
        dir_path = os.path.split(regr_image_path)[0]
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
        # save output image
        cv.imwrite(regr_image_path, image_raster)
Ejemplo n.º 10
0
    def test_read_block_2d(self):
        """
        Read 2d uncompressed block.

        Reads thew whole uncompressed image and compares received
        raster against reference images.
        """
        # Image to test
        image_path = get_test_image_path("czi", "pJP31mCherry.czi")
        # Reference channel images
        channel_image_paths = [
            get_test_image_path(
                "czi",
                "pJP31mCherry.grey/pJP31mCherry_b0t0z0c0x0-512y0-512.bmp"),
            get_test_image_path(
                "czi",
                "pJP31mCherry.grey/pJP31mCherry_b0t0z0c1x0-512y0-512.bmp"),
            get_test_image_path(
                "czi",
                "pJP31mCherry.grey/pJP31mCherry_b0t0z0c2x0-512y0-512.bmp")
        ]
        slide = slideio.open_slide(image_path, "CZI")
        self.assertTrue(slide is not None)
        scene = slide.get_scene(0)
        self.assertTrue(scene is not None)
        for channel_index in range(scene.num_channels):
            image_raster = scene.read_block(channel_indices=[channel_index])
            reference_raster = cv.imread(channel_image_paths[channel_index],
                                         cv.IMREAD_GRAYSCALE)
            self.assertTrue(np.array_equal(image_raster, reference_raster))
Ejemplo n.º 11
0
    def test_file_metadata2(self):
        """
        Checks image metadata.

        Opens 6 channel uncompressed czi file and checks metadata.
        """
        image_path = get_test_image_path("czi", "08_18_2018_enc_1001_633.czi")
        channel_names = ["646", "655", "664", "673", "682", "691"]
        slide = slideio.open_slide(image_path, "CZI")
        self.assertTrue(slide is not None)
        num_scenes = slide.num_scenes
        self.assertEqual(num_scenes, 1)
        self.assertEqual(image_path, slide.file_path)
        scene = slide.get_scene(0)
        self.assertTrue(scene is not None)
        self.assertEqual(image_path, scene.file_path)
        self.assertEqual(6, scene.num_channels)
        scene_rect = scene.rect
        self.assertEqual(0, scene_rect[0])
        self.assertEqual(0, scene_rect[1])
        self.assertEqual(1000, scene_rect[2])
        self.assertEqual(1000, scene_rect[3])
        self.assertEqual(63, scene.magnification)
        for channel_index in range(scene.num_channels):
            channel_type = scene.get_channel_data_type(channel_index)
            self.assertEqual(channel_type, np.uint16)
            compression = scene.compression
            self.assertEqual(compression, slideio.Compression.Uncompressed)
            channel_name = scene.get_channel_name(channel_index)
            self.assertEqual(channel_name, channel_names[channel_index])
        res = scene.resolution
        correct_res = 6.7475572821478794e-8
        self.assertEqual(correct_res, pytest.approx(res[0]))
        self.assertEqual(correct_res, pytest.approx(res[1]))
Ejemplo n.º 12
0
    def test_file_metadata(self):
        """
        Checks image metadata.

        Opens 3 channel uncompressed czi file and checks metadata.
        """
        image_path = get_test_image_path("czi", "pJP31mCherry.czi")
        slide = slideio.open_slide(image_path, "CZI")
        self.assertTrue(slide is not None)
        num_scenes = slide.num_scenes
        self.assertEqual(num_scenes, 1)
        self.assertEqual(image_path, slide.file_path)
        scene = slide.get_scene(0)
        self.assertTrue(scene is not None)
        self.assertEqual(image_path, scene.file_path)
        self.assertEqual(3, scene.num_channels)
        scene_rect = scene.rect
        self.assertEqual(0, scene_rect[0])
        self.assertEqual(0, scene_rect[1])
        self.assertEqual(512, scene_rect[2])
        self.assertEqual(512, scene_rect[3])
        self.assertEqual(100, scene.magnification)
        raw_metadata = slide.raw_metadata
        self.assertTrue(raw_metadata.startswith("<ImageDocument>"))
        for channel_index in range(scene.num_channels):
            channel_type = scene.get_channel_data_type(channel_index)
            self.assertEqual(channel_type, np.uint8)
            compression = scene.compression
            self.assertEqual(compression, slideio.Compression.Uncompressed)
        res = scene.resolution
        correct_res = 9.76783e-8
        self.assertEqual(correct_res, pytest.approx(res[0]))
        self.assertEqual(correct_res, pytest.approx(res[1]))
Ejemplo n.º 13
0
    def test_read_block_4d(self):
        """
        Read 4d uncompressed block.

        Reads thew whole uncompressed image and compares received
        raster against reference images.
        """
        # Image to test
        image_path = get_test_image_path("czi", "pJP31mCherry.czi")
        slide = slideio.open_slide(image_path, "CZI")
        self.assertTrue(slide is not None)
        scene = slide.get_scene(0)
        self.assertTrue(scene is not None)
        slices = (2, 5)
        frames = (0, 1)
        for channel_index in range(scene.num_channels):
            image_raster = scene.read_block(channel_indices=[channel_index],
                                            slices=slices,
                                            frames=frames)
            image_shape = image_raster.shape
            self.assertEqual(image_shape, (3, 512, 512))
            for slice_index in range(slices[0], slices[1]):
                slice_raster = image_raster[slice_index - slices[0], :, :]
                slice_shape = slice_raster.shape
                self.assertEqual(slice_shape, (512, 512))
                ref_image_name = "pJP31mCherry.grey/pJP31mCherry_b0t0z" + \
                    str(slice_index) + "c" + str(channel_index) + \
                    "x0-512y0-512.bmp"
                ref_image_path = get_test_image_path("czi", ref_image_name)
                reference_raster = cv.imread(ref_image_path,
                                             cv.IMREAD_GRAYSCALE)
                self.assertTrue(np.array_equal(slice_raster, reference_raster))
Ejemplo n.º 14
0
 def extract_features(self, dataset_name: str, scales=None):
     scales = self.images[dataset_name].keys() if scales is None else scales
     for s in scales:
         images = self.images[dataset_name][s]
         if dataset_name not in self.features:
             self.features[dataset_name] = {}
         self.features[dataset_name][s] = np.zeros(images.shape[0],
                                                   dtype=object)
         print(
             f"Extracting binary features for \"{dataset_name}\" dataset on scale {s} "
             f"with {self.cfg.feature_extractor.type} extractor:")
         for n, image_name in enumerate(
                 tqdm(images, disable=images.shape[0] < 5)):
             if image_name.endswith('.svs'):
                 wsi = slideio.open_slide(image_name, 'SVS').get_scene(0)
                 cur_scale_size = (np.array(wsi.size) *
                                   (s / wsi.magnification)).astype('int64')
                 image = wsi.read_block(size=cur_scale_size)
             else:
                 image = np.array(Image.open(image_name))
             features = get_image_features(image=image,
                                           tile_size=self.__tile_size,
                                           extractor=self.extractor,
                                           binarizator=self.__hash,
                                           log=image_name.endswith('.svs'))
             self.features[dataset_name][s][n] = {
                 'features': features,
                 'image_name': image_name,
             }
Ejemplo n.º 15
0
 def test_3chnl_png16b_metadata(self):
     """Opens 3 channel 16 bit png file and checks metadata."""
     image_path = get_test_image_path(
         "gdal",
         "img_2448x2448_3x16bit_SRC_RGB_ducks.png"
         )
     slide = slideio.open_slide(image_path, "GDAL")
     self.assertTrue(slide is not None)
     num_scenes = slide.num_scenes
     self.assertEqual(num_scenes, 1)
     self.assertEqual(image_path, slide.file_path)
     scene = slide.get_scene(0)
     self.assertTrue(scene is not None)
     self.assertEqual(image_path, scene.file_path)
     self.assertEqual(3, scene.num_channels)
     scene_rect = scene.rect
     self.assertEqual(0, scene_rect[0])
     self.assertEqual(0, scene_rect[1])
     self.assertEqual(2448, scene_rect[2])
     self.assertEqual(2448, scene_rect[3])
     for channel_index in range(scene.num_channels):
         channel_type = scene.get_channel_data_type(channel_index)
         self.assertEqual(channel_type, np.uint16)
         compression = scene.compression
         self.assertEqual(compression, slideio.Compression.Png)
     res = scene.resolution
     self.assertEqual(0, res[0])
     self.assertEqual(0, res[1])
Ejemplo n.º 16
0
 def test_3chnl_jpeg_metadata(self):
     """Opens 3 channel jpeg file and checks metadata."""
     image_path = get_test_image_path(
         "gdal",
         "Airbus_Pleiades_50cm_8bit_RGB_Yogyakarta.jpg"
         )
     slide = slideio.open_slide(image_path, "GDAL")
     self.assertTrue(slide is not None)
     num_scenes = slide.num_scenes
     self.assertEqual(num_scenes, 1)
     self.assertEqual(image_path, slide.file_path)
     scene = slide.get_scene(0)
     self.assertTrue(scene is not None)
     self.assertEqual(image_path, scene.file_path)
     self.assertEqual(3, scene.num_channels)
     scene_rect = scene.rect
     self.assertEqual(0, scene_rect[0])
     self.assertEqual(0, scene_rect[1])
     self.assertEqual(5494, scene_rect[2])
     self.assertEqual(5839, scene_rect[3])
     for channel_index in range(scene.num_channels):
         channel_type = scene.get_channel_data_type(channel_index)
         self.assertEqual(channel_type, np.uint8)
         compression = scene.compression
         self.assertEqual(compression, slideio.Compression.Jpeg)
     res = scene.resolution
     self.assertEqual(0, res[0])
     self.assertEqual(0, res[1])
Ejemplo n.º 17
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # image = scene.read_block(size=(size,0))
        slide = slideio.open_slide(str(self.filename), 'SVS')
        self.dataset = slide.get_scene(0)
        self.dims = self.dataset.size #self.dataset.width, self.dataset.height
Ejemplo n.º 18
0
    def test_jp2k_16b_regression(self):
        """
        Regression test for 16b Jpeg 2K compressed image.

        Read the block from a slide and compares it
        with a reference image. The reference image
        is obtained by reading of the same region
        by the slideo and savint it as a tif file.
        """
        # Image to test
        image_path = get_test_image_path("svs", "jp2k_1chnl.svs")
        # Image to test
        reference_image_path = get_test_image_path(
            "svs", "jp2k_1chnl.regression_x700_y400_w500_y400.tif")
        # Read reference image
        reference_image = cv.imread(reference_image_path, cv.IMREAD_UNCHANGED)
        x_beg = 700
        y_beg = 400
        width = 500
        height = 400
        rect = (x_beg, y_beg, width, height)
        new_size = (100, 80)

        # open the slide
        slide = slideio.open_slide(image_path, "SVS")
        self.assertTrue(slide is not None)
        scene = slide.get_scene(0)
        self.assertTrue(scene is not None)
        block_raster = scene.read_block(rect, size=new_size)
        self.assertTrue(np.array_equal(block_raster, reference_image))
Ejemplo n.º 19
0
    def test_jp2k_16b_read_block(self):
        """
        Read a block of Jpeg2K compressed 16 bit image.

        Reads a block from a slide and compares it
        with a block exported by ImageScope software.
        """
        # Image to test
        image_path = get_test_image_path("svs", "jp2k_1chnl.svs")
        # Image to test
        reference_image_path = get_test_image_path(
            "svs", "jp2k_1chnl.region_x700_y400_w500_y400.tif")
        # Read reference image
        reference_image = cv.imread(reference_image_path, cv.IMREAD_UNCHANGED)
        x_beg = 700
        y_beg = 400
        width = 500
        height = 400
        # Read region with slideio
        slide = slideio.open_slide(image_path, "SVS")
        self.assertTrue(slide is not None)
        scene = slide.get_scene(0)
        self.assertTrue(scene is not None)
        region = scene.read_block((x_beg, y_beg, width, height))
        # call structural difference score
        scores_cf = cv.matchTemplate(region.astype(np.float32),
                                     reference_image.astype(np.float32),
                                     cv.TM_CCOEFF_NORMED)[0][0]
        # calculate square normed errors
        scores_sq = cv.matchTemplate(region.astype(np.float32),
                                     reference_image.astype(np.float32),
                                     cv.TM_SQDIFF_NORMED)[0][0]
        self.assertLess(0.99, scores_cf)
        self.assertLess(scores_sq, 0.0002)
Ejemplo n.º 20
0
 def get_image(self, dataset_name: str, scale: int, image_idx: int):
     image_name = self.images[dataset_name][scale][image_idx]
     if image_name.endswith('.svs'):
         wsi = slideio.open_slide(image_name, 'SVS').get_scene(0)
         cur_scale_size = (np.array(wsi.size) *
                           (scale / wsi.magnification)).astype('int64')
         return wsi.read_block(size=cur_scale_size)
     else:
         return np.array(Image.open(image_name))
Ejemplo n.º 21
0
    def test_jp2k_16b_resample_block(self):
        """
        Test for resampling of a 16bit block.

        A region of 16 bit, jpeg 2000 compressed image is read
        and resized with different scale.
        An reference block is exportded by ImageScope software
        on scale 1:1 and resized with opencv with the same
        scale coefficients as the original region.
        """
        # Image to test
        image_path = get_test_image_path("svs", "jp2k_1chnl.svs")
        # Image to test
        reference_image_path = get_test_image_path(
            "svs", "jp2k_1chnl.region_x700_y400_w500_y400.tif")
        # Read reference image
        reference_image = cv.imread(reference_image_path, cv.IMREAD_UNCHANGED)
        x_beg = 700
        y_beg = 400
        width = 500
        height = 400
        rect = (x_beg, y_beg, width, height)
        size = (width, height)

        # open the slide
        slide = slideio.open_slide(image_path, "SVS")
        self.assertTrue(slide is not None)
        scene = slide.get_scene(0)
        self.assertTrue(scene is not None)

        scaling_params = {
            1.0: (0.9999, 2.e-7),
            1.5: (0.99, 0.002),
            2.0: (0.999, 1.e-7),
            3.0: (0.98, 0.01),
            5.0: (0.98, 0.01)
        }
        for resize_cof, params in scaling_params.items():
            new_size = (int(round(size[0] / resize_cof)),
                        int(round(size[1] / resize_cof)))
            resized_raster = scene.read_block(rect, size=new_size)
            cv_resized_raster = cv.resize(reference_image, new_size)
            # call structural difference score
            score_cf = cv.matchTemplate(resized_raster.astype(np.float32),
                                        cv_resized_raster.astype(np.float32),
                                        cv.TM_CCOEFF_NORMED)[0][0]
            # calculate square normed errors
            score_sq = cv.matchTemplate(resized_raster.astype(np.float32),
                                        cv_resized_raster.astype(np.float32),
                                        cv.TM_SQDIFF_NORMED)[0][0]
            self.assertLess(params[0], score_cf)
            self.assertLess(score_sq, params[1])
Ejemplo n.º 22
0
    def load_svs(self, path: str, dataset_name: str, scales: List[int]):
        if path.endswith('.svs') and os.path.exists(path):
            scales = np.array(scales)
            wsi = slideio.open_slide(path, 'SVS').get_scene(0)
            scales = scales[scales <= int(wsi.magnification)]

            if dataset_name not in self.images:
                self.images[dataset_name] = {}
            for scale in scales:
                if scale not in self.images[dataset_name]:
                    self.images[dataset_name][scale] = np.array([])
                self.images[dataset_name][scale] = np.append(
                    self.images[dataset_name][scale], path)
Ejemplo n.º 23
0
    def disabled_test_corrupted_fail_file(self):
        """
        Opening of a corrupted image.

        Checks if slideio throws RuntimeError
        exception during opening.
        """
        image_path = get_priv_test_image_path(
            "afi",
            "corrupted.afi"
            )
        slide = slideio.open_slide(image_path, "AFI")
        scene = slide.get_scene(0)
        with pytest.raises(RuntimeError):
            scene.read_block()
Ejemplo n.º 24
0
 def test_image_similarity_equal(self):
     """Similarity score of equal images shall be 1."""
     image_path = get_test_image_path(
         "gdal", "img_2448x2448_3x8bit_SRC_RGB_ducks.png")
     with slideio.open_slide(image_path, "GDAL") as slide:
         with slide.get_scene(0) as scene:
             img1 = scene.read_block()
             img2 = scene.read_block()
     score = slideio.compare_images(img1, img2)
     self.assertEqual(score, 1)
     blank_image = np.zeros(img1.shape, np.uint8)
     score = slideio.compare_images(img1, blank_image)
     self.assertLess(score, 0.5)
     blur = cv.blur(img2, (20, 20))
     score = slideio.compare_images(img1, blur)
     self.assertLess(score, 0.98)
     self.assertGreater(score, 0.8)
def data_generation(cfg):
    image_dir = to_absolute_path(cfg.image_dir)
    files = os.listdir(image_dir)
    image_names = np.array(
        list(
            filter(lambda x: x.endswith('.svs') and x not in cfg.skip_images,
                   files)))
    all_images = np.vectorize(lambda x: f"{image_dir}/{x}")(image_names)
    all_images.sort()
    wsi_list = [
        slideio.open_slide(image_name, 'SVS') for image_name in all_images
    ]

    print(f'=====GENERATING TILES======')
    for i in tqdm(range(cfg.n_images)):
        tile = generate_tile(wsi_list, cfg.level, np.array(cfg.tile_size))
        tile = Image.fromarray(tile)
        tile = tile.convert('RGB')
        output_name = f"{to_absolute_path(cfg.output_dir)}/{i}.jpg"
        tile.save(output_name)
    print(f'====={cfg.n_images} TILES GENERATED======')
Ejemplo n.º 26
0
    def test_jpegxr_16b_resample_block(self):
        """
        Test for resampling of a block.

        A region of 16 bit, jpegxr compressed image is read
        with 1:1 scale and resampled with different scales.
        1:1 block is resized in memory by opencv and compared
        with resampled region from slideio.
        """
        # Image to test
        image_path = get_test_image_path("czi", "jxr-16bit-4chnls-2.czi")
        region_size = (1000, 500)
        region_rect = (5000, 2000, region_size[0], region_size[1])
        slide = slideio.open_slide(image_path, "CZI")
        self.assertTrue(slide is not None)
        scene = slide.get_scene(0)
        self.assertTrue(scene is not None)
        origin_raster = scene.read_block(region_rect)
        scaling_params = {
            1.0: (0.9999, 1.e-7),
            1.5: (0.99, 0.0004),
            2.0: (0.98, 0.0035),
            3.0: (0.95, 0.007),
            5.0: (0.95, 0.008)
        }
        for resize_cof, params in scaling_params.items():
            new_size = (int(round(region_size[0] / resize_cof)),
                        int(round(region_size[1] / resize_cof)))
            resized_raster = scene.read_block(region_rect, size=new_size)
            cv_resized_raster = cv.resize(origin_raster, new_size)
            # call structural difference score
            scores_cf = cv.matchTemplate(resized_raster.astype(np.float32),
                                         cv_resized_raster.astype(np.float32),
                                         cv.TM_CCOEFF_NORMED)[0][0]
            # calculate square normed errors
            scores_sq = cv.matchTemplate(resized_raster.astype(np.float32),
                                         cv_resized_raster.astype(np.float32),
                                         cv.TM_SQDIFF_NORMED)[0][0]
            self.assertLess(params[0], scores_cf)
            self.assertLess(scores_sq, params[1])
Ejemplo n.º 27
0
    def test_image_block_resampled(self):
        """
        Checks image block (resampled)

        Opens a valid file, reads an image block 
        from
        one of the scenes.
        """
        image_path = get_priv_test_image_path(
            "afi",
            "fs.afi"
            )
        slide = slideio.open_slide(image_path, "AFI")
        self.assertTrue(slide is not None)
        scene = slide.get_scene(1)
        self.assertTrue(scene is not None)
        
        rect = (2500, 4000, 400, 400)
        size = (800, 800)
        scene_image = scene.read_block(rect, size=size)
        scene_image = scene_image.astype("float32")
        
        reference_image_file = get_priv_test_image_path(
                    "afi", 
                    "fs_Alexa Fluor 488_block_2500_4000_400_400.tif"
                    )
        reference_image = cv.imread(
            reference_image_file,
            cv.IMREAD_UNCHANGED
            )
        reference_region = cv.resize(reference_image, size)
        reference_region = reference_region.astype("float32")
        self.assertEqual(scene_image.shape, reference_region.shape)
        score = cv.matchTemplate(
                scene_image,
                reference_region,
                cv.TM_CCOEFF_NORMED
                )
        min_score = np.amin(score)
        self.assertLess(.99, min_score);
Ejemplo n.º 28
0
    def test_jpegxr_rgb_read_block(self):
        """
        Read a block of rgb jpegxr compressed image.

        Read the block from a slide and compares it
        with a reference image.
        """
        # Image to test
        image_path = get_test_image_path("czi", "jxr-rgb-5scenes.czi")
        # Reference channel images
        ref_image_paths = get_test_image_path(
            "czi",
            "jxr-rgb-5scenes/jxr-rgb-5scenes_s3_x2500_y3000_w400_h600.png")
        slide = slideio.open_slide(image_path, "CZI")
        self.assertTrue(slide is not None)
        scene = slide.get_scene(3)
        self.assertTrue(scene is not None)
        image_raster = scene.read_block((2500, 3000, 400, 600))
        reference_raster = cv.imread(ref_image_paths, cv.IMREAD_UNCHANGED)
        scores_cf = cv.matchTemplate(reference_raster, image_raster,
                                     cv.TM_CCOEFF_NORMED)[0][0]
        self.assertLess(0.99, scores_cf)
Ejemplo n.º 29
0
    def test_valid_file(self):
        """
        Checks scenes of a valid file.

        Opens a valid afi file and checks the number of
        scenes loaded
        """
        image_path = get_priv_test_image_path(
            "afi",
            "fs.afi"
            )
        slide = slideio.open_slide(image_path, "AFI")
        self.assertTrue(slide is not None)
        num_scenes = slide.num_scenes
        self.assertEqual(num_scenes, 3)
        self.assertEqual(image_path, slide.file_path)
        self.assertEqual(slide.get_scene(1).name, "Image")
        expected_path = get_priv_test_image_path("afi", 
                                                 "fs_Alexa Fluor 488.svs")
        expected_path = expected_path.replace(os.sep, posixpath.sep)
        self.assertEqual(slide.get_scene(1).file_path, 
                         expected_path)
Ejemplo n.º 30
0
def detect_scales(scalenet: ScaleNet, query, test_wsi, scales, n_samples=10):
    device = torch.device(
        'cuda') if torch.cuda.is_available() else torch.device('cpu')
    scalenet.to(device)
    scalenet.eval()

    wsi = slideio.open_slide(test_wsi, 'SVS').get_scene(0)

    scale_probs = []
    for scale in scales:
        samples_batch = np.empty([
            n_samples, scalenet.in_channels, scalenet.input_size,
            scalenet.input_size
        ])
        for i in range(n_samples):
            sample = generate_tile(wsi, scale,
                                   (scalenet.input_size, scalenet.input_size))
            while sample is None or sample.mean() / 255 > 0.9:
                sample = generate_tile(
                    wsi, scale, (scalenet.input_size, scalenet.input_size))
            samples_batch[i, ...] = concat_images(query, sample)
        samples_batch /= 255
        samples_batch = torch.FloatTensor(samples_batch).to(device)
        scale_probs.append(torch.mean(scalenet(samples_batch)).item())

    detected_scale_idx = int(np.argmax(scale_probs))
    detected_scales = [scales[detected_scale_idx]]
    if detected_scale_idx > 0:
        detected_scales.append(scales[detected_scale_idx - 1])
    if detected_scale_idx < len(scales) - 1:
        detected_scales.append(scales[detected_scale_idx + 1])
    return {
        'query_scales': sorted(detected_scales),
        'detected_scale': scales[detected_scale_idx],
        'prob': np.max(scale_probs)
    }