本文整理汇总了Python中openslide.OpenSlide方法的典型用法代码示例。如果您正苦于以下问题:Python openslide.OpenSlide方法的具体用法?Python openslide.OpenSlide怎么用?Python openslide.OpenSlide使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类openslide
的用法示例。
在下文中一共展示了openslide.OpenSlide方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
def process(opts):
i, pid, x_center, y_center, args = opts
x = int(int(x_center) - args.patch_size / 2)
y = int(int(y_center) - args.patch_size / 2)
wsi_path = os.path.join(args.wsi_path, pid + '.tif')
slide = openslide.OpenSlide(wsi_path)
img = slide.read_region(
(x, y), args.level,
(args.patch_size, args.patch_size)).convert('RGB')
img.save(os.path.join(args.patch_path, str(i) + '.png'))
global lock
global count
with lock:
count.value += 1
if (count.value) % 100 == 0:
logging.info('{}, {} patches generated...'
.format(time.strftime("%Y-%m-%d %H:%M:%S"),
count.value))
示例2: run
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
def run(args):
logging.basicConfig(level=logging.INFO)
slide = openslide.OpenSlide(args.wsi_path)
# note the shape of img_RGB is the transpose of slide.level_dimensions
img_RGB = np.transpose(np.array(slide.read_region((0, 0),
args.level,
slide.level_dimensions[args.level]).convert('RGB')),
axes=[1, 0, 2])
img_HSV = rgb2hsv(img_RGB)
background_R = img_RGB[:, :, 0] > threshold_otsu(img_RGB[:, :, 0])
background_G = img_RGB[:, :, 1] > threshold_otsu(img_RGB[:, :, 1])
background_B = img_RGB[:, :, 2] > threshold_otsu(img_RGB[:, :, 2])
tissue_RGB = np.logical_not(background_R & background_G & background_B)
tissue_S = img_HSV[:, :, 1] > threshold_otsu(img_HSV[:, :, 1])
min_R = img_RGB[:, :, 0] > args.RGB_min
min_G = img_RGB[:, :, 1] > args.RGB_min
min_B = img_RGB[:, :, 2] > args.RGB_min
tissue_mask = tissue_S & tissue_RGB & min_R & min_G & min_B
np.save(args.npy_path, tissue_mask)
示例3: __init__
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
def __init__(self, path):
self.slide = openslide.OpenSlide(path)
示例4: _preprocess
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
def _preprocess(self):
self._mask = np.load(self._mask_path)
self._slide = openslide.OpenSlide(self._wsi_path)
X_slide, Y_slide = self._slide.level_dimensions[0]
X_mask, Y_mask = self._mask.shape
if X_slide / X_mask != Y_slide / Y_mask:
raise Exception('Slide/Mask dimension does not match ,'
' X_slide / X_mask : {} / {},'
' Y_slide / Y_mask : {} / {}'
.format(X_slide, X_mask, Y_slide, Y_mask))
self._resolution = X_slide * 1.0 / X_mask
if not np.log2(self._resolution).is_integer():
raise Exception('Resolution (X_slide / X_mask) is not power of 2 :'
' {}'.format(self._resolution))
# all the idces for tissue region from the tissue mask
self._X_idcs, self._Y_idcs = np.where(self._mask)
self._idcs_num = len(self._X_idcs)
if self._image_size % self._patch_size != 0:
raise Exception('Image size / patch size != 0 : {} / {}'.
format(self._image_size, self._patch_size))
self._patch_per_side = self._image_size // self._patch_size
self._grid_size = self._patch_per_side * self._patch_per_side
示例5: __init__
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
def __init__(self, fname, fname_outdir, params):
dict.__init__(self)
self["warnings"] = [''] # this needs to be first key in case anything else wants to add to it
self["output"] = []
# these 2 need to be first for UI to work
self.addToPrintList("filename", os.path.basename(fname))
self.addToPrintList("comments", " ")
self["outdir"] = fname_outdir
self["dir"] = os.path.dirname(fname)
self["os_handle"] = openslide.OpenSlide(fname)
self["image_base_size"] = self["os_handle"].dimensions
self["image_work_size"] = params.get("image_work_size", "1.25x")
self["mask_statistics"] = params.get("mask_statistics", "relative2mask")
self["base_mag"] = getMag(self, params)
self.addToPrintList("base_mag", self["base_mag"])
mask_statistics_types = ["relative2mask", "absolute", "relative2image"]
if (self["mask_statistics"] not in mask_statistics_types):
logging.error(
f"mask_statistic type '{self['mask_statistics']}' is not one of the 3 supported options relative2mask, absolute, relative2image!")
exit()
self["img_mask_use"] = np.ones(self.getImgThumb(self["image_work_size"]).shape[0:2], dtype=bool)
self["img_mask_force"] = []
self["completed"] = []
示例6: output_jpeg_tiles
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
def output_jpeg_tiles(image_name, output_path): # converts svs image with meta data into just the jpeg image
img = openslide.OpenSlide(image_name)
width, height = img.level_dimensions[0]
increment_x = int(ceil(width / window_size))
increment_y = int(ceil(height / window_size))
print("converting", image_name, "with width", width, "and height", height)
for incre_x in range(increment_x): # have to read the image in patches since it doesn't let me do it for larger things
for incre_y in range(increment_y):
begin_x = window_size * incre_x
end_x = min(width, begin_x + window_size)
begin_y = window_size * incre_y
end_y = min(height, begin_y + window_size)
patch_width = end_x - begin_x
patch_height = end_y - begin_y
patch = img.read_region((begin_x, begin_y), 0, (patch_width, patch_height))
patch.load()
patch_rgb = Image.new("RGB", patch.size, (255, 255, 255))
patch_rgb.paste(patch, mask=patch.split()[3])
# compress the image
patch_rgb = patch_rgb.resize((int(patch_rgb.size[0] / compression_factor), int(patch_rgb.size[1] / compression_factor)), Image.ANTIALIAS)
# save the image
output_subfolder = join(output_path, image_name.split('/')[-1][:-4])
if not os.path.exists(output_subfolder):
os.makedirs(output_subfolder)
output_image_name = join(output_subfolder, image_name.split('/')[-1][:-4] + '_' + str(incre_x) + '_' + str(incre_y) + '.jpg')
patch_rgb.save(output_image_name)
示例7: make_tissue_mask
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
def make_tissue_mask():
''' make tissue mask using binary threshold and otsu threshold
return tissue mask array which has tissue locations
'''
slide = openslide.OpenSlide(cf.demo_slide_path)
tissue_mask = slide.read_region((0,0), hp.mask_level, slide.level_dimensions[hp.mask_level])
tissue_mask = cv2.cvtColor(np.array(tissue_mask), cv2.COLOR_RGBA2RGB)
tissue_mask = cv2.cvtColor(tissue_mask, cv2.COLOR_BGR2HSV)
tissue_mask = tissue_mask[:, :, 1]
_, tissue_mask = cv2.threshold(tissue_mask, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
tissue_mask = np.array(tissue_mask)
return tissue_mask
示例8: make_patch
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
def make_patch(tissue_mask):
''' extract patches in the whole slide using tissue mask
return patch list and patch location
Args:
tissue_mask (numpy array): tissue mask list
'''
slide = openslide.OpenSlide(cf.demo_slide_path)
p_size = hp.patch_size
width, height = np.array(slide.level_dimensions[0])//304
total = width * height
all_cnt, patch_cnt = 0,0
step = int(p_size/(2**MASK_LV))
patch_list = []
patch_location = []
for i in range(width):
for j in range(height):
tissue_mask_sum = tissue_mask[step * j : step * (j+1),
step * i : step * (i+1)].sum()
tissue_mask_max = step * step * 255
tissue_area_ratio = tissue_mask_sum / tissue_mask_max
if tissue_area_ratio > hp.tissue_threshold:
patch = np.array(slide.read_region((p_size*i, p_size*j),0,(p_size,p_size)))
patch = cv2.cvtColor(patch, cv2.COLOR_RGBA2RGB)
patch_list.append(patch)
patch_location += [[i,j]]
patch_cnt += 1
all_cnt +=1
print('\rProcess: %.3f%%, All Patch: %d, Tissue Patch: %d'
%(100.*all_cnt/total, all_cnt, patch_cnt), end='')
patch_list = np.array(patch_list)
patch_location = np.array(patch_location)
return patch_list, patch_location
示例9: get_dimension
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
def get_dimension(lv, patch_size):
''' get width and height of level and return them
Args:
lv (int): level of slide
patch_size(int): patch size
'''
slide = openslide.OpenSlide(cf.demo_slide_path)
width, height = np.array(slide.level_dimensions[lv])//patch_size
return width, height
示例10: convert_image
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
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)
assert level < len(slide_img.level_dimensions), \
'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)
示例11: make_mask
# 需要导入模块: import openslide [as 别名]
# 或者: from openslide import OpenSlide [as 别名]
def make_mask(slide_num, mask_level):
'''make tumor, normal, tissue mask using xml files and otsu threshold
Args:
slide_num (int): number of slide
mask_level (int): level of mask
'''
# path setting
slide_path = make_dir(slide_num, 'slide')
map_path = make_dir(slide_num, 'map')
mask_folder_path = make_dir(slide_num, 'mask')
tumor_mask_path = make_dir(slide_num, 'tumor_mask')
tissue_mask_path = make_dir(slide_num, 'tissue_mask')
normal_mask_path = make_dir(slide_num, 'normal_mask')
#slide loading
slide = openslide.OpenSlide(slide_path)
slide_map = np.array(slide.get_thumbnail(slide.level_dimensions[hp.map_level]))
# xml loading
coors_list = read_xml(slide_num, mask_level)
# draw boundary of tumor in map
for coors in coors_list:
cv2.drawContours(slide_map, np.array([coors]), -1, 255, 1)
cv2.imwrite(map_path, slide_map)
# check tumor mask / draw tumor mask
tumor_mask_exist = chk_file(mask_folder_path, 'b' + str(slide_num) + '_tumor_mask.png')
if tumor_mask_exist == False:
tumor_mask = np.zeros(slide.level_dimensions[mask_level][::-1])
for coors in coors_list:
cv2.drawContours(tumor_mask, np.array([coors]), -1, 255, -1)
cv2.imwrite(tumor_mask_path, tumor_mask)
# check tissue mask / draw tissue mask
tissue_mask_exist = chk_file(mask_folder_path, 'b' + str(slide_num) + '_tissue_mask.png')
if tissue_mask_exist == False:
slide_lv = slide.read_region((0, 0), mask_level, slide.level_dimensions[mask_level])
slide_lv = cv2.cvtColor(np.array(slide_lv), cv2.COLOR_RGBA2RGB)
slide_lv = cv2.cvtColor(slide_lv, cv2.COLOR_BGR2HSV)
slide_lv = slide_lv[:, :, 1]
_,tissue_mask = cv2.threshold(slide_lv, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imwrite(tissue_mask_path, np.array(tissue_mask))
# check normal mask / draw normal mask
normal_mask_exist = chk_file(mask_folder_path, 'b' + str(slide_num) + '_normal_mask.png')
if normal_mask_exist == False:
tumor_mask = cv2.imread(tumor_mask_path, 0)
height, width = np.array(tumor_mask).shape
for i in range(width):
for j in range(height):
if tumor_mask[j][i] > 127:
tissue_mask[j][i] = 0
normal_mask = np.array(tissue_mask)
cv2.imwrite(normal_mask_path, normal_mask)