コード例 #1
0
ファイル: dzi.py プロジェクト: stijnimaging/histoannot
def tile(mode, project, specimen, block, resource, slide_name, slide_ext,
         level, col, row, format):
    format = format.lower()
    if format != 'jpeg' and format != 'png':
        # Not supported by Deep Zoom
        return 'bad format'
        abort(404)

    # Get a project reference, using either local database or remotely supplied dict
    pr = dzi_get_project_ref(project)

    # Get the raw SVS/tiff file for the slide (the resource should exist,
    # or else we will spend a minute here waiting with no response to user)
    sr = SlideRef(pr, specimen, block, slide_name, slide_ext)
    tiff_file = sr.get_local_copy(resource)

    os = None
    if mode == 'affine':
        os = AffineTransformedOpenSlide(
            tiff_file, get_affine_matrix(sr, 'affine', resource, 'image'))
    else:
        os = OpenSlide(tiff_file)

    dz = DeepZoomGenerator(os)
    tile = dz.get_tile(level, (col, row))

    buf = PILBytesIO()
    tile.save(buf, format, quality=75)
    resp = make_response(buf.getvalue())
    resp.mimetype = 'image/%s' % format
    print('PNG size: %d' % (len(buf.getvalue(), )))
    return resp
コード例 #2
0
def index_wsi(file_path):
    config_map = {
        'DEEPZOOM_TILE_SIZE': 'tile_size',
        'DEEPZOOM_OVERLAP': 'overlap',
        'DEEPZOOM_LIMIT_BOUNDS': 'limit_bounds',
    }
    opts = dict((v, app.config[k]) for k, v in config_map.items())
    slide = open_slide('static/wsi/' + file_path)
    app.slides = {
        SLIDE_NAME: DeepZoomGenerator(slide, **opts)
    }
    app.associated_images = []
    app.slide_properties = slide.properties
    for name, image in slide.associated_images.items():
        app.associated_images.append(name)
        slug = slugify(name)
        app.slides[slug] = DeepZoomGenerator(ImageSlide(image), **opts)
    try:
        mpp_x = slide.properties[openslide.PROPERTY_NAME_MPP_X]
        mpp_y = slide.properties[openslide.PROPERTY_NAME_MPP_Y]
        slide_mpp = (float(mpp_x) + float(mpp_y)) / 2
    except (KeyError, ValueError):
        slide_mpp = 0
    slide_url = url_for('dzi', slug=SLIDE_NAME)
    return render_template('as_viewer.html', slide_url=slide_url, slide_mpp=slide_mpp, file_name=file_path, dictionary=getDictionary(file_path))
コード例 #3
0
ファイル: slideServer.py プロジェクト: PetraSong/slideToolKit
def load_slide():
    slidefile = app.config['DEEPZOOM_SLIDE']
    if slidefile is None:
        raise ValueError('No slide file specified')
    config_map = {
        'DEEPZOOM_TILE_SIZE': 'tile_size',
        'DEEPZOOM_OVERLAP': 'overlap',
        'DEEPZOOM_LIMIT_BOUNDS': 'limit_bounds',
    }
    opts = dict((v, app.config[k]) for k, v in config_map.items())
    slide = open_slide(slidefile)
    app.slides = {
        SLIDE_NAME: DeepZoomGenerator(slide, **opts)
    }
    app.associated_images = []
    app.slide_properties = slide.properties
    for name, image in slide.associated_images.items():
        app.associated_images.append(name)
        slug = slugify(name)
        app.slides[slug] = DeepZoomGenerator(ImageSlide(image), **opts)
    try:
        mpp_x = slide.properties[openslide.PROPERTY_NAME_MPP_X]
        mpp_y = slide.properties[openslide.PROPERTY_NAME_MPP_Y]
        app.slide_mpp = (float(mpp_x) + float(mpp_y)) / 2
    except (KeyError, ValueError):
        app.slide_mpp = 0
コード例 #4
0
def ndpi_cut(ndpi_way, x, k, outway, pe):  # x = 分割后图片边长  k = ndpi图片的第几个level
    # time_start = time.time()
    if not os.path.isdir(outway):
        os.makedirs(outway)
    for files in os.listdir(ndpi_way):
        # 当前文件夹所有文件
        if files.endswith('.tiff'):  # 判断是否以.ndpi结尾 也可以为tiff
            slide = op.OpenSlide(ndpi_way + '\\' + files)
            # print(slide.level_dimensions)
            bigImg = DeepZoomGenerator(slide,
                                       tile_size=x - 2,
                                       overlap=1,
                                       limit_bounds=False)
            count = bigImg.level_count - 1
            z = count - k  # 倒着读取
            raw, col = bigImg.level_tiles[z]
            # print(raw, col)
            (filename, extension) = os.path.splitext(files)
            for i in range(raw - 1):
                for j in range(col - 1):
                    try:
                        img = bigImg.get_tile(z, (j, i))
                        Img = np.asarray(img)
                        if Img.shape == (a, a, Img.shape[2]):
                            p = judge_white.judge_white(Img)
                            print(p, Img.shape, (a, a, Img.shape[2]))
                            if p < pe:
                                outputway = outway + '\\' + filename + r'_{a}_{b}.png'.format(
                                    a=i, b=j)
                                img.save(outputway)
                            else:
                                pass
                    except ValueError:
                        break
            print(files + ' done')
