예제 #1
0
def test_loading_invalid_reference_rt_struct(series_path):
    # This RTStruct references images not found within the series path
    invalid_reference_rt_struct_path = os.path.join(
        series_path, "invalid_reference_rt.dcm")
    assert os.path.exists(invalid_reference_rt_struct_path)
    with pytest.raises(Exception):
        RTStructBuilder.create_from(series_path,
                                    invalid_reference_rt_struct_path)
예제 #2
0
def full_process():
    SRC_DATA = opt.source
    print('Preprocessing starts........ ', end="")
    patients = [
        os.path.join(SRC_DATA, name) for name in os.listdir(SRC_DATA)
        if os.path.isdir(os.path.join(SRC_DATA, name))
    ]
    patient = patients[1]
    name_idx = len(SRC_DATA)
    image = read_images_masks(patient)

    #Predicting and cutting bounding box
    for slice in range(image.shape[0]):
        plt.imsave(bbox_saving_path + "/hi" + str(slice) + ".jpg",
                   image[slice],
                   cmap="gray")
    with HiddenPrints():
        result = detect("/home/seenia/allen/Final/processing/sampleP",
                        "/home/seenia/allen/Final/demo/best.pt")
    minxP, minyP, maxxP, maxyP = 1000, 1000, 0, 0
    for i in result:
        if (len(i) == 4):
            minxP, minyP, maxxP, maxyP = min(minxP, int(i[0])), min(
                minyP, int(i[1])), max(maxxP,
                                       int(i[2])), max(maxyP, int(i[3]))

    #Saving npy
    image = image[:, minyP - 5:maxyP + 5, minxP - 5:maxxP + 5]
    saving_name = processed_path + patient[name_idx:] + "image.npy"
    np.save(saving_name, image)
    print('Preprocessing Finished')

    #Prediction
    print('Prediction starts........ ', end="")
    predict_mask(saving_name, opt.weights)
    print('Prediction Finished')

    #Saving results
    print('Saving results starts........ ', end="")
    rtstruct = RTStructBuilder.create_new(dicom_series_path=opt.source)
    names = ['Lung_L', 'Lung_R', 'Heart', 'SpinalCord', 'Esophagus']
    colour = [[197, 165, 145], [197, 165, 145], [127, 150, 88],
              [253, 135, 192], [85, 188, 255]]
    with HiddenPrints():
        for organ, clr in zip(names, colour):
            result = np.load(result_path + organ + ".npy")
            result = result > 0
            result = result.transpose(1, 2, 0)
            #if(arr.count(organ[0].lower())>0):
            rtstruct.add_roi(mask=result, color=clr, name=organ)
    print('Saving results Finished')
    rtstruct.save(opt.dest + 'final')
    #removing all unwanted files
    stream1 = os.popen(
        'rm -r /home/seenia/allen/Final/processing/sampleP/*.jpg')
    stream2 = os.popen(
        'rm -r /home/seenia/allen/Final/processing/dataProcessed/*.npy')
    stream3 = os.popen(
        'rm -r /home/seenia/allen/Final/processing/resultsP/*.npy')
예제 #3
0
def convert_nifti(dcm_path,
                  mask_input,
                  output_file,
                  color_map=cm.get_cmap("rainbow")):
    """Convert a set of masks to a DICOM RTStruct object.

    This function now utilises the rt-utils package: https://github.com/qurit/rt-utils
    We keep this function in here for compatibility

    Args:
        dcm_path (str|pathlib.Path): Path to the reference DICOM series
        mask_input (dict|list): A dictionary containing the name as key and image as value. Or a
                                list of string with comma separated name and mask paths (name,path)
        output_file (str|pathlib.Path): The path to the file to write the RTStruct
         color_map (matplotlib.colors.Colormap, optional): Colormap to use for output. Defaults to
                                                           cm.get_cmap("rainbow").
    """

    logger.info("Will convert the following Nifti masks to RTStruct:")

    masks = {}  # Dict stores key value pairs for masks
    if isinstance(mask_input, dict):
        # Dict was already passed in
        masks = mask_input
    else:
        # Otherwise convert list of comma separated masks
        for mask in mask_input:
            mask_parts = mask.split(",")
            masks[mask_parts[0]] = mask_parts[1]

    if not isinstance(dcm_path, Path):
        dcm_path = Path(dcm_path)

    dcm_series_path = None
    if dcm_path.is_file():
        dcm_series_path = dcm_path.parent
    else:
        dcm_series_path = dcm_path

    rtstruct = RTStructBuilder.create_new(
        dicom_series_path=str(dcm_series_path))

    for mask_name in masks:

        # Use a hash of the name to get the color from the supplied color map
        color = color_map(hash(mask_name) % 256)
        color = color[:3]
        color = [int(c * 255) for c in color]

        mask = masks[mask_name]
        if not isinstance(mask, sitk.Image):
            mask = sitk.ReadImage(str(mask))

        bool_arr = sitk.GetArrayFromImage(mask) != 0
        bool_arr = np.transpose(bool_arr, (1, 2, 0))
        rtstruct.add_roi(mask=bool_arr, color=color, name=mask_name)

    rtstruct.save(str(output_file))
