Beispiel #1
0
def convert_nii(y_pred,img):
	
	y_gt_nii=  nib.load(img)
	np_img = y_gt_nii.get_data()
	print(y_pred.shape)

	# print(np_img.shape)
	# y_pred = np.argmax(y_pred, axis = 0).astype(np.uint8)
	y_pred = dv.crop_or_pad(y_pred, y_gt_nii.get_data().shape)
	img_pred = nib.Nifti1Image(y_pred, y_gt_nii.affine,header=y_gt_nii.header)
	
	out = os.path.dirname(img)
	out = os.path.dirname(img[:-1])
	# print(out)
	out = os.path.join(os.path.join(os.path.dirname(out),"seg-pred-2"),os.path.basename(img))
	print(out)
	os.makedirs(os.path.dirname(out), exist_ok = True)
	# out = ("{0}.nii.gz".format(j))
	nib.save(img_pred, out)
	n = np.product(y_gt_nii.get_data().shape)
	for c in range(0, 12):
		print("Predicted = ",np.sum(y_pred==c)/n)
		print(c,np.sum(y_gt_nii.get_data()==c)/n)
		iou = dv.jaccard_index(y_gt_nii.get_data(), y_pred, c)
		print(iou)
Beispiel #2
0
def out_adapt_raw(x, relabel_LVOT, target=adapt_size, n=cg.num_classes):
    x = nb.load(x).get_data()
    if relabel_LVOT == True:
        x = relabel(x)
    elif relabel_LVOT == False:
        a = 1
    else:
        raise ValueError('have not defined relabel_LVOT')
    x[x >= n] = 0
    x = dv.crop_or_pad(x, target)
    return x
Beispiel #3
0
def in_adapt(x, target=adapt_size):
    x = nb.load(x).get_data()
    x = dv.crop_or_pad(x, target)
    x = np.expand_dims(x, axis=-1)
    return x
Beispiel #4
0
                    relabel_LVOT=cg.relabel_LVOT,
                    input_adapter=ut.in_adapt,
                    output_adapter=ut.out_adapt,
                    shape=cg.dim,
                    input_channels=1,
                    output_channels=cg.num_classes,
                ),
                verbose=1,
                steps=1,
            )

            # save u_net segmentation
            if task_list[task_num] == 's':
                u_gt_nii = nb.load(img)
                u_pred = np.argmax(u_pred[0], axis=-1).astype(np.uint8)
                u_pred = dv.crop_or_pad(u_pred, u_gt_nii.get_data().shape)
                u_pred[u_pred == 3] = 4
                u_pred = nb.Nifti1Image(u_pred, u_gt_nii.affine)
                save_path = os.path.join(
                    save_folder, patient_class, patient_id, 'seg-pred-1.5',
                    'pred_' + task_list[task_num] + '_' +
                    os.path.basename(img))
                #ff.make_folder([os.path.join(save_folder,patient_class),os.path.join(save_folder,patient_class,patient_id),os.path.join(save_folder,patient_class,patient_id,'seg-pred-1.5')])
                #nb.save(u_pred, save_path)

        # # save vectors
        #   if task_list[task_num] != 's':
        #     x_n = ff.normalize(x_pred)
        #     y_n = ff.normalize(y_pred)
        #     matrix = np.concatenate((t_pred.reshape(1,3),x_n.reshape(1,3),y_n.reshape(1,3)))
        #     save_path = os.path.join(p,'vector-pred','pred_'+task_list[task_num])
