Example #1
0
def coscia_apply(modelObj: DynamicDLModel, data: dict):
    from dl.common.padorcut import padorcut
    from dl.common.preprocess_train import split_mirror
    from scipy.ndimage import zoom
    try:
        np
    except:
        import numpy as np

    from dl.labels.thigh import long_labels as LABELS_DICT

    MODEL_RESOLUTION = np.array([1.037037, 1.037037])
    MODEL_SIZE = (432, 432)
    netc = modelObj.model
    resolution = np.array(data['resolution'])
    zoomFactor = resolution / MODEL_RESOLUTION
    img = data['image']
    originalShape = img.shape
    img = zoom(img, zoomFactor)  # resample the image to the model resolution
    img = padorcut(img, MODEL_SIZE)
    segmentation = netc.predict(
        np.expand_dims(np.stack([img, np.zeros(MODEL_SIZE)], axis=-1), axis=0))
    labelsMask = np.argmax(np.squeeze(segmentation[0, :, :, :13]), axis=2)
    if (data['split_laterality']):
        a1, a2, a3, a4, b1, b2 = split_mirror(img)
        labelsMask_left = np.zeros(MODEL_SIZE, dtype='float32')
        labelsMask_right = np.zeros(MODEL_SIZE, dtype='float32')
        labelsMask_left[int(b1):int(b2),
                        int(a1):int(a2)] = labelsMask[int(b1):int(b2),
                                                      int(a1):int(a2)]
        labelsMask_right[int(b1):int(b2),
                         int(a3):int(a4)] = labelsMask[int(b1):int(b2),
                                                       int(a3):int(a4)]
        labelsMask_left = zoom(labelsMask_left, 1 / zoomFactor, order=0)
        labelsMask_left = padorcut(labelsMask_left,
                                   originalShape).astype(np.int8)
        labelsMask_right = zoom(labelsMask_right, 1 / zoomFactor, order=0)
        labelsMask_right = padorcut(labelsMask_right,
                                    originalShape).astype(np.int8)
        outputLabels = {}
        for labelValue, labelName in LABELS_DICT.items():
            outputLabels[labelName +
                         '_L'] = (labelsMask_left == labelValue).astype(
                             np.int8)
            outputLabels[labelName +
                         '_R'] = (labelsMask_right == labelValue).astype(
                             np.int8)

        return outputLabels
    else:
        labelsMask = zoom(labelsMask, 1 / zoomFactor, order=0)
        labelsMask = padorcut(labelsMask, originalShape).astype(np.int8)
        outputLabels = {}
        for labelValue, labelName in LABELS_DICT.items():
            outputLabels[labelName] = (labelsMask == labelValue).astype(
                np.int8)

        return outputLabels
def leg_incremental(modelObj: DynamicDLModel, trainingdata: dict,
                    trainingoutputs):
    from unused.create_train import create_train_leg
    import dl.common.preprocess_train as pretrain
    import os
    import math
    from keras.callbacks import ModelCheckpoint
    from keras import optimizers
    try:
        np
    except:
        import numpy as np
    create_train_leg(trainingdata, trainingoutputs)
    path = './train/leg'
    pretrain.split_mirror(path, card, 7)
    batch_size = 5
    card = len(os.listdir(path))
    steps = int(math.floor(float(card / batch_size)))
    pretrain.input_creation(path, card, 270, 64, 7)
    netc = modelObj.model
    checkpoint_path = "./Weights_incremental/weights_leg_split-{epoch:02d}-{loss:.2f}.hdf5"
    check = ModelCheckpoint(filepath=checkpoint_path,
                            monitor='loss',
                            verbose=0,
                            save_best_only=False,
                            save_weights_only=True,
                            mode='auto',
                            period=5)
    adamlr = optimizers.Adam(learning_rate=0.001,
                             beta_1=0.9,
                             beta_2=0.999,
                             epsilon=1e-08,
                             amsgrad=True)
    training_generator = DataGenerator(path=path,
                                       list_X=list(
                                           range(1, steps * batch_size + 1)),
                                       batch_size=batch_size)
    netc.compile(loss=weighted_loss, optimizer=adamlr)
    history = netc.fit_generator(generator=training_generator,
                                 steps_per_epoch=steps,
                                 epochs=5,
                                 callbacks=[check],
                                 verbose=1)
