在这里插入代码片
import os
import numpy as np
import cv2
import json
from PIL import Image
import openslide
from tqdm import tqdm
#export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libffi.so.7
os.environ['LD_PRELOAD'] = '/usr/lib/x86_64-linux-gnu/libffi.so.7'
def run(wsi_path,level,json_path):
# get the level * dimensions e.g. tumor0.tif level 6 shape (1589, 7514)
slide = openslide.OpenSlide(wsi_path)
w, h = slide.level_dimensions[level]
mask_tumor = np.zeros((h, w)) # the init mask, and all the value is 0
# get the factor of level * e.g. level 6 is 2^6
factor = slide.level_downsamples[level]
with open(json_path) as f:
dicts = json.load(f)
tumor_polygons = dicts['positive']
for tumor_polygon in tumor_polygons:
name = tumor_polygon["name"]
vertices = np.array(tumor_polygon["vertices"]) / factor
vertices = vertices.astype(np.int32)
cv2.fillPoly(mask_tumor, [vertices], (255))
mask_tumor = mask_tumor[:] > 127
return mask_tumor
def mask_show(npy_path,wsi_path,mask_save_path):
wsi_name = wsi_path.split('/')[-1]
mask = np.load(npy_path)
num = np.zeros((mask.shape[0], (mask.shape[1])), dtype=np.int32)
num[mask] = 1
img_mask = num * 255
cv2.imwrite(mask_save_path,img_mask)
def wsi_png(wsi_path,level,slide_save_path):
wsi_name = wsi_path.split('/')[-1]
slide = openslide.OpenSlide(wsi_path)
downsamples = slide.level_downsamples
[w, h] = slide.level_dimensions[0]
# size1=int(w*(downsamples[0]/downsamples[4]))
# size2=int(h*(downsamples[0]/downsamples[4]))
size_w = round(w * (downsamples[0] / downsamples[level]))
size_h = round(h * (downsamples[0] / downsamples[level]))
region = np.array(slide.read_region((0, 0), level, (size_w, size_h)))
im = Image.fromarray(region.astype('uint8')).convert('RGB')
#save_path = os.path.join(slide_save_path,wsi_name)
im.save(slide_save_path, quality=100)
def main():
level = 3
# json_route = '/media/wagnchogn/data_2tb/path_sam/dataset/camleyon17/label/json'
# wsi_route = '/media/wagnchogn/data_16t/camelyon/CAMELYON17/training_wsi/center_4'
# #npy_route = r'D:\code\pre_code\wsi_prepocessing\dataset\camelyon\tumor4'
# #mask_save_route = r'D:\code\pre_code\wsi_prepocessing\dataset\camelyon\tumor4_show'
# save_route = '/media/wagnchogn/data_2tb/path_sam/dataset/camleyon17_10x/center_4/tumor'
json_route = '/media/dell/data_4t/SAM_withmag/data/17/labels/json_1'
wsi_route = '/media/dell/data_4t/SAM_withmag/data/17/train'
#npy_route = r'D:\code\pre_code\wsi_prepocessing\dataset\camelyon\tumor4'
#mask_save_route = r'D:\code\pre_code\wsi_prepocessing\dataset\camelyon\tumor4_show'
save_route = '/media/dell/data_4t/SAM_withmag/data/17/train/level_3_v2'
mask_save_route = os.path.join(save_route,'mask')
crop_save_route = os.path.join(save_route, 'img')
if not os.path.exists(mask_save_route):
os.makedirs(mask_save_route)
if not os.path.exists(crop_save_route):
os.makedirs(crop_save_route)
label_files = os.listdir(json_route)
wsi_files = os.listdir(wsi_route)
for wsi_file in tqdm(wsi_files):
json_path = os.path.join(json_route, wsi_file.replace('.tif', '.json'))
wsi_path = os.path.join(wsi_route, wsi_file)
if wsi_file.replace('.tif','.json') in label_files:
print(wsi_file)
mask_tumor = run(wsi_path, level, json_path)
else:
continue
slide = openslide.OpenSlide(wsi_path)
level_downsample = slide.level_downsamples[level]
tumor_img = np.uint8(mask_tumor*255)
contours, _ = cv2.findContours(tumor_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
bounding_rects = [cv2.boundingRect(contour) for contour in contours] #(x,y,width,height)
for i in range(len(bounding_rects)):
###
# x_ori,y_ori,width_ori,height_ori = bounding_rects[i]
# '''
# x = x_ori - 50
# y = y_ori - 50
# width = width_ori + 100
# height = height_ori + 100
# '''
# width = (width_ori + 255) // 256 * 256
# height = (height_ori + 255) // 256 * 256
#
# # 计算增量
# delta_width = width - width_ori
# delta_height = height - height_ori
#
# # 调整 x 和 y 以保持中心不变
# x = x_ori - delta_width // 2
# y = y_ori - delta_height // 2
#
###
x_ori, y_ori, width_ori, height_ori = bounding_rects[i]
# 1. 计算高和宽能否被1024整除,求商的最大值
####?
factor_width = (width_ori // 1024) + (1 if width_ori % 1024 != 0 else 0)
factor_height = (height_ori // 1024) + (1 if height_ori % 1024 != 0 else 0)
# 2. 新的宽度和高度
factor_all = max(factor_width, factor_height)
width = factor_all * 1024
height = factor_all * 1024
# 3. 计算增量并调整x和y,以保持中心不变
delta_width = width - width_ori
delta_height = height - height_ori
x = x_ori - delta_width // 2
y = y_ori - delta_height // 2
###
#cv2.rectangle(tumor_img, (x, y), (x + width, y + height), (0, 255, 0), 2) #显示裁剪区域
mask = tumor_img[y:y + height, x:x + width]
x_level_0 = int(x * level_downsample)
y_level_0 = int(y * level_downsample)
sel_wsi = slide.read_region((x_level_0, y_level_0), level, (width, height))
sel_wsi = sel_wsi.convert('RGB')
mask_path = os.path.join(mask_save_route, wsi_file.split('.tif')[0] + '_' + str(x) + '_' + str(y) + '_' + str(width) + '_' + str(height) + '_' + str(level) + f'level_mask' + '.png')
sel_wsi_path = os.path.join(crop_save_route,
wsi_file.split('.tif')[0] + '_' + str(x) + '_' + str(y) + '_' + str(
width) + '_' + str(height) + '_' + str(level) + 'level' + '.png')
try:
cv2.imwrite(mask_path, mask)
sel_wsi.save(sel_wsi_path)
except Exception as e:
print(e)
print(f'{wsi_file} {x}x {y}y {width}width {height}height {level}level')
# continue
#print(bounding_rects)
if __name__ == "__main__":
main()
#### level=3 one bug
SAM_ca17_04_no_level0_tumor_mask_for_kaili
于 2024-03-26 17:47:26 首次发布