コード例 #5
0
    def get(self, path):
        """
        Method for getting slide cache. Has self and path arguments.
        """
        with self._lock:
            if path in self._cache:
                # Move to end of LRU
                slide = self._cache.pop(path)
                self._cache[path] = slide
                return slide

        osr = OpenSlide(path)
        slide = DeepZoomGenerator(osr, **self.dz_opts)
        try:
            mpp_x = osr.properties[openslide.PROPERTY_NAME_MPP_X]
            mpp_y = osr.properties[openslide.PROPERTY_NAME_MPP_Y]
            slide.mpp = (float(mpp_x) + float(mpp_y)) / 2
        except (KeyError, ValueError):
            slide.mpp = 0

        with self._lock:
            if path not in self._cache:
                if len(self._cache) == self.cache_size:
                    self._cache.popitem(last=False)
                self._cache[path] = slide
        return slide
コード例 #6
0
 def __init__(self, osr, tile_size=254, overlap=1, limit_bounds=False):
     if osr.format in ['.kfb', '.KFB']:
         self._dzg = KfbDZG(osr, tile_size, overlap, limit_bounds)
     elif osr.format in ['.tmap', '.TMAP']:
         self._dzg = TmapDZG(osr, 256, overlap, limit_bounds)
     else:
         self._dzg = OpenSlideDZG(osr, tile_size, overlap, limit_bounds)
コード例 #7
0
def save_valid_imgs(samples, patch_size=PATCH_SIZE):
    num_samples = len(samples)
    for idx in range(num_samples):
        for _, batch_sample in samples.iloc[idx:idx + 1].iterrows():
            slide_path = batch_sample.slide_path
        print(slide_path)
        slide_name = 's'
        slide_contains_tumor = 'pos' in slide_path
        with openslide.open_slide(slide_path) as slide:
            tiles = DeepZoomGenerator(slide,
                                      tile_size=patch_size,
                                      overlap=0,
                                      limit_bounds=False)
            x, y = batch_sample.tile_loc[::-1]
            if slide_contains_tumor:
                start_x = int(slide.properties.get('openslide.bounds-x', 0))
                start_y = int(slide.properties.get('openslide.bounds-y', 0))
                start_x = start_x / patch_size
                start_y = start_y / patch_size
                x += start_x
                y += start_y

                img = tiles.get_tile(tiles.level_count - 1, (x, y))
                img.save('/data/model/patches/val/pos/{}_pos_{}.png'.format(
                    slide_name, idx))

            else:
                img = tiles.get_tile(tiles.level_count - 1, (x, y))
                img.save('/data/model/patches/val/neg/{}_neg_{}.png'.format(
                    slide_name, idx))

    print('num_samples_val : ', num_samples)
    print('val img save completed')
コード例 #8
0
ファイル: deepzoom.py プロジェクト: chaitanya2334/label-coach
def load_slide(slidefile, tile_size):
    print("there is an image")
    slide = open_slide(slidefile)
    slides = {
        "slide": DeepZoomGenerator(slide,
                                   tile_size=tile_size,
                                   overlap=1,
                                   limit_bounds=True)
    }
    associated_images = []
    slide_properties = slide.properties
    for name, image in slide.associated_images.items():
        associated_images.append(name)
        slug = slugify(name)
        slides[slug] = DeepZoomGenerator(ImageSlide(image),
                                         tile_size=tile_size,
                                         overlap=1,
                                         limit_bounds=True)
    try:
        mpp_x = slide.properties[openslide.PROPERTY_NAME_MPP_X]
        mpp_y = slide.properties[openslide.PROPERTY_NAME_MPP_Y]
        slide_mpp = (float(mpp_x) + float(mpp_y)) / 2
    except (KeyError, ValueError):
        slide_mpp = 0

    return slides, associated_images, slide_properties, slide_mpp