def coscia_apply(modelObj: DynamicDLModel, data: dict):
    from dl.common.padorcut import padorcut
    import dl.common.biascorrection as biascorrection
    import dl.common.preprocess_train as pretrain
    from dl.common.preprocess_train import split_mirror
    from scipy.ndimage import zoom
    try:
        np
    except:
        import numpy as np

    from dl.labels.thigh import long_labels as LABELS_DICT

    MODEL_RESOLUTION = np.array([1.037037, 1.037037])
    MODEL_SIZE = (432, 432)
    MODEL_SIZE_SPLIT = (250, 250)
    netc = modelObj.model
    resolution = np.array(data['resolution'])
    zoomFactor = resolution / MODEL_RESOLUTION
    img = data['image']
    originalShape = img.shape
    img = zoom(img, zoomFactor)  # resample the image to the model resolution
    img = padorcut(img, MODEL_SIZE)
    imgbc = biascorrection.biascorrection_image(img)
    a1, a2, a3, a4, b1, b2 = split_mirror(imgbc)
    left = imgbc[int(b1):int(b2), int(a1):int(a2)]
    left = padorcut(left, MODEL_SIZE_SPLIT)
    right = imgbc[int(b1):int(b2), int(a3):int(a4)]
    right = right[::1, ::-1]
    right = padorcut(right, MODEL_SIZE_SPLIT)
    segmentationleft = netc.predict(
        np.expand_dims(np.stack([left, np.zeros(MODEL_SIZE_SPLIT)], axis=-1),
                       axis=0))
    labelleft = np.argmax(np.squeeze(segmentationleft[0, :, :, :13]), axis=2)
    segmentationright = netc.predict(
        np.expand_dims(np.stack([right, np.zeros(MODEL_SIZE_SPLIT)], axis=-1),
                       axis=0))
    labelright = np.argmax(np.squeeze(segmentationright[0, :, :, :13]), axis=2)
    labelright = labelright[::1, ::-1]
    labelsMask_left = np.zeros(MODEL_SIZE, dtype='float32')
    labelsMask_right = np.zeros(MODEL_SIZE, dtype='float32')
    labelsMask_left[int(b1):int(b2),
                    int(a1):int(a2)] = padorcut(labelleft, [b2 - b1, a2 - a1])
    labelsMask_right[int(b1):int(b2),
                     int(a3):int(a4)] = padorcut(labelright,
                                                 [b2 - b1, a4 - a3])
    labelsMask_left = zoom(labelsMask_left, 1 / zoomFactor, order=0)
    labelsMask_left = padorcut(labelsMask_left, originalShape).astype(np.int8)
    labelsMask_right = zoom(labelsMask_right, 1 / zoomFactor, order=0)
    labelsMask_right = padorcut(labelsMask_right,
                                originalShape).astype(np.int8)
    outputLabels = {}

    if data['split_laterality']:
        for labelValue, labelName in LABELS_DICT.items():
            outputLabels[labelName + '_R'] = (
                labelsMask_left == labelValue).astype(
                    np.int8)  # left in the image is right in the anatomy
            outputLabels[labelName +
                         '_L'] = (labelsMask_right == labelValue).astype(
                             np.int8)
        return outputLabels
    else:
        for labelValue, labelName in LABELS_DICT.items():
            outputLabels[labelName] = np.logical_or(
                labelsMask_left == labelValue,
                labelsMask_right == labelValue).astype(np.int8)
        return outputLabels