예제 #4
0
def test_non_existant_referenced_study_sequence(series_path):
    non_existent_reference_study_rt_struct_path = os.path.join(
        series_path, "non_existent_reference_rt.dcm")
    assert os.path.exists(non_existent_reference_study_rt_struct_path)
    rtstruct = RTStructBuilder.create_from(
        series_path, non_existent_reference_study_rt_struct_path)

    # Test that the attribute does not exist but RTStruct instantiation was still successful
    assert not hasattr(rtstruct.ds.ReferencedFrameOfReferenceSequence[0],
                       "RTReferencedStudySequence")
예제 #5
0
def test_loading_valid_rt_struct(series_path):
    valid_rt_struct_path = os.path.join(series_path, "rt.dcm")
    assert os.path.exists(valid_rt_struct_path)
    rtstruct = RTStructBuilder.create_from(series_path, valid_rt_struct_path)

    # Tests existing values predefined in the file are found
    assert hasattr(rtstruct.ds, "ROIContourSequence")
    assert hasattr(rtstruct.ds, "StructureSetROISequence")
    assert hasattr(rtstruct.ds, "RTROIObservationsSequence")
    assert len(rtstruct.ds.ROIContourSequence) == 1
    assert len(rtstruct.ds.StructureSetROISequence) == 1
    assert len(rtstruct.ds.RTROIObservationsSequence) == 1

    # Test adding a new ROI
    mask = get_empty_mask(rtstruct)
    mask[50:100, 50:100, 0] = 1
    rtstruct.add_roi(mask)

    assert len(rtstruct.ds.ROIContourSequence) == 2  # 1 should be added
    assert len(rtstruct.ds.StructureSetROISequence) == 2  # 1 should be added
    assert len(rtstruct.ds.RTROIObservationsSequence) == 2  # 1 should be added
    new_roi = rtstruct.ds.StructureSetROISequence[-1]
    assert new_roi.ROIName == "ROI-2"
예제 #6
0
def new_rtstruct() -> RTStruct:
    path = get_and_test_series_path()
    rtstruct = RTStructBuilder.create_new(path)
    return rtstruct
예제 #7
0
def test_loading_invalid_rt_struct(series_path):
    invalid_rt_struct_path = os.path.join(series_path, "ct_1.dcm")
    assert os.path.exists(invalid_rt_struct_path)
    with pytest.raises(Exception):
        RTStructBuilder.create_from(series_path, invalid_rt_struct_path)
예제 #8
0
def test_create_from_empty_series_dir():
    empty_dir_path = os.path.join(os.path.dirname(__file__), "empty")
    assert os.path.exists(empty_dir_path)
    with pytest.raises(Exception):
        RTStructBuilder.create_new(empty_dir_path)
예제 #9
0
def new_rtstruct() -> RTStruct:
    rtstruct = RTStructBuilder.create_new(get_series_path())
    return rtstruct
예제 #10
0
        type=str,
        default=
        '/home/seenia/allen/Final/demo/Unet_3D_DiceLoss_epochs_40_trainsize_45_loss_dice_trainloss_4.214956012864312',
        help='path to model weights')
    parser.add_argument('--source',
                        type=str,
                        default='/home/seenia/allen/Final/demo/data/',
                        help='path to dicom series')
    parser.add_argument('--dest',
                        type=str,
                        default='/home/seenia/allen/Final/',
                        help='path to destination')

    opt = parser.parse_args()
    flag = 0

    if (path.exists(opt.weights) & path.exists(opt.source)
            & path.exists(opt.dest)):
        try:
            demo = RTStructBuilder.create_new(dicom_series_path=opt.source)
            flag = 1
        except:
            print("No DICOM series found in input path")
    else:
        print("Weights File exists:" + str(path.exists(opt.weights)))
        print("Source File exists:" + str(path.exists(opt.source)))
        print("Destination File exists:" + str(path.exists(opt.dest)))

    if (flag == 1):
        full_process()
예제 #11
0
파일: conftest.py 프로젝트: qurit/rt-utils
def get_rtstruct(dirname) -> RTStruct:
    path = get_and_test_series_path(dirname)
    rtstruct = RTStructBuilder.create_new(path)
    return rtstruct