コード例 #9
0
ファイル: visual.py プロジェクト: tony32769/tupac
    def get(self, path):
        with self._lock:
            if path in self._cache:
                # Move to end of LRU
                slide = self._cache.pop(path)
                self._cache[path] = slide
                return slide

        if is_image(path):
            #osr = ImageSlide(path)
            osr = get_osr(path)
        else:
            osr = OpenSlide(path)
        slide = DeepZoomGenerator(osr, **self.dz_opts)
        try:
            mpp_x = osr.properties[openslide.PROPERTY_NAME_MPP_X]
            mpp_y = osr.properties[openslide.PROPERTY_NAME_MPP_Y]
            slide.mpp = (float(mpp_x) + float(mpp_y)) / 2
        except (KeyError, ValueError):
            slide.mpp = 0

        with self._lock:
            if path not in self._cache:
                if len(self._cache) == self.cache_size:
                    self._cache.popitem(last=False)
                self._cache[path] = slide
        return slide
コード例 #10
0
    def _serve_tiles(self, request):
        tile_config = request.path[len("/data/plugin/WSI/tiles/"):].split("/")

        id = int(tile_config[0])

        if id == self._cache_slide_id:
            slide = self._cache_slide
        else:
            slide_path = self._cache_slide_prop[id]["slide_path"]
            slide = DeepZoomGenerator(open_slide(slide_path))
            self._cache_slide = slide
            self._cache_slide_id = id

        if len(tile_config) <= 2:
            response = werkzeug.Response(slide.get_dzi("jpeg"))
            response.headers.set('Content-Type', 'application/xml')
            return response
        else:
            level, colrow = tile_config[1:]
            level = int(level)
            col, row = map(int, colrow[:-1 * len(".jpeg"):].split("_"))

            tile = slide.get_tile(level, (col, row))

            buf = PILBytesIO()
            tile.save(buf, "jpeg", quality=75)
            response = werkzeug.Response(buf.getvalue())
            response.headers.set('Content-Type', 'image/jpeg')
            return response
コード例 #11
0
def getTile(file, level, col, row):
    format = 'jpeg'
    slide = DeepZoomGenerator(open_slide(file))
    tile = slide.get_tile(level, (col, row))
    buf = PILBytesIO()
    tile.save(buf, format, quality=app.config['DEEPZOOM_TILE_QUALITY'])
    return base64.b64encode(buf.getvalue())
コード例 #12
0
def dzi_asso(path, associated_name):
    slide = _get_slide(path)
    associated_image = slide.osr.associated_images[associated_name]
    dzg = DeepZoomGenerator(ImageSlide(associated_image))
    format = app.config['DEEPZOOM_FORMAT']
    resp = make_response(dzg.get_dzi(format))
    resp.mimetype = 'application/xml'
    return resp
コード例 #13
0
ファイル: views.py プロジェクト: scancer-org/webapp
def slide_dzi(request, pk):
    scan = get_object_or_404(Scan, pk=pk)
    raw_slide = open_slide(scan.file)
    slide = DeepZoomGenerator(
        raw_slide,
        tile_size=DEEPZOOM_TILE_SIZE,
        overlap=DEEPZOOM_OVERLAP,
        limit_bounds=DEEPZOOM_LIMIT_BOUNDS,
    )
    response = slide.get_dzi(DEEPZOOM_FORMAT)
    return HttpResponse(response, content_type="application/xml")
コード例 #14
0
ファイル: tiling.py プロジェクト: saketkc/pyvirchow
def get_tiles(batch_samples, patch_size=256, num_classes=2, convert_to_cat=True):
    """Generator function to yield image and mask tuples,

    Parameters
    ----------
    batch_samples: DataFrame
                   Subsetted dataframe as obtained from get_all_patches_from_slide
    patch_size: int
                Patch size
    convert_to_cat: bool
                    Should convert to categorical

    Returns
    -------
    X: tensor
    Y: tensor

    """
    images = []
    masks = []
    for _, batch_sample in batch_samples.iterrows():
        slide_contains_tumor = batch_sample["uid"].startswith("tumor")

        with WSIReader(batch_sample.slide_path, 40) as slide:
            tiles = DeepZoomGenerator(
                slide, tile_size=patch_size, overlap=0, limit_bounds=False
            )
            tile_loc = batch_sample.tile_loc  # [::-1]
            if isinstance(tile_loc, six.string_types):
                tile_row, tile_col = eval(tile_loc)
            else:
                tile_row, tile_col = tile_loc
            # the get_tile tuple required is (col, row)
            img = tiles.get_tile(tiles.level_count - 1, (tile_col, tile_row))
            (tile_x, tile_y), tile_level, _ = tiles.get_tile_coordinates(
                tiles.level_count - 1, (tile_col, tile_row)
            )

        if slide_contains_tumor:
            json_filepath = batch_sample["json_filepath"]
            polygons = get_annotation_polygons(json_filepath, "shapely")
            mask = create_tumor_mask_from_tile(tile_x, tile_y, polygons, patch_size)
        else:
            mask = np.zeros((patch_size, patch_size))

        images.append(np.array(img))
        masks.append(mask)

    X_train = np.array(images)
    y_train = np.array(masks)
    if convert_to_cat:
        y_train = mask_to_categorical(y_train, num_classes, patch_size)
    return X_train, y_train
