SAM_ca17_level0_tokaili

在这里插入代码片
import sys
import os
import argparse
import logging
import cv2
import numpy as np
import json

OPENSLIDE_PATH = r'D:\openslide\bin'
if hasattr(os, 'add_dll_directory'):
    # Python >= 3.8 on Windows
    with os.add_dll_directory(OPENSLIDE_PATH):
        import openslide
else:
    import openslide
import xml.etree.ElementTree as ET
from skimage.color import rgb2hsv
from skimage.filters import threshold_otsu

import time
from tqdm import tqdm
def check_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)

def get_xml_data(xml_path,mask_level):
    tree = ET.parse(xml_path)
    xml = tree.getroot()
    coors_list = []
    coors = []
    for areas in xml.iter('Coordinates'):
        for area in areas:
            coors.append([round(float(area.get('X'))/(2**mask_level)),
                            round(float(area.get('Y'))/(2**mask_level))])
        coors_list.append(coors)
        coors=[]
    return np.array(coors_list,dtype=object)

###
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





#centers = os.listdir(wsi_route)

# wsi_path = r'E:\path_sam_dataset\shuxin_pre\wsi_test\16\tumor_071.tif'
# xml_path = r'E:\path_sam_dataset\shuxin_pre\wsi_test\16\tumor_071.xml'
# save_route =r'E:\path_sam_dataset\shuxin_pre\wsi_test\16\tumor/patient_004_node_4.xml'

# xml_path = '/media/dell/data_4t/SAM_withmag/data/17/labels/lesion_annotations/patient_004_node_4.xml'
# wsi_path = '/media/dell/data_4t/SAM_withmag/data/17/train/patient_004_node_4.tif'
# json_path = '/media/dell/data_4t/SAM_withmag/data/17/labels/json_1/patient_004_node_4.json'
# save_route =r'/media/dell/data_4t/SAM_withmag/data/17/test_3'


###
json_in_route = '/media/dell/data_4t/SAM_withmag/data/17/labels/json_1'
wsi_in_route = '/media/dell/data_4t/SAM_withmag/data/17/train'
xml_in_route = '/media/dell/data_4t/SAM_withmag/data/17/labels/lesion_annotations'

###
save_route = '/media/dell/data_4t/SAM_withmag/data/17/level_0_v5'

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_in_route)

###
wsi_files = os.listdir(wsi_in_route)
for wsi_file in tqdm(wsi_files):
    ###
        json_path = os.path.join(json_in_route, wsi_file.replace('.tif', '.json'))
        wsi_path = os.path.join(wsi_in_route, wsi_file)
        xml_path = os.path.join(xml_in_route, wsi_file.replace('.tif', '.xml'))

    ###
        ###level ori = 0,to calculate the mask

        level_ori = 0

        slide = openslide.OpenSlide(wsi_path)
        slide_map = np.array(slide.get_thumbnail(slide.level_dimensions[4]))

        if os.path.exists(xml_path):
            coors_list = get_xml_data(xml_path, level_ori)
        else:
            coors_list = np.array([], dtype=np.int32)

        ###
        tumor_mask_ori = np.zeros(slide.level_dimensions[level_ori][::-1], dtype=np.int32)
        for coors in coors_list:
            cv2.drawContours(tumor_mask_ori, np.array([coors], dtype=np.int32), -1, 255, -1)

        ### dedao tumor_mask_ori

        ###zuobiao zhuanhuan level=3
        level_cal = 2
        if wsi_file.replace('.tif','.json') in label_files:
            print(wsi_file)
            mask_tumor = run(wsi_path, level_cal, json_path)
        else:
            continue

        try:
            slide = openslide.OpenSlide(wsi_path)

        except Exception as e:
            print(e)
            print(wsi_file)

        level_downsample_cal = slide.level_downsamples[level_cal]


        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]
            # 1. 计算level0高和宽能否被1024整除,求商的最大值
            ####?
            factor_width_level0 = (width_ori * level_downsample_cal // 1024) + (
                1 if width_ori * level_downsample_cal % 1024 != 0 else 0)
            factor_height_level0 = (height_ori * level_downsample_cal // 1024) + (
                1 if height_ori * level_downsample_cal % 1024 != 0 else 0)

            # 2. 新的宽度和高度
            factor_all_level0 = max(factor_width_level0, factor_height_level0)

            width_level0 = int(factor_all_level0 * 1024)
            height_level0 = int(factor_all_level0 * 1024)

            ###xinde zuobiao
            width_betwenn = int(width_level0 // level_downsample_cal)
            height_betwenn = int(height_level0 // level_downsample_cal)

            # 3. 计算增量并调整x和y,以保持中心不变
            delta_width = width_betwenn - width_ori
            delta_height = height_betwenn - height_ori
            x = x_ori - delta_width // 2
            y = y_ori - delta_height // 2


            x_level_0 = int(x * level_downsample_cal)
            y_level_0 = int(y * level_downsample_cal)

            # width_level_0 = int(width * level_downsample)
            # height_level_0 = int(height * level_downsample)

            sel_wsi = slide.read_region((x_level_0, y_level_0), 0, (width_level0, height_level0))
            mask = tumor_mask_ori[y_level_0:y_level_0 + height_level0, x_level_0:x_level_0 + width_level0]

            if mask.dtype != np.uint8:
                mask = mask.astype(np.uint8)

            sel_wsi = sel_wsi.convert('RGB')


            # cv2.imwrite(f'/media/dell/data_4t/SAM_withmag/data/17/test_3/{i}_mask.png', mask)
            # sel_wsi.save(f'/media/dell/data_4t/SAM_withmag/data/17/test_3/{i}.png')


            mask_save_path = os.path.join(mask_save_route,
                                     wsi_file.split('.tif')[0] + '_' + str(x_level_0) + '_' + str(y_level_0) + '_' + str(width_level0) + '_' + str(
                                         height_level0) + '_' + str(level_ori) + f'level_mask' + '.png')
            sel_wsi_save_path = os.path.join(crop_save_route,
                                        wsi_file.split('.tif')[0] + '_' + str(x_level_0) + '_' + str(y_level_0) + '_' + str(
                                            width_level0) + '_' + str(height_level0) + '_' + str(level_ori) + 'level' + '.png')

            try:
                cv2.imwrite(mask_save_path, mask)
                sel_wsi.save(sel_wsi_save_path)

            except Exception as e:
                print(e)
                print(f'{wsi_file} {x_level_0}x {y_level_0}y {width_level0}width {height_level0}height {level_ori}level')
            continue














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值