Beispiel #5
0
def validate(batch):

    #===========================================
    dv.section_print('Calculating Image Lists...')

    partition_file_name = 'one_time_frame_4classes'

    imgs_list_tst = [
        np.load(os.path.join(cg.partition_dir, partition_file_name,
                             'img_list_' + str(p) + '.npy'),
                allow_pickle=True) for p in range(cg.num_partitions)
    ]
    segs_list_tst = [
        np.load(os.path.join(cg.partition_dir, partition_file_name,
                             'seg_list_' + str(p) + '.npy'),
                allow_pickle=True) for p in range(cg.num_partitions)
    ]

    if batch == None:
        raise ValueError('No batch was provided: wrong!')
        # print('pick all batches')
        # batch = 'all'
        # imgs_list_tst = np.concatenate(imgs_list_tst)
        # segs_list_tst = np.concatenate(segs_list_tst)
    else:
        imgs_list_tst = imgs_list_tst[batch]
        segs_list_tst = segs_list_tst[batch]

    print(imgs_list_tst.shape)
    #===========================================
    dv.section_print('Loading Saved Weights...')

    # Build the U-NET
    shape = cg.dim + (1, )
    model_inputs = [Input(shape)]
    model_outputs = []
    _, _, unet_output = dvpy.tf_2d.get_unet(
        cg.dim,
        cg.num_classes,
        cg.conv_depth,
        layer_name='unet',
        dimension=cg.unetdim,
        unet_depth=cg.unet_depth,
    )(model_inputs[0])
    model_outputs += [unet_output]
    model = Model(inputs=model_inputs, outputs=model_outputs)

    # Load weights
    model.load_weights(model_files[0], by_name=True)

    #===========================================
    dv.section_print('Calculating Predictions...')
    # build data generator
    valgen = dv.tf_2d.ImageDataGenerator(
        cg.unetdim,
        input_layer_names=['input_1'],
        output_layer_names=['unet'],
    )

    # predict
    for img, seg in zip(imgs_list_tst, segs_list_tst):
        patient_id = os.path.basename(os.path.dirname(os.path.dirname(img)))
        patient_class = os.path.basename(
            os.path.dirname(os.path.dirname(os.path.dirname(img))))
        print(img)
        print(patient_class, patient_id, '\n')

        u_pred = model.predict_generator(
            valgen.flow(
                np.asarray([img]),
                np.asarray([seg]),
                slice_num=cg.slice_num,
                batch_size=cg.slice_num,
                relabel_LVOT=cg.relabel_LVOT,
                shuffle=False,
                input_adapter=ut.in_adapt,
                output_adapter=ut.out_adapt,
                shape=cg.dim,
                input_channels=1,
                output_channels=cg.num_classes,
                adapted_already=cg.adapted_already,
            ),
            verbose=1,
            steps=1,
        )

        # save u_net segmentation
        time = ff.find_timeframe(seg, 1, '_')
        u_gt_nii = nb.load(
            os.path.join(cg.seg_data_dir, patient_class, patient_id,
                         'seg-pred-1.5-upsample-retouch',
                         'pred_s_' + str(time) + '.nii.gz')
        )  # load the manual segmentation file for affine matrix
        u_pred = np.rollaxis(u_pred, 0, 3)
        u_pred = np.argmax(u_pred, axis=-1).astype(np.uint8)
        u_pred = dv.crop_or_pad(u_pred, u_gt_nii.get_fdata().shape)
        u_pred[u_pred == 3] = 4  # use for LVOT only
        u_pred = nb.Nifti1Image(u_pred, u_gt_nii.affine)
        save_file = os.path.join(cg.seg_data_dir, patient_class, patient_id,
                                 'seg-pred-0.625-4classes',
                                 seg_filename + str(time) +
                                 '.nii.gz')  # predicted segmentation file
        os.makedirs(os.path.dirname(save_file), exist_ok=True)
        nb.save(u_pred, save_file)
def test_crop_or_pad():

    ##
    ## Test when a target is an `int`
    ##

    # a.ndim == 1
    a = np.ones((75))
    t = dv.crop_or_pad(a, 64)
    assert np.allclose(t.shape, [64])

    a = np.ones((75))
    t = dv.crop_or_pad(a, 128)
    assert np.allclose(t.shape, [128])

    # a.ndim == 2
    a = np.ones((75, 75))
    t = dv.crop_or_pad(a, 64)
    assert np.allclose(t.shape, [64, 64])

    a = np.ones((75, 75))
    t = dv.crop_or_pad(a, 128)
    assert np.allclose(t.shape, [128, 128])

    # a.ndim == 3
    a = np.ones((75, 75, 75))
    t = dv.crop_or_pad(a, 64)
    assert np.allclose(t.shape, [64, 64, 64])

    a = np.ones((75, 75, 75))
    t = dv.crop_or_pad(a, 128)
    assert np.allclose(t.shape, [128, 128, 128])

    ##
    ## Test when a target is an `int`
    ##

    # a.ndim == 1
    a = np.ones((75))
    t = dv.crop_or_pad(a, (64))
    assert np.allclose(t.shape, [64])

    a = np.ones((75))
    t = dv.crop_or_pad(a, (128))
    assert np.allclose(t.shape, [128])

    # a.ndim == 2
    a = np.ones((75, 75))
    t = dv.crop_or_pad(a, (64, 64))
    assert np.allclose(t.shape, [64, 64])

    a = np.ones((75, 75))
    t = dv.crop_or_pad(a, (128, 128))
    assert np.allclose(t.shape, [128, 128])

    # a.ndim == 3
    a = np.ones((75, 75, 75))
    t = dv.crop_or_pad(a, (64, 64, 64))
    assert np.allclose(t.shape, [64, 64, 64])

    a = np.ones((75, 75, 75))
    t = dv.crop_or_pad(a, (128, 128, 128))
    assert np.allclose(t.shape, [128, 128, 128])
	segment = nib.load(seg)
	np_img = np.array(image.dataobj)
	
	

	np_seg = np.array(segment.dataobj)
	
	np_seg[np_seg>9]=10
	# print(len(np_seg[np_seg>0]),len(np_seg[np_seg==0]))


	# np_seg = converted_labels(np_seg,np_img)
	np_img[np_img<-clip] = -clip
	np_img[np_img>clip] = clip
	np_img = np_img
	np_img= dv.crop_or_pad(np_img, cg.dim)
	


	np_seg= dv.crop_or_pad(np_seg, cg.dim)
	# np_img,np_seg = random_transform(np_img,np_seg)
	# array_img = nib.Nifti1Image(np_img,image.affine,header=image.header)

	# nib.save(array_img,"test.nii.gz")
	# array_img = nib.Nifti1Image(np_seg,segment.affine,header=segment.header)

	# nib.save(array_img,"testseg.nii.gz")
	

	# np_seg[np_seg>10]=1
	