コード例 #15
0
ファイル: views.py プロジェクト: scancer-org/webapp
def tile(request, pk, level, col, row):
    scan = get_object_or_404(Scan, pk=pk)
    raw_slide = open_slide(scan.file)
    slide = DeepZoomGenerator(
        raw_slide,
        tile_size=DEEPZOOM_TILE_SIZE,
        overlap=DEEPZOOM_OVERLAP,
        limit_bounds=DEEPZOOM_LIMIT_BOUNDS,
    )
    tile = slide.get_tile(level, (col, row))
    buf = BytesIO()
    tile.save(buf, DEEPZOOM_FORMAT, quality=DEEPZOOM_TILE_QUALITY)
    return HttpResponse(buf.getvalue(), content_type="image/jpeg")
コード例 #16
0
ファイル: save_patches.py プロジェクト: sauravgarg001/minor2
    def sample_and_store_patches(self, patch_size, level, progressBar):
        start_time = start_timer()  # Timer Start

        rows_per_txn = 20
        tile_size = patch_size
        slide = open_slide(self.file_path)
        tiles = DeepZoomGenerator(slide,
                                  tile_size=tile_size,
                                  overlap=0,
                                  limit_bounds=True)

        if level >= tiles.level_count:
            print(
                "[error]: requested level does not exist. Number of slide levels: "
                + str(tiles.level_count))
            return 0
        x_tiles, y_tiles = tiles.level_tiles[level]

        x, y = 0, 0
        count, batch_count = 0, 0
        patches, coords, labels = [], [], []
        while y < y_tiles:
            while x < x_tiles:
                new_tile = np.array(tiles.get_tile(level, (x, y)),
                                    dtype=np.uint8)
                # OpenSlide calculates overlap in such a way that sometimes depending on the dimensions, edge
                # patches are smaller than the others. We will ignore such patches.
                if np.shape(new_tile) == (patch_size, patch_size, 3):
                    patches.append(new_tile)
                    coords.append(np.array([x, y]))
                    count += 1
                progressBar.setValue(
                    int((y * x_tiles + x) * 100 / (x_tiles * y_tiles)))
                x += 1

            # To save memory, we will save data into the dbs every rows_per_txn rows. i.e., each transaction will commit
            # rows_per_txn rows of patches. Write after last row regardless. HDF5 does NOT follow
            # this convention due to efficiency.
            if (y % rows_per_txn == 0 and y != 0) or y == y_tiles - 1:
                self.save_to_disk(patches, coords, labels)
            y += 1
            x = 0

        print("============ Patches Dataset Stats ===========")
        print("Total patches sampled:   ", count)
        print("Patches saved to:        ", self.db_location)
        print("==============================================")

        end_timer(start_time)  # Timer Ends
コード例 #17
0
ファイル: wsi_utils.py プロジェクト: zhoudaxia233/misp
 def __init__(self, path: str, tile_size: int = 224):
     self.path = path
     self.tile_size = tile_size
     self.slide = openslide.OpenSlide(self.path)
     self.deepzoom_gen = DeepZoomGenerator(self.slide,
                                           tile_size=self.tile_size,
                                           overlap=0,
                                           limit_bounds=False)
     self.mpp = (float(
         self.slide.properties[openslide.PROPERTY_NAME_MPP_X]),
                 float(
                     self.slide.properties[openslide.PROPERTY_NAME_MPP_Y]))
     self.level_count = self.deepzoom_gen.level_count
     self.level_dimensions = self.deepzoom_gen.level_dimensions
     self.level_tiles = self.deepzoom_gen.level_tiles
コード例 #18
0
def ChangeImage(folder, filename):
    global imagePathLookupTable
    session["ID"] = binascii.hexlify(os.urandom(20))
    path = "//home/prosjekt" + imagePathLookupTable[folder + "/" + filename]
    image = openslide.OpenSlide(path)
    logger.log(
        25,
        configuration.LogFormat() + current_user.username +
        " requested image " + filename)
    deepZoomGen = DeepZoomGenerator(image,
                                    tile_size=254,
                                    overlap=1,
                                    limit_bounds=False)
    deepZoomList.append(session["ID"], deepZoomGen)
    return deepZoomGen.get_dzi("jpeg")
