def read_wsi_mask(self, wsi_path, mask_path):
        try:
            self.cur_wsi_path = wsi_path
            self.wsi_image = OpenSlide(wsi_path)
            self.mask_image = OpenSlide(mask_path)

            self.level_used = min(self.def_level,
                                  self.wsi_image.level_count - 1,
                                  self.mask_image.level_count - 1)

            self.mask_pil = self.mask_image.read_region(
                (0, 0), self.level_used,
                self.mask_image.level_dimensions[self.level_used])
            self.mask = np.array(self.mask_pil)

        except OpenSlideUnsupportedFormatError:
            print('Exception: OpenSlideUnsupportedFormatError')
            return False

        return True
def read_wsi_tumor(wsi_tumor_path, wsi_mask_path, resolution_level=None):

    try:

        wsi_tumor = OpenSlide(wsi_tumor_path)
        if resolution_level is None:
            resolution_level = wsi_tumor.level_count - 1
        wsi_tumor_sample = wsi_tumor.read_region(
            (0, 0), resolution_level,
            wsi_tumor.level_dimensions[resolution_level])
        wsi_tumor.close()

        wsi_tumor_mask = OpenSlide(wsi_mask_path)
        wsi_tumor_mask_sample = wsi_tumor_mask.read_region(
            (0, 0), resolution_level,
            wsi_tumor_mask.level_dimensions[resolution_level])
        wsi_tumor_mask.close()
    except Exception as e:
        return None, None

    return wsi_tumor_sample, wsi_tumor_mask_sample
Beispiel #3
0
def get_label(path):
    """
    gets the label image of a wsi using openslide

    :param path str: path to the wsi
    returns pil image of label or 1 for fail
    """
    try:
        image = OpenSlide(path)  # open svs image
        return image.associated_images["label"]
    except KeyError as e:
        return 1