Beispiel #8
0
def mask_to_transform(seg,
                      rotation=0.0,
                      margin=0.0,
                      radians=True,
                      return_images=False):

    assert seg.ndim == 2

    seg_original = seg.copy()
    seg = dv.binarize_array(seg)

    ##
    ## Calculate Useful Quantities
    ##

    ctr = [s // 2 for s in seg.shape]
    com = center_of_mass(seg)
    nrm = [
        2.0 * (i_com - i_ctr) / i_shp
        for i_com, i_ctr, i_shp in zip(com, ctr, seg.shape)
    ]
    ost = [-n * c for n, c in zip(nrm, ctr)]

    if radians:
        rotation = np.degrees(rotation)

    ##
    ## Translation
    ##

    seg_xy = itp.shift(seg, ost, order=0, mode="constant", cval=0)

    ##
    ## Rotation
    ##

    seg_rt = itp.rotate(seg_xy,
                        rotation,
                        reshape=False,
                        order=0,
                        mode="nearest")

    ##
    ## Zoom
    ##

    bbox = dv.bounding_box(seg_rt)

    scale = [(i_max - i_min) / i_shp
             for (i_min, i_max), i_shp in zip(bbox, seg.shape)]

    scale = max(scale)

    scale = min(1.0, scale + margin * 2.0)

    if return_images:
        seg_xy = itp.shift(seg_original, ost, order=0, mode="constant", cval=0)
        seg_rt = itp.rotate(seg_xy,
                            rotation,
                            reshape=False,
                            order=0,
                            mode="nearest")
        seg_zm = dv.crop_or_pad(itp.zoom(seg_rt, 1.0 / scale, order=0),
                                seg.shape)
        return nrm, -np.radians(rotation), scale, seg_xy, seg_rt, seg_zm
    else:
        return nrm, -np.radians(rotation), scale
Beispiel #9
0
def in_adapt(x, target=cg.dim):
    x = nb.load(x).get_data()
    # clip the very high value
    x = dv.crop_or_pad(x, target)
    x = np.expand_dims(x, axis=-1)
    return x
Beispiel #10
0
out_base = os.path.expanduser('~/Dropbox/Cardiac_Segmentation/manuscript-ohm-net-data/ohm/')

patients = gb.glob(os.path.join(base, '*/HCMNet_*/*/*/'))

offsets = {'00_SAX' : np.pi,
           '01_HLA' : np.pi / 2.0,
           '02_VLA' : np.pi / 2.0,
          }

for p in patients:
  print(p)

  rotation = np.load(os.path.join(p, 'rotation.npy')) + offsets[dv.tokenize_path(p)[-2]]

  sg = np.asarray(nb.load(os.path.join(p, 'seg_gt.nii')).get_data())[:,:,0]
  sg = dv.crop_or_pad(sg, target = 256)
  xy, rt, zm, s_xy, s_rt, s_zm = dv.mask_to_transform(sg,
                                                      rotation = rotation,
                                                      margin = 0.1,
                                                      return_images = True)

  im = np.asarray(Image.open(os.path.join(p, 'ssfp/0.png')))
  im = dv.crop_or_pad(equalize_hist(dv.correct_nonuniform_illumination(im)), target = 256)
  i_xy = itp.shift(im, np.array(xy)*-128)
  i_rt = itp.rotate(i_xy, rotation*180/np.pi, reshape = False)
  i_zm = dv.crop_or_pad(itp.zoom(i_rt, 1.0/zm), target = 256)

  out_file = os.path.join(out_base, *dv.tokenize_path(p)[-4:])
  os.makedirs(out_file, exist_ok = True)

  dv.save_interpolated_image(im, os.path.join(out_file, 'im.png'))
Beispiel #11
0
 def out_adapt_raw(self, x, target=cg.dim):
     """Assumes that image is stored as a nifti file.  Update for your images."""
     x = nb.load(x).get_data()
     return dv.crop_or_pad(x, target)
Beispiel #12
0
 def in_adapt(self, x, target=cg.dim):
     """Assumes that image is stored as a nifti file.  Update for your images."""
     x = nb.load(x).get_data()
     x = dv.crop_or_pad(x, target)
     x = np.expand_dims(x, axis=-1)
     return x