コード例 #19
0
    def __init__(self, path):
        self.warning = ''
        self.path = path
        self.reader = None
        self.tilesize = 1024
        self.ext = check_ext(path)
        self.default_dtype = np.uint16

        if self.ext == '.ome.tif' or self.ext == '.ome.tiff':
            self.io = TiffFile(self.path, is_ome=False)
            self.group = zarr.open(self.io.series[0].aszarr())
            self.reader = 'tifffile'
            self.ome_version = self._get_ome_version()
            print("OME ", self.ome_version)
            num_channels = self.get_shape()[0]
            tile_0 = self.get_tifffile_tile(num_channels, 0, 0, 0, 0, 1024)
            if tile_0 is not None:
                self.default_dtype = tile_0.dtype

            if (num_channels == 3 and tile_0.dtype == 'uint8'):
                self.rgba = True
                self.rgba_type = '3 channel'
            elif (num_channels == 1 and tile_0.dtype == 'uint8'):
                self.rgba = True
                self.rgba_type = '1 channel'
            else:
                self.rgba = False
                self.rgba_type = None

            print("RGB ", self.rgba)
            print("RGB type ", self.rgba_type)

        elif self.ext == '.svs':
            self.io = OpenSlide(self.path)
            self.dz = DeepZoomGenerator(self.io,
                                        tile_size=1024,
                                        overlap=0,
                                        limit_bounds=True)
            self.reader = 'openslide'
            self.rgba = True
            self.rgba_type = None
            self.default_dtype = np.uint8

            print("RGB ", self.rgba)
            print("RGB type ", self.rgba_type)

        else:
            self.reader = None
コード例 #20
0
def slide_to_tiles(slide,
                   new_mpp=0.5,
                   tile_size=512,
                   overlap=0,
                   return_locations=False):
    """
    Convert a slide to tiles with a given mpp and tile size
    """

    # Identify appropriate pyramid level for given micron per pixel
    mpp = np.float(slide.properties['openslide.mpp-x'])
    scale_factor = new_mpp / mpp
    offset = math.floor(np.log2((scale_factor + 0.1)))

    level_mpp = 2**offset * mpp
    scale_from_level = new_mpp / level_mpp
    level_tile_size = math.ceil(tile_size * scale_from_level)

    generator = DeepZoomGenerator(slide,
                                  tile_size=level_tile_size,
                                  overlap=overlap,
                                  limit_bounds=True)

    highest_level = generator.level_count - 1
    level = highest_level - offset

    cols, rows = generator.level_tiles[level]

    # Extract tiles
    tiles = []
    tile_locations = []
    for col in range(cols):
        for row in range(rows):
            tile = np.array(generator.get_tile(level, (col, row)))
            if tile.shape[0] == level_tile_size and tile.shape[
                    1] == level_tile_size:
                tile = cv2.resize(tile, (tile_size, tile_size),
                                  interpolation=cv2.INTER_LINEAR)
                tiles.append(tile)
                tile_locations.append([row, col])

    tiles = np.stack(tiles, axis=0)
    tile_locations = np.array(tile_locations)

    if return_locations:
        return tiles, tile_locations
    else:
        return tiles
コード例 #21
0
 def run_image(self, associated=None):
     """
     Run a single image from self.slide.
     """
     if associated is None:
         image = self.slide
         if self.with_viewer:
             basename = os.path.join(self.basename, VIEWER_SLIDE_NAME)
         else:
             basename = self.basename
     else:
         image = ImageSlide(self.slide.associated_images[associated])
         basename = os.path.join(self.basename, self.slugify(associated))
     dz = DeepZoomGenerator(image,
                            self.tile_size,
                            self.overlap,
                            limit_bounds=self.limit_bounds)
     tiler = DeepZoomImageTiler(dz, basename, self.format, associated,
                                self.queue, self.slide, self.basename_jpg,
                                self.xml_file, self.mask_type,
                                self.xml_label, self.roi_percentage,
                                self.img_extension, self.save_masks,
                                self.magnification)
     tiler.run()
     self.dzi_data[self.url_for(associated)] = tiler.get_dzi()
コード例 #22
0
 def _run_image(self, associated=None):
     """Run a single image from self._slide."""
     if associated is None:
         image = self._slide
         if self._with_viewer:
             basename = os.path.join(self._basename, VIEWER_SLIDE_NAME)
         else:
             basename = self._basename
     else:
         image = ImageSlide(self._slide.associated_images[associated])
         basename = os.path.join(self._basename, self._slugify(associated))
     print("enter DeepZoomGenerator")
     dz = DeepZoomGenerator(image,
                            self._tile_size,
                            self._overlap,
                            limit_bounds=self._limit_bounds)
     print("enter DeepZoomImageTiler")
     tiler = DeepZoomImageTiler(dz, basename, self._format, associated,
                                self._queue, self._slide, self._basenameJPG,
                                self._xmlfile, self._mask_type,
                                self._xmlLabel, self._ROIpc,
                                self._ImgExtension, self._SaveMasks,
                                self._Mag)
     tiler.run()
     self._dzi_data[self._url_for(associated)] = tiler.get_dzi()
コード例 #23
0
ファイル: save_patches.py プロジェクト: sauravgarg001/minor2
    def print_tile_dimensions(self, patch_size=0):
        patch_dim = patch_size
        level_count = 0
        level_tiles = []
        level_dimensions = []

        # Check that either tile or patch size is set correctly.
        if patch_size == 0:
            print("[error]: set patch size.")
        else:
            print("Setting patch size ", patch_dim)

            # Open image and return variables.
            slide = open_slide(self.file_path)
            tiles = DeepZoomGenerator(slide, tile_size=patch_size, overlap=0)

            level_count = tiles.level_count
            level_tiles = tiles.level_tiles
            level_dimensions = tiles.level_dimensions

        print("============Tile Dimensions==========")
        print("Level count:         " + str(level_count))
        print("Level tiles:         " + str(level_tiles))
        print("Level dimensions:    " + str(level_dimensions))
        print("=====================================")
コード例 #24
0
def get_regions(dz: DZG, i: int, j: int) -> Tuple[List[int], List[int]]:
    """Retourne une région d'intérêt étant donné deux indices i et j.
    Paramètres:
        i   : indice selon la largeur de la lame
        j   : indice selon la hauteur de la lame

    Outputs:
        region_0 :  liste de 4 entiers (w_0, h_0, t_w, t_h) avec w_0 et h_0
                    les coordonnées du coin en haut à gauche du patch d'indice
                    (i, j). t_w et t_h sont la largeur et la hauteur du patch
                    en pixel. En principe, t_w = t_h sauf pour les patches 
                    présents sur les bordures de la lame. Les coordonnées w_0,
                    h_0, t_w, t_h sont prises pour le plus haut niveau de 
                    résolution.
        
        region_l :  liste de 4 entiers (h_start, h_end, w_start, w_end) 
                    correpondant aux coordonnées du patch équivalent à
                    un niveau de résolution plus faible (ex. 32). Ces
                    coordonnées permettront de calculer le pourcentage 
                    de fond blanc sur le patch grâce au masque de segmen-
                    tation.
    """
    # coordonnées dans le niveau de résolution le plus élevé
    (w_0_ij, h_0_ij), _, (d_w_0_ij,
                          d_h_0_ij) = dz.get_tile_coordinates(dz.l0_z, (j, i))
    # coordonnées dans le niveau de résolution le plus faible
    d_h_l_ij, d_w_l_ij = round(d_h_0_ij / dz.f_h), round(d_w_0_ij / dz.f_w)
    start_w_l_ij, start_h_l_ij = round(w_0_ij / dz.f_w), round(h_0_ij / dz.f_h)
    region_0 = [w_0_ij, h_0_ij, d_h_0_ij, d_w_0_ij]
    region_l = [
        start_h_l_ij, start_h_l_ij + d_h_l_ij, start_w_l_ij,
        start_w_l_ij + d_w_l_ij
    ]
    return region_0, region_l
コード例 #25
0
    def get(self, path):
        with self._lock:
            if path in self._cache:
                # Move to end of LRU
                slide = self._cache.pop(path)
                self._cache[path] = slide
                return slide

        if path.endswith('.ndpi') and self.use_ndp_read and os.path.getsize(
                path) >= self.ndpi_size_limit:
            slide = LargeNDPiDeepZoomGenerator(path, self.dz_opts['tile_size'],
                                               self.dz_opts['overlap'])
        else:
            osr = OpenSlide(path)
            slide = DeepZoomGenerator(osr, **self.dz_opts)
            try:
                mpp_x = osr.properties[openslide.PROPERTY_NAME_MPP_X]
                mpp_y = osr.properties[openslide.PROPERTY_NAME_MPP_Y]
                slide.mpp = (float(mpp_x) + float(mpp_y)) / 2
            except (KeyError, ValueError):
                slide.mpp = 0

        with self._lock:
            if path not in self._cache:
                if len(self._cache) == self.cache_size:
                    self._cache.popitem(last=False)
                self._cache[path] = slide
        return slide
コード例 #26
0
 def _get_dz(self, associated=None):
     if associated is not None:
         image = ImageSlide(self._slide.associated_images[associated])
     else:
         image = self._slide
     return DeepZoomGenerator(image, self._tile_size, self._overlap,
                              limit_bounds=self._limit_bounds)