Beispiel #4
0
 def __init__(self, image_path):
     super(Slide, self).__init__()
     self.image_path = image_path.strip()
     self.image_file = os.path.basename(image_path)
     self.image_name, self.suffix = self.image_file.split('.')
     if not self.suffix in config.format_mapping.keys():
         raise Exception('Error: File format ' + self.suffix +
                         ' is supported yet.')
     self._slide = OpenSlide(image_path)
     self._level_downsamples = self._slide.level_downsamples
     self._level_dimensions = self._slide.level_dimensions
     self.width, self.height = self._level_dimensions[0]
    def sample_tumor_coord(self,
                           coords_path: str,
                           wsi_path: str,
                           mask_path: str,
                           annot_path: str,
                           wsi_level: int = 0):
        '''Sample a center coordinate of a normal patch from
    
        - Args
            coords_path: Path to the pre-sampled tumor coordinates
            wsi_path: Path to the wsi
            mask_path: Path to the binary mask of wsi
            annot_path: Path to the annotations directory
            wsi_level: Level of the given wsi

        - Returns
            A center coordinate of tumor patch; tuple of int
        '''
        # If the cache of tumor coordinates(tumor_coords.json) does not exist
        if not os.path.exists(coords_path):
            slide = OpenSlide(wsi_path)
            slide_width, slide_height = slide.level_dimensions[wsi_level]

            roi_mask = np.load(mask_path)
            roi_mask_width, roi_mask_height = roi_mask.shape

            assert (slide_width // roi_mask_width) == (slide_height // roi_mask_height), \
                f'Dimension does not match: slide_width({slide_width})//mask_width({roi_mask_width}) != \
                    slide_height({slide_height})//mask_height({roi_mask_height})'

            resolution = slide_width // roi_mask_width

            roi_x_coords, roi_y_coords = np.where(roi_mask)
            roi_coords = zip(roi_x_coords, roi_y_coords)
            roi_coords = list(roi_coords)
            roi_coords = [
                self.scale_coord(coord, resolution) for coord in roi_coords
            ]
            roi_coords = np.array(roi_coords)

            lesion_annots = LesionAnnotations(annot_path)
            tumor_coords = lesion_annots.filter_tumor_coords(coords_path,
                                                             roi_coords,
                                                             is_pos=True)
        # If the cache of tumor coordinates(tumor_coords.json) exists
        else:
            with open(coords_path, 'r', encoding='utf-8') as f:
                tumor_coords_dict = json.load(f)
                tumor_coords = tumor_coords_dict['tumor_coords']

        picked_tumor_coord = random.choice(tumor_coords)

        return picked_tumor_coord
Beispiel #6
0
def tile(image_file, outdir, level, std_img, path_to_slide=str(cwd+"/../images/"), dp=None, ft=1):
    slide = OpenSlide(path_to_slide+image_file)
    slp = str(path_to_slide+image_file)
    print(slp)
    print(slide.level_dimensions)

    bounds_width = slide.level_dimensions[level][0]
    bounds_height = slide.level_dimensions[level][1]
    x = 0
    y = 0
    half_width_region = 49*ft
    full_width_region = 299*ft
    stepsize = (full_width_region - half_width_region)

    n_x = int((bounds_width - 1) / stepsize)
    n_y = int((bounds_height - 1) / stepsize)

    lowres = slide.read_region((x, y), level+1, (int(n_x*stepsize/4), int(n_y*stepsize/4)))
    lowres = np.array(lowres)[:,:,:3]

    x0 = 0
    # create multiporcessing pool
    print(mp.cpu_count())
    pool = mp.Pool(processes=mp.cpu_count())
    tasks = []
    while x0 < n_x:
        task = tuple((slp, n_y, x, y, full_width_region, stepsize, x0, outdir, level, dp, std_img))
        tasks.append(task)
        x0 += 1
    # slice images with multiprocessing
    temp = pool.starmap(v_slide, tasks)
    tempdict = list(temp)
    temp = None
    pool.close()
    pool.join()

    tempdict = list(filter(None, tempdict))
    imloc = []
    list(map(imloc.extend, tempdict))
    imlocpd = pd.DataFrame(imloc, columns = ["X_pos", "Y_pos", "X", "Y", "Loc"])
    imlocpd = imlocpd.sort_values(["X_pos", "Y_pos"], ascending=[True, True])
    imlocpd = imlocpd.reset_index(drop=True)
    imlocpd = imlocpd.reset_index(drop=False)
    imlocpd.columns = ["Num", "X_pos", "Y_pos", "X", "Y", "Loc"]
    if dp:
        imlocpd.to_csv(outdir + "/{}_dict.csv".format(dp), index=False)
    else:
        imlocpd.to_csv(outdir + "/dict.csv", index=False)
    tempdict = None
    ct = len(imloc)
    print(ct)

    return n_x, n_y, lowres, ct
def get_slide(fn_slide):
    if not exists(fn_slide):
        print('This file does NOT exist. Check the path : ' + fn_slide)
        slide = None
        return slide
    try:
        slide = OpenSlide(fn_slide)
    except:
        print('Can NOT open this slide with OpenSlide : ' + fn_slide)
        print('I do not know why. Just can not read !!')
        slide = None
    return slide
def process(opts):
    i, pid, x_center, y_center, file_path_tif, path_patch, patch_size, patch_level = opts
    x = int(int(float(x_center)) - 1024 / 2)
    y = int(int(float(y_center)) - 1024 / 2)
    wsi_path = os.path.join(file_path_tif + pid + '.svs')
    slide = OpenSlide(wsi_path)
    img = slide.read_region((x, y), 0, (1024, 1024)).convert('RGB')
    if not os.path.exists(os.path.join(path_patch,
                                       pid + "_" + str(i) + '.png')):

        print(os.path.join(path_patch, pid + "_" + str(i) + '.png'))
        img.save(os.path.join(path_patch, pid + "_" + str(i) + '.png'))
Beispiel #9
0
def load_image(fn, mode=None):
    "Open and load a `PIL.Image` and convert to `mode`"

    wsi_name, x, y, level, crop_size = fn.split(',')
    x=int(x); y=int(y); level=int(level); crop_size=int(crop_size)
    
    im = OpenSlide(wsi_name[2:]).read_region((x, y), 
                                             level, 
                                             (crop_size, crop_size))
    
    im = im._new(im.im)
    return im.convert(mode) if mode else im
    def read_wsi_mask(mask_path, level=def_level):
        try:
            wsi_mask = OpenSlide(mask_path)

            mask_image = np.array(wsi_mask.read_region((0, 0), level,
                                                       wsi_mask.level_dimensions[level]))

        except OpenSlideUnsupportedFormatError:
            print('Exception: OpenSlideUnsupportedFormatError')
            return None, None

        return wsi_mask, mask_image
Beispiel #11
0
def get_thumbnails():
    import os
    from openslide import OpenSlide

    data_dir = '/media/hui/Local Disk1/work/Data/Liver_Multi_Modality/Pathology/SlideImages/20-1018 PURU_VINOD'
    save_dir = '/media/hui/Local Disk1/work/Data/Liver_Multi_Modality/Pathology/thumbnails'
    os.makedirs(save_dir, exist_ok=True)
    filelist = os.listdir(data_dir)

    for file in filelist:
        wsi_file = OpenSlide('{:s}/{:s}'.format(data_dir, file))
        thumbnail = wsi_file.get_thumbnail((1000, 1000))
        thumbnail.save('{:s}/{:s}.png'.format(save_dir, file.split('.')[0]))
Beispiel #12
0
def check_wsi(num):
    folder_name = 'patient_' + num
    folder_dir = root_dir + folder_name + '/'
    files_list = os.listdir(folder_dir)

    for filename in files_list:
        file_path = folder_dir + filename
        try:
            slide = OpenSlide(file_path)
            print("Slide is ok: {}".format(filename))
        except:
            print("Error opening {}".format(filename))
            continue
Beispiel #13
0
def read_image(image_path):
    try:
        image = OpenSlide(image_path)
        w, h = image.dimensions
        n = int(math.floor((h - 0) / 224))
        m = int(math.floor((w - 0) / 224))
        level = image.level_count - 1
        downsample_image = np.array(image.read_region((0, 0), level, image.level_dimensions[level]))
    except OpenSlideUnsupportedFormatError:
        print('Exception: OpenSlideUnsupportedFormatError')
        return None, None, None, None

    return image, downsample_image, level, m, n
def getImageTiles(filenameImage, filenameXML, size=128):

    #Getting the appropriate upper left coordinates
    rRegionList = getCoordinates(filenameXML, size)

    image = OpenSlide(filenameImage)

    regionList = []

    for region in tqdm(rRegionList):
        regionImg = image.read_region(region, 0, (size, size))
        regionList.append(regionImg)

    return regionList
Beispiel #15
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
     slide = DeepZoomGenerator(OpenSlide(path), **self.dz_opts)
     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
Beispiel #16
0
def get_image_metadata():
    """
    Read slide and process
    :return:
    """
    p = Path(os.path.join(SLIDE_DIR, (CASE_ID + '.svs')))
    osr = OpenSlide(str(p))
    # props = osr.properties
    # props.__getitem__('openslide.level[0].width')
    # props.__getitem__('openslide.level[0].height')
    image_width = osr.dimensions[0]
    image_height = osr.dimensions[1]
    osr.close()
    return image_width, image_height
Beispiel #17
0
def export_images(slide_pos_by_global,
                  slidedir,
                  leaves_by_trunc,
                  outfolder,
                  slidetype=".mrxs",
                  level=1,
                  size=299,
                  maxperconcept=1000):
    """
    Export images for every truncated leaf.

    Loop over slides,
    For every patch in slide,
    extract patch and put it in the right folder.
    """
    # Now, for every significant leaf concept, we get the corresponding images and store them
    significant_concept_counter = 1
    for trunc, leaves in leaves_by_trunc.items():
        print("processing significant concept {} / {}".format(significant_concept_counter,
                                                              len(leaves_by_trunc)))
        print("#" * 20)
        # create the directory if does not exists
        folder = os.path.join(outfolder, str(trunc))
        if not os.path.exists(folder):
            print("creating significant concept folder")
            os.makedirs(folder)
        # get unique slidenames in leaf_concepts as well as their count
        names, c = numpy.unique([slide_pos_by_global[idx]["Slidename"] for idx in leaves], return_counts=True)
        print("significant concept id={} has {} leaf-concepts".format(trunc, len(leaves)))
        print("leaf-concepts lay in {} different slides".format(len(names)))
        n_per_slide = int(float(maxperconcept) / c.sum())
        subconcept_counter = 1
        for global_id in leaves:
            # It is obvious that one global_id can only have one slidename.
            slidename = slide_pos_by_global[global_id]["Slidename"]
            positions = slide_pos_by_global[global_id]["Positions"]
            print("- processing concept {} / {}  |  id={}  |  slidename={}  |  patch extraction={}".format(subconcept_counter,
                                                                                                           len(leaves),
                                                                                                           global_id,
                                                                                                           slidename,
                                                                                                           n_per_slide))

            for p in numpy.random.permutation(positions)[0:min(n_per_slide, len(positions))]:
                slidepath = os.path.join(slidedir, slidename + slidetype)
                slide = OpenSlide(slidepath)
                image = slide.read_region(p, level, (size, size))
                image = numpy.array(image)[:, :, 0:3]
                imsave(os.path.join(folder, "{}_{}_{}.png".format(slidename, p[0], p[1])), image)
            subconcept_counter += 1
        significant_concept_counter += 1
def save_slide_cutting(file_path, save_location, level):
    slide = OpenSlide(file_path)
    print('==> saving slide_lv_' + str(level) + ' at ' + save_location)
    x_lv_, y_lv_ = 0, 0
    w_lv_, h_lv_ = slide.level_dimensions[level]
    try:
        wsi_pil_lv_ = slide.read_region((0, 0), level, \
                                        (w_lv_, h_lv_))

        wsi_ary_lv_ = np.array(wsi_pil_lv_)
        wsi_bgr_lv_ = cv2.cvtColor(wsi_ary_lv_, cv2.COLOR_RGBA2BGR)
        cv2.imwrite(save_location, wsi_bgr_lv_)
    except:
        print(file_path)
Beispiel #19
0
    def read_wsi_tumor(self, wsi_path, mask_path):
        """
            # =====================================================================================
            # read WSI image and resize
            # Due to memory constraint, we use down sampled (4th level, 1/32 resolution) image
            # ======================================================================================
        """
        try:
            self.cur_wsi_path = wsi_path
            self.wsi_image = OpenSlide(wsi_path)
            self.mask_image = OpenSlide(mask_path)

            self.level_used = min(self.def_level, self.wsi_image.level_count - 1, self.mask_image.level_count - 1)

            self.rgb_image_pil = self.wsi_image.read_region((0, 0), self.level_used,
                                                            self.wsi_image.level_dimensions[self.level_used])
            self.rgb_image = np.array(self.rgb_image_pil)

        except OpenSlideUnsupportedFormatError:
            print('Exception: OpenSlideUnsupportedFormatError')
            return False

        return True
Beispiel #20
0
def export_segimages(slide, data,outputfolder,filename):
    cmap = matplotlib.cm.viridis
    norm = mpl.colors.Normalize(vmin=0, vmax=1)
    if not os.path.exists(outputfolder):
        os.makedirs(outputfolder)

    # compute segmentation image
    xs = list()
    ys = list()
    for patch in data.keys():
        xs.append(data[patch]['x'])
        ys.append(data[patch]['y'])
    xmin = min(xs)
    xmax = max(xs)
    ymin = min(ys)
    ymax = max(ys)
    print(xmin,xmax,ymin,ymax)
    dx = xmax - xmin
    dy = ymax - ymin

    segimage = numpy.zeros((int(dy / args.delta) + 1, int(dx / args.delta) + 1, 3), float)
    print("created image's shape ",segimage.shape)

    for patch in data.keys():
        x = data[patch]['x'] - xmin
        y = data[patch]['y'] - ymin
        x = int(x / args.delta)
        y = int(y / args.delta)
        
        #Implemented for a binary classification problem
        if data[patch]['feature'][0] > 0.5 and data[patch]['var'][0] < args.var:
            segimage[y, x, 0] = 1.0
            segimage[y, x, 1] = 1.0
            segimage[y, x, 2] = 1.0
        if data[patch]['feature'][1] > 0.5 and data[patch]['var'][1] < args.var:
            segimage[y, x, 0] = 1.0
            segimage[y, x, 1] = 0.0
            segimage[y, x, 2] = 0.0

    imsave(os.path.join(outputfolder, filename+'_'+str(args.var)+"_hypothese.png"), img_as_ubyte(segimage))
    print("working on ",slide)


    slide = OpenSlide(slide)
    img = slide.read_region((0, 0),7, slide.level_dimensions[7])
    img = numpy.array(img)[:, :, 0:-1]
    
    empty_img = numpy.zeros(shape=(img.shape),dtype='uint8')
    print('shape vide = ',empty_img.shape)
    imsave(os.path.join(outputfolder, filename+"empty.png"), empty_img)
Beispiel #21
0
def denoising(inputsvs,
              magnification="20x",
              filtering="GaussianBlur",
              patch_size=(256, 256),
              upperlimit=1100,
              lowerlimit=300,
              red_value=(80, 220),
              green_value=(80, 200),
              blue_value=(80, 170),
              Annotation=None,
              Annotatedlevel=0,
              Requiredlevel=0):
    slide = OpenSlide(inputsvs)
    slide_dimensions = slide.level_dimensions
    img, slide_dimensions = readWSI(inputsvs, magnification, Annotation,
                                    Annotatedlevel, Requiredlevel)
    dictx = dictionary(slide_dimensions)
    if filtering == "GaussianBlur":
        out = denoising_using_GaussianBlur(inputsvs, magnification, dictx,
                                           patch_size, upperlimit, lowerlimit,
                                           Annotation, Annotatedlevel,
                                           Requiredlevel)
    elif filtering == "RGB":
        mask = denoising_RGB_Thersholding(img, slide_dimensions, magnification,
                                          dictx, patch_size, red_value,
                                          green_value, blue_value)
        out = np.zeros_like(img)
        print("cleaning image at high mignification")
        mask = mask.astype(np.bool)
        out[mask] = img[mask]
        out = np.where(out != [0, 0, 0], out, [255, 255, 255])
        print("cleaning WSI done")
        #     cv2.imwrite("/home/pagenet2/PageNet2/Data Preprocessing Pipeline/WSI_Precessing_test/cleanedimages/%s/cleanedsmallf.png"%(inputsvs.split("/")[-1][:-4]),out)
        garbage_collector()
        print("exisiting cleaning")

    else:
        mask = denoising_No_filters(img, slide_dimensions, magnification,
                                    dictx)
        out = np.zeros_like(img)
        print("cleaning image at high mignification")
        mask = mask.astype(np.bool)
        out[mask] = img[mask]
        out = np.where(out != [0, 0, 0], out, [255, 255, 255])
        print("cleaning WSI done")
        #     cv2.imwrite("/home/pagenet2/PageNet2/Data Preprocessing Pipeline/WSI_Precessing_test/cleanedimages/%s/cleanedsmallf.png"%(inputsvs.split("/")[-1][:-4]),out)
        garbage_collector()
        print("exisiting cleaning")
    return out
Beispiel #22
0
def convert_image(path_img, level=DEFAULT_LEVEL, overwrite=False):
    """ convert TIFF/SVS image to standard format
    The output image has the same name and it is exported in the same folder

    :param str path_img: path to the input image
    :param int level: selected level of the internal pyramid representation
        the level 0 means full scale and higher number is small image in pyramid scaling
    :param bool overwrite: whether overwrite existing image on output
    """
    slide_img = OpenSlide(path_img)
    if level >= len(slide_img.level_dimensions):
        raise ValueError('unsupported level %i of %i' %
                         (level, slide_img.level_count))

    path_img_new = os.path.splitext(path_img)[0] + IMAGE_EXTENSION
    if os.path.isfile(path_img_new) and not overwrite:
        logging.warning('existing "%s"', path_img_new)
        return

    level_size = slide_img.level_dimensions[level]
    level_scale = slide_img.level_downsamples[level]

    level_downsample = 1
    while max(np.array(level_size) / level_downsample) > MAX_LOAD_IMAGE_SIZE:
        level_downsample *= 2
    logging.debug('using down-sample: %i', level_downsample)

    tile_size = (np.array(level_size) / level_downsample).astype(int)
    locations = [(i * tile_size[0], j * tile_size[1])
                 for i in range(level_downsample)
                 for j in range(level_downsample)]
    im = np.array(slide_img.read_region((0, 0), 0, size=(10, 10)))
    nb_channels = min(3, im.shape[2]) if im.ndim == 3 else 1
    img_size = list(tile_size * level_downsample)[::-1] + [nb_channels]
    image = np.zeros(img_size, dtype=np.uint8)
    for loc_i, loc_j in tqdm.tqdm(locations, desc=os.path.basename(path_img)):
        loc_img = int(loc_i * level_scale), int(loc_j * level_scale)
        img = np.array(slide_img.read_region(loc_img, level, size=tile_size))
        image[loc_j:loc_j + img.shape[0], loc_i:loc_i + img.shape[1],
              ...] = img[:, :, :nb_channels]
        del img

    if nb_channels == 2:
        image = image[:, :, 0]

    logging.debug('save image: "%s"', path_img_new)
    cv.imwrite(path_img_new, image, params=(cv.IMWRITE_PNG_COMPRESSION, 9))
    gc.collect()
    time.sleep(1)
Beispiel #23
0
def conver_axis_to_large_mrxs(xmin, ymin, xmax, ymax, mrxs_filename, image,
                              index):
    overlap_ratio = 10
    osr = OpenSlide(mrxs_filename)
    props = osr.properties
    w, h = osr.level_dimensions[0]
    nums = round(w / image.shape(1))

    xmin_change = xmin / ww_ratio
    ymin_change = ymin / hh_ratio
    xmax_change = xmax / ww_ratio
    ymax_change = ymax / hh_ratio

    [x1 + xmin_change, y1 + ymin_change, x2 + xmax_change, y2 + ymax_change]
    return xmin, ymin, xmax, ymax
Beispiel #24
0
def get_property(request, slide_id):
    try:
        s = Alopecia.objects.get(pk=slide_id)
    except Alopecia.DoesNotExist:
        raise Http404

    if s.SlideType == 2:
        file = path.join(settings.HISTOSLIDE_SLIDEROOT, str(s.UrlPath))
        slide = OpenSlide(file)
        return JsonResponse({
            'status': 'success',
            'data': dict(slide.properties)
        })
    else:
        return JsonResponse({'status': 'success', 'data': dict()})
Beispiel #25
0
def load_tile(
        slide_path: str,
        width: int,
        downscale: int,
        coords: Tuple[int, Tuple[int, int]]):
    # Load slide from global.
    reader = OpenSlide(slide_path)
    i, (x, y) = coords
    out_shape = (int(width/downscale), int(width/downscale))
    try:
        tile = reader.read_region((x, y), 0, (width, width)).convert('RGB')
        tile = cv2.resize(np.array(tile), out_shape, cv2.INTER_LANCZOS4)
    except:
        tile = np.zeros(out_shape + (3,)).astype(np.uint8)
    return i, tile
Beispiel #26
0
def get_label(slide, slide_name, masks_dir):
    h, w = slide.level_dimensions[_SAMPLE_LEVEL]
    label_mask = np.full((w, h), False)
    label_slide = None

    label_path = masks_dir / f'{slide_name}_Mask.tif'

    if label_path.is_file():
        label_slide = OpenSlide(str(label_path))
        label_dim = label_slide.level_dimensions[_SAMPLE_LEVEL]
        label_img = label_slide.read_region((0, 0), _SAMPLE_LEVEL, label_dim)
        label_img = np.array(label_img.convert('L'))
        init_label(label_mask, label_img)

    return label_mask, label_slide
Beispiel #27
0
def save_level_images(input_folder, output_folder, level):
    ndpi_id = ndpi_file[:-5]
    ndpi_path = os.path.join(input_folder, ndpi_file)
    ndpi_slide = OpenSlide(ndpi_path)

    width = ndpi_slide.level_dimensions[level][0]
    height = ndpi_slide.level_dimensions[level][1]

    image = ndpi_slide.read_region((0, 0), level, (width, height))
    image = np.array(image)
    if image.shape[2] > 3:
        image = image[:, :, 0:3]  # convert from RGBA to RGB

    image_path = os.path.join(output_folder, ndpi_id + '.tif')
    skimage.io.imsave(image_path, image)
Beispiel #28
0
def process(opts):
    i, pid, x, y, file_path_tif, patch_path, patch_size, patch_level, class_dir = opts
    dir = pid.split("/")[-1]
    dir_split = dir.split("-")[:3]
    dir_name = dir_split[0] + '-' + dir_split[1] + '-' + dir_split[2]

    x = int(float(x))
    y = int(float(y))
    wsi_path = os.path.join(file_path_tif, dir + '.svs')

    slide = OpenSlide(wsi_path)
    img = slide.read_region((x, y), 1, (256, 256))
    wsi_ary_lv_ = np.array(img)
    img = cv2.cvtColor(wsi_ary_lv_, cv2.COLOR_RGBA2BGR)
    cv2.imwrite(os.path.join(class_dir, dir_name + "_" + str(i) + '.png'), img)
Beispiel #29
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
Beispiel #30
0
def split_region_around(max_length, image_num, file_dir):
    osr = OpenSlide(file_dir + '.mrxs')
    props = osr.properties
    axis_list = read_label(file_dir)

    for ID, axis in axis_list:
        print("axis:", axis)
        width = float(axis[2]) - float(axis[0])
        height = float(axis[3]) - float(axis[1])
        print("width:", width, ",height:", height)
        label_list = []
        for i in range(image_num):
            #print(props)
            radioX = random.uniform(0, 1 - width / max_length)
            radioY = random.uniform(0, 1 - height / max_length)
            crop_xl = math.floor(max(float(axis[0]) - max_length * radioX, 0))
            crop_yl = math.floor(max(float(axis[1]) - max_length * radioY, 0))
            crop_xr = crop_xl + max_length
            crop_yr = crop_yl + max_length
            #print("crop_xl:", crop_xl)
            img = osr.read_region((crop_xl, crop_yl), 0,
                                  (max_length, max_length)).convert("RGB")
            #draw = ImageDraw.Draw(img)
            #draw.rectangle((radioX * max_length, radioY * max_length, width, height), None, "red")
            labelxmin = math.floor(radioX * max_length)
            labelymin = math.floor(radioY * max_length)
            labelxmax = math.floor(radioX * max_length + width)
            labelymax = math.floor(radioY * max_length + height)
            label_list.append([labelxmin, labelymin, labelxmax, labelymax])
            for ID_other, axis_other in axis_list:
                width_other = float(axis_other[2]) - float(axis_other[0])
                height_other = float(axis_other[3]) - float(axis_other[1])
                labelxmin_other = max(math.floor(axis_other[0]), crop_xl)
                labelymin_other = max(math.floor(axis_other[1]), crop_yl)
                labelxmax_other = min(math.floor(axis_other[2]), crop_xr)
                labelymax_other = min(math.floor(axis_other[3]), crop_yr)
                if labelxmin_other == labelxmin and labelymin_other == labelymin and labelxmax_other == labelxmax \
                        and labelymax_other == labelymax:
                    continue
                if width_other > max_length or height_other > max_length:
                    logger.error(
                        "The label box is too large, its width or height is bigger than the crop max /"
                        "length {}".format(max_length))
                    continue
                label_list.append([
                    labelxmin_other, labelymin_other, labelxmax_other,
                    labelymax_other
                ])