Example #4
0
def gamba_apply(modelObj: DynamicDLModel, data: dict):
    from dl.common.padorcut import padorcut
    import dl.common.biascorrection as biascorrection
    import dl.common.preprocess_train as pretrain
    from dl.common.preprocess_train import split_mirror
    from scipy.ndimage import zoom
    try:
        np
    except:
        import numpy as np

    from dl.labels.leg import long_labels as LABELS_DICT
    
    MODEL_RESOLUTION = np.array([1.037037, 1.037037])
    MODEL_SIZE = (432, 432)
    MODEL_SIZE_SPLIT = (216, 216)

    classification = data.get('classification', '')

    single_side = False
    swap = False

    # Note: this is anatomical right, which means it's image left! It's the image right that is swapped
    if classification.lower().strip().endswith('right'):
        single_side = True
        swap = False
    elif classification.lower().strip().endswith('left'):
        single_side = True
        swap = True

    # otherwise: double sided

    netc = modelObj.model
    resolution = np.array(data['resolution'])
    zoomFactor = resolution / MODEL_RESOLUTION
    img = data['image']
    originalShape = img.shape
    img = zoom(img, zoomFactor)  # resample the image to the model resolution

    if single_side:
        img = padorcut(img, MODEL_SIZE_SPLIT)
        if swap:
            img = img[::1, ::-1]

        segmentation = netc.predict(np.expand_dims(np.stack([img, np.zeros(MODEL_SIZE_SPLIT)], axis=-1), axis=0))
        label = np.argmax(np.squeeze(segmentation[0, :, :, :13]), axis=2)
        if swap:
            label = label[::1, ::-1]

        labelsMask = zoom(label, 1 / zoomFactor, order=0)
        labelsMask = padorcut(labelsMask, originalShape).astype(np.int8)

        outputLabels = {}

        suffix = ''
        if data['split_laterality']:
            suffix = '_L' if swap else '_R'
        for labelValue, labelName in LABELS_DICT.items():
            outputLabels[labelName + suffix] = (labelsMask == labelValue).astype(
                np.int8)  # left in the image is right in the anatomy
        return outputLabels

    # two sides
    img = padorcut(img, MODEL_SIZE)
    imgbc=biascorrection.biascorrection_image(img)
    a1,a2,a3,a4,b1,b2=split_mirror(imgbc)
    left=imgbc[int(b1):int(b2),int(a1):int(a2)]
    left=padorcut(left, MODEL_SIZE_SPLIT)
    right=imgbc[int(b1):int(b2),int(a3):int(a4)]
    right=right[::1,::-1]
    right=padorcut(right, MODEL_SIZE_SPLIT)
    segmentationleft=netc.predict(np.expand_dims(np.stack([left,np.zeros(MODEL_SIZE_SPLIT)],axis=-1),axis=0))
    labelleft=np.argmax(np.squeeze(segmentationleft[0,:,:,:7]), axis=2)
    segmentationright=netc.predict(np.expand_dims(np.stack([right,np.zeros(MODEL_SIZE_SPLIT)],axis=-1),axis=0))
    labelright=np.argmax(np.squeeze(segmentationright[0,:,:,:7]), axis=2)
    labelright=labelright[::1,::-1]
    labelsMask_left=np.zeros(MODEL_SIZE,dtype='float32')
    labelsMask_right=np.zeros(MODEL_SIZE,dtype='float32')
    labelsMask_left[int(b1):int(b2),int(a1):int(a2)]=padorcut(labelleft, [b2-b1, a2-a1])
    labelsMask_right[int(b1):int(b2),int(a3):int(a4)]=padorcut(labelright, [b2-b1, a4-a3])
    labelsMask_left = zoom(labelsMask_left, 1/zoomFactor, order=0)
    labelsMask_left = padorcut(labelsMask_left, originalShape).astype(np.int8)
    labelsMask_right = zoom(labelsMask_right, 1/zoomFactor, order=0)
    labelsMask_right = padorcut(labelsMask_right, originalShape).astype(np.int8)
    outputLabels = {}

    if data['split_laterality']:
        for labelValue, labelName in LABELS_DICT.items():
            outputLabels[labelName+'_R'] = (labelsMask_left == labelValue).astype(np.int8)
            outputLabels[labelName+'_L'] = (labelsMask_right == labelValue).astype(np.int8)
        return outputLabels
    else:
        for labelValue, labelName in LABELS_DICT.items():
            outputLabels[labelName] = np.logical_or(labelsMask_left == labelValue, labelsMask_right == labelValue).astype(np.int8)
        return outputLabels