コード例 #27
0
def load_slide(file):
    slidefile = file
    if slidefile is None:
        raise ValueError('No slide file specified')
    config_map = {
        'DEEPZOOM_TILE_SIZE': 'tile_size',
        'DEEPZOOM_OVERLAP': 'overlap',
        'DEEPZOOM_LIMIT_BOUNDS': 'limit_bounds',
    }
    opts = dict((v, app.config[k]) for k, v in config_map.items())
    slide = open_slide(slidefile)
    left = slide.properties[
        "mirax.NONHIERLAYER_3_LEVEL_0_SECTION.COMPRESSED_STITCHING_ORIG_SLIDE_SCANNED_AREA_IN_PIXELS__LEFT"]
    top = slide.properties[
        "mirax.NONHIERLAYER_3_LEVEL_0_SECTION.COMPRESSED_STITCHING_ORIG_SLIDE_SCANNED_AREA_IN_PIXELS__TOP"]

    app.slides = {
        SLIDE_NAME: DeepZoomGenerator(slide, **opts),
        'left': left,
        'top': top
    }
    try:
        mpp_x = slide.properties[openslide.PROPERTY_NAME_MPP_X]
        mpp_y = slide.properties[openslide.PROPERTY_NAME_MPP_Y]
        app.slide_mpp = (float(mpp_x) + float(mpp_y)) / 2
        return app.slide_mpp
    except (KeyError, ValueError):
        app.slide_mpp = 0
        return 0
コード例 #28
0
    def tile_gen(self, state=9):
        """Call this function to divide the slice in tiles, it manage the dimension and the edge cuts.
        This function call the method 'manage_process' that create same vectors for the next step, run the theads"""

        self.generator = DeepZoomGenerator(self.slide,
                                           tile_size=self.tile_size,
                                           overlap=self.overlap,
                                           limit_bounds=self.limit_bounds)
        dim = self.generator.level_dimensions
        ntile = self.generator._t_dimensions

        for i, a in enumerate(dim):
            if self.list_levels[self.lev_sec][1] == a[1] or self.list_levels[
                    self.lev_sec][1] == (
                        a[1] -
                        1) or self.list_levels[self.lev_sec][1] == (a[1] + 1):
                self.levi = i
                print(
                    f'found the right level {i} -- rr = {self.list_levels[self.lev_sec][1]} --- a = {a[1]}'
                )
                print(self.list_levels)
            else:
                pass

        try:
            numx, numy = ntile[self.levi]
            print('{}---{}'.format(numx, numy))
        except IndexError:
            numx, numy = ntile[-1]
            self.levi = len(ntile) - 1
            print(
                f'------There is a problem in if, add combinations, max resolution selected------{numx},{numy}'
            )

        self.ntiles_y = numy

        numx_start, numx_stop, list_proc, start_indexs, stop_index = self.manage_process(
            numx, numy)

        if state == 0:
            return numx_start, numx_stop, list_proc, start_indexs, stop_index, numy, self.levi
        elif state == 1:
            return self.generator
        elif state == 2:
            return numx
        else:
            self.start_thread(numx_start, numx_stop, list_proc, start_indexs)
コード例 #29
0
def image(filename):
    user = current_user
    engine = db.get_engine(bind=user.dbname)
    DBSession = sessionmaker(bind=engine)
    db_session = DBSession()

    annotationsInfo = db_session.query(Annotation).filter_by(pathimage_imageid=filename).all()

    slug = slugify(filename)
    slidempp = 'slide_mpp'
    imagesize = 'imagesize'
    if not hasattr(app,'slides'):
        app.slides = {}
        print('app.slides is null')


    if not app.slides.has_key(slug):
        print('image not exsits ' + slug)
        image = db_session.query(PathImage).filter_by(filename=filename).first()
        slidefile = image.filepath
        config_map = {
            'DEEPZOOM_TILE_SIZE': 'tile_size',
            'DEEPZOOM_OVERLAP': 'overlap',
            'DEEPZOOM_LIMIT_BOUNDS': 'limit_bounds',
        }
        opts = dict((v, app.config[k]) for k, v in config_map.items())

        if 'kfb' in slidefile:
            slide = kfbslide.KfbSlide(slidefile)
            deepzoom = kfb_deepzoom.KfbDeepZoomGenerator(slide, **opts)
        else:
            slide = open_slide(slidefile)
            deepzoom = DeepZoomGenerator(slide, **opts)

        slideinfo = {SLIDE_NAME: deepzoom}

        try:
            mpp_x = slide.properties[openslide.PROPERTY_NAME_MPP_X]
            mpp_y = slide.properties[openslide.PROPERTY_NAME_MPP_Y]
            slideinfo[slidempp] = (float(mpp_x) + float(mpp_y)) / 2
        except (KeyError, ValueError):
            slideinfo[slidempp] = 0
        slideinfo[imagesize] = [int(deepzoom.level_dimensions[-1][0]), int(deepzoom.level_dimensions[-1][1])]
        slideinfo['active'] = True
        app.slides[slug] = slideinfo

    annotaions = getannotations(annotationsInfo, app.slides[slug][imagesize], db_session,user)
    db_session.close()
    slidename = SLIDE_NAME + slug
    slide_url = url_for('dzi', slug=slidename)
    return render_template("display.html",
                           user=user,
                           slide_url=slide_url,
                           slide_mpp=app.slides[slug][slidempp],
                           canlogout=True,
                           image_name=filename,
                           annotations=annotaions,
                           imagesize=app.slides[slug][imagesize]
                           )
