def main(): parser = argparse.ArgumentParser() parser.add_argument( 'input', metavar='input', type=path, help='Path to the input image, can be a folder for dicoms') parser.add_argument('output', metavar='output', type=str, help='Filepath for output lungmask') parser.add_argument('--modeltype', help='Default: unet', type=str, choices=['unet', 'resunet'], default='unet') parser.add_argument('--modelname', help="spcifies the trained model, Default: R231", type=str, choices=['R231', 'LTRCLobes', 'R231CovidWeb'], default='R231') parser.add_argument( '--cpu', help= "Force using the CPU even when a GPU is available, will override batchsize to 1", action='store_true') parser.add_argument( '--nopostprocess', help= "Deactivates postprocessing (removal of unconnected components and hole filling", action='store_true') parser.add_argument( '--batchsize', type=int, help= "Number of slices processed simultaneously. Lower number requires less memory but may be slower.", default=20) argsin = sys.argv[1:] args = parser.parse_args(argsin) batchsize = args.batchsize if args.cpu: batchsize = 1 logging.info(f'Load model') model = mask.get_model(args.modeltype, args.modelname) input_image = utils.get_input_image(args.input) logging.info(f'Infer lungmask') result = mask.apply(input_image, model, force_cpu=args.cpu, batch_size=batchsize, volume_postprocessing=not (args.nopostprocess)) result_out = sitk.GetImageFromArray(result) result_out.CopyInformation(input_image) logging.info(f'Save result to: {args.output}') sys.exit(sitk.WriteImage(result_out, args.output))
def segmenter(): from lungmask import lungmask, utils import SimpleITK as sitk from pathlib import Path import os import logging import numpy as np # import pdb images_path = Path("./Data/COVID") segmentation_path = Path("./Data/Segmentations") dict_path = Path("./Data/Dictionaries") images = [ f for f in os.listdir(images_path) if os.path.isdir(os.path.join(images_path, f)) ] # pdb.set_trace() logging.info(f'Load model') model = lungmask.get_model('unet', 'R231') for input in images: input_image = utils.get_input_image(os.path.join(images_path, input)) logging.info(f'Infer lungmask') result = lungmask.apply(input_image, model, batch_size=1, volume_postprocessing=False) result_dict = np.zeros((np.shape(result)[0], 2)) for i in range(np.shape(result)[0]): slice = result[i, :, :] area = np.size(np.where(slice > 0)) result_dict[i, :] = [i + 1, area] result_dict = np.flip(result_dict[result_dict[:, 1].argsort()], axis=0) with open(os.path.join(dict_path, '{}.csv'.format(input)), "w") as outfile: np.savetxt(outfile, result_dict, delimiter=",") result_out = sitk.GetImageFromArray(result) result_out.CopyInformation(input_image) logging.info(f' %s results saved', input) sitk.WriteImage( result_out, os.path.join(segmentation_path, '{}.dcm'.format(input)))
def __host_segment(self, source_dir, model_name): from lungmask import lungmask from lungmask import utils import SimpleITK as sitk model = lungmask.get_model('unet', model_name) input_image = utils.get_input_image(source_dir) input_nda = sitk.GetArrayFromImage(input_image) print(input_nda.shape) segmentation = lungmask.apply(input_image, model, force_cpu=False, batch_size=20, volume_postprocessing=False) return segmentation, input_nda
def run_lungmask_absolute(abs_source_dir, model_name='R231CovidWeb'): data_share = os.environ["DATA_SHARE_PATH"] model = lungmask.get_model('unet', model_name) if not os.path.exists(abs_source_dir): log_debug("Input image source dir doesn't exist", abs_source_dir) return {}, False input_image = utils.get_input_image(abs_source_dir) segmentation = lungmask.apply(input_image, model, force_cpu=False, batch_size=20, volume_postprocessing=False) log_debug("Got result") log_debug(segmentation) result_dict = {} lungmask_dir = "lungmask_output" os.makedirs(os.path.join(data_share, lungmask_dir), exist_ok=True) unique_id = cutils.get_unique_id() hostname = os.environ["LUNGMASK_HOSTNAME"] rel_seg_save_path = os.path.join( lungmask_dir, f"{hostname}-segmentation-{unique_id}.nii.gz") abs_seg_save_path = os.path.join(data_share, rel_seg_save_path) segmentation_nifti = sitk.GetImageFromArray(segmentation) segmentation_nifti.SetSpacing(input_image.GetSpacing()) sitk.WriteImage(segmentation_nifti, abs_seg_save_path) result_dict["segmentation"] = rel_seg_save_path return result_dict, True
def main(): parser = argparse.ArgumentParser() parser.add_argument('--in-folder', type=str, default=in_folder) parser.add_argument('--out-folder', type=str, default=out_mask_folder) parser.add_argument('--file-list-txt', type=str, default=file_list_txt) parser.add_argument('--failed-list-txt', type=str) parser.add_argument('--modeltype', help='Default: unet', type=str, choices=['unet'], default='unet') parser.add_argument( '--modelname', help="spcifies the trained model, Default: R231", type=str, choices=['R231', 'LTRCLobes', 'LTRCLobes_R231', 'R231CovidWeb'], default='R231') parser.add_argument( '--cpu', help= "Force using the CPU even when a GPU is available, will override batchsize to 1", action='store_true') parser.add_argument( '--nopostprocess', help= "Deactivates postprocessing (removal of unconnected components and hole filling", action='store_true') parser.add_argument( '--noHU', help= "For processing of images that are not encoded in hounsfield units (HU). E.g. png or jpg images from the web. Be aware, results may be substantially worse on these images", action='store_true') parser.add_argument( '--batchsize', type=int, help= "Number of slices processed simultaneously. Lower number requires less memory but may be slower.", default=20) argsin = sys.argv[1:] args = parser.parse_args(argsin) batchsize = args.batchsize if args.cpu: batchsize = 1 logging.info(f'Load model') file_list = read_file_contents_list(args.file_list_txt) failed_case_list = [] for file_idx in range(len(file_list)): file_name = file_list[file_idx] logging.info(f'Process {file_name}, {file_idx} / {len(file_list)}') try: in_nii = os.path.join(args.in_folder, file_name) out_nii_mask = os.path.join(args.out_folder, file_name) input_image = utils.get_input_image(in_nii) logging.info(f'Infer lungmask') if args.modelname == 'LTRCLobes_R231': result = mask.apply_fused( input_image, force_cpu=args.cpu, batch_size=batchsize, volume_postprocessing=not (args.nopostprocess), noHU=args.noHU) else: model = mask.get_model(args.modeltype, args.modelname) result = mask.apply( input_image, model, force_cpu=args.cpu, batch_size=batchsize, volume_postprocessing=not (args.nopostprocess), noHU=args.noHU) result_out = sitk.GetImageFromArray(result) result_out.CopyInformation(input_image) logging.info(f'Save result to: {out_nii_mask}') # sys.exit(sitk.WriteImage(result_out, out_nii_mask)) sitk.WriteImage(result_out, out_nii_mask) except: print(f'Something wrong with {file_name}') failed_case_list.append(file_name) save_file_contents_list(args.failed_list_txt, failed_case_list)
if st.button('download and analyse'): latest_iteration = st.empty() bar = st.progress(0) dir_ = os.path.join('/tmp/', subject_name) scan.download_dir(dir_, verbose=True) download_dir = '' for path in Path(dir_).rglob('*.dcm'): download_dir, file = os.path.split(str(path.resolve())) break bar.progress(100) st.text('Analysis progress...') bar2 = st.progress(0) model = lungmask.get_model('unet', 'R231CovidWeb') input_image = utils.get_input_image(download_dir) input_nda = sitk.GetArrayFromImage(input_image) print(input_nda.shape) zd, yd, xd = input_nda.shape spx, spy, spz = input_image.GetSpacing() result = lungmask.apply(input_image, model, bar2, force_cpu=False, batch_size=20, volume_postprocessing=False) result_out = sitk.GetImageFromArray(result) result_out.CopyInformation(input_image) sitk.WriteImage(result_out,