コード例 #30
0
 def insertslide(cls, key, sl):
     opts = {
         'tile_size': settings.DEEPZOOM_TILE_SIZE,
         'overlap': settings.DEEPZOOM_OVERLAP
     }
     with cls._dict_lock:
         cls._slides[key] = sl
         cls._deepzooms[key] = DeepZoomGenerator(sl, **opts)
コード例 #31
0
    def get(self, path):
        with self._lock:
            if path in self._cache:
                # Move to end of LRU
                slide = self._cache.pop(path)
                self._cache[path] = slide
                return slide

        osr = OpenSlide(path)
        slide = DeepZoomGenerator(osr, **self.dz_opts)
        try:
            mpp_x = osr.properties[openslide.PROPERTY_NAME_MPP_X]
            mpp_y = osr.properties[openslide.PROPERTY_NAME_MPP_Y]
            slide.mpp = (float(mpp_x) + float(mpp_y)) / 2
        except (KeyError, ValueError):
            slide.mpp = 0

        with self._lock:
            if path not in self._cache:
                if len(self._cache) == self.cache_size:
                    self._cache.popitem(last=False)
                self._cache[path] = slide
        return slide
コード例 #32
0
class _BoxesDeepZoomTest(object):
    def setUp(self):
        self.osr = self.CLASS(file_path(self.FILENAME))
        self.dz = DeepZoomGenerator(self.osr, 254, 1)

    def tearDown(self):
        self.osr.close()

    def test_repr(self):
        self.assertEqual(repr(self.dz),
                ('DeepZoomGenerator(%r, tile_size=254, overlap=1, ' +
                'limit_bounds=False)') % self.osr)

    def test_metadata(self):
        self.assertEqual(self.dz.level_count, 10)
        self.assertEqual(self.dz.tile_count, 11)
        self.assertEqual(self.dz.level_tiles,
                ((1, 1), (1, 1), (1, 1), (1, 1), (1, 1),
                (1, 1), (1, 1), (1, 1), (1, 1), (2, 1)))
        self.assertEqual(self.dz.level_dimensions,
                ((1, 1), (2, 1), (3, 2), (5, 4), (10, 8),
                (19, 16), (38, 32), (75, 63), (150, 125), (300, 250)))

    def test_get_tile(self):
        self.assertEqual(self.dz.get_tile(9, (1, 0)).size, (47, 250))

    def test_get_tile_bad_level(self):
        self.assertRaises(ValueError, lambda: self.dz.get_tile(-1, (0, 0)))
        self.assertRaises(ValueError, lambda: self.dz.get_tile(10, (0, 0)))

    def test_get_tile_bad_address(self):
        self.assertRaises(ValueError, lambda: self.dz.get_tile(0, (-1, 0)))
        self.assertRaises(ValueError, lambda: self.dz.get_tile(0, (1, 0)))

    def test_get_tile_coordinates(self):
        self.assertEqual(self.dz.get_tile_coordinates(9, (1, 0)),
                ((253, 0), 0, (47, 250)))

    def test_get_tile_dimensions(self):
        self.assertEqual(self.dz.get_tile_dimensions(9, (1, 0)), (47, 250))

    def test_get_dzi(self):
        self.assertTrue('http://schemas.microsoft.com/deepzoom/2008' in
                self.dz.get_dzi('jpeg'))
コード例 #33
0
ファイル: my.py プロジェクト: Jondeen/openslide-python
#!/usr/local/bin/python
from openslide import OpenSlide
from openslide.deepzoom import DeepZoomGenerator
from PIL import Image
import Thresholding as T, numpy, cv2

slide=DeepZoomGenerator(OpenSlide("/usr/local/OpenSlideServe/data/CarlZeiss/TilOysteinAnalyse/Alphonse.tif"))
tile=slide.get_tile(15,(72,15))
t=""
tile = Image.open("colorwheel-rgb.jpg")
# print tile.getextrema()
# tile.save("orig.tif")
# t=T.Thresholder([[0,255],[0,255],[0,255]],"rgb","hsv")
# th=t.threshold_image(tile)
# th.save("new.tif")
# print th.getextrema()
a=numpy.array([255,255,0,0],dtype=numpy.uint8)
b=numpy.array([200,150,100,50],dtype=numpy.uint8)
print a
print b
print "mask:"
print a
print "image:"
print b
print "result of cv2.bitwise_and(b,b,mask=a):"
im2=cv2.bitwise_and(b,b,mask=a)
print im2
コード例 #34
0
 def setUp(self):
     self.osr = self.CLASS(file_path(self.FILENAME))
     self.dz = DeepZoomGenerator(self.osr, 254, 1)