当前位置: 首页>>代码示例>>Python>>正文


Python nibabel.save方法代码示例

本文整理汇总了Python中nibabel.save方法的典型用法代码示例。如果您正苦于以下问题:Python nibabel.save方法的具体用法?Python nibabel.save怎么用?Python nibabel.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在nibabel的用法示例。


在下文中一共展示了nibabel.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: extractMeanDataStats

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def extractMeanDataStats(size = [200, 200, 100], 
						postfix = '_200x200x100orig', 
						main_folder_path = '../../Data/MS2017b/', 
						):
	scan_folders = glob.glob(main_folder_path + 'scans/*')
	img_path = 'pre/FLAIR' + postfix + '.nii.gz'
	segm_path = 'wmh' + postfix + '.nii.gz'
	
	shape_ = [len(scan_folders), size[0], size[1], size[2]]
	arr = np.zeros(shape_)

	for i, sf in enumerate(scan_folders):
		arr[i, :,:,:] =  numpyFromScan(os.path.join(sf,img_path)).squeeze()

	arr /= len(scan_folders)

	means = np.mean(arr)
	stds = np.std(arr, axis = 0)

	np.save(main_folder_path + 'extra_data/std' + postfix, stds)
	np.save(main_folder_path + 'extra_data/mean' + postfix, means) 
开发者ID:Achilleas,项目名称:pytorch-mri-segmentation-3D,代码行数:23,代码来源:PP.py

示例2: generateImgSlicesFolder

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def generateImgSlicesFolder(data_folder = '../Data/MS2017a/scans/'):
	scan_folders = glob.glob(data_folder + '*')

	for sf in scan_folders:
		slice_dir_path = os.path.join(sf, 'slices/')
		if not os.path.exists(slice_dir_path):
			print('Creating directory at:' , slice_dir_path)
			os.makedirs(slice_dir_path)

		img = nib.load(os.path.join(sf, 'pre/FLAIR.nii.gz'))
		img_np = img.get_data()
		img_affine = img.affine
		print(sf)
		print('The img shape', img_np.shape[2])
		for i in range(img_np.shape[2]):
			slice_img_np = img_np[:,:,i]
			nft_img = nib.Nifti1Image(slice_img_np, img_affine)
			nib.save(nft_img, slice_dir_path + 'FLAIR_' + str(i) + '.nii.gz')

			if os.path.basename(sf) == '0':
				slice_img = nib.load(slice_dir_path + 'FLAIR_' + str(i) + '.nii.gz').get_data() / 5
				print('DID I GET HERE?')
				print('Writing to', str(i) + '.jpg') 
开发者ID:Achilleas,项目名称:pytorch-mri-segmentation-3D,代码行数:25,代码来源:PP.py

示例3: generateGTSlicesFolder

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def generateGTSlicesFolder(data_folder = '../Data/MS2017a/scans/'):
	scan_folders = glob.glob(data_folder + '*')

	for sf in scan_folders:
		slice_dir_path = os.path.join(sf, 'gt_slices/')
		if not os.path.exists(slice_dir_path):
			print('Creating directory at:' , slice_dir_path)
			os.makedirs(slice_dir_path)

		img = nib.load(os.path.join(sf, 'wmh.nii.gz'))
		img_np = img.get_data()
		img_affine = img.affine
		print(sf)
		print('The img shape', img_np.shape[2])
		for i in range(img_np.shape[2]):
			slice_img_np = img_np[:,:,i]
			nft_img = nib.Nifti1Image(slice_img_np, img_affine)
			nib.save(nft_img, slice_dir_path + 'wmh_' + str(i) + '.nii.gz')

			if os.path.basename(sf) == '0':
				slice_img = nib.load(slice_dir_path + 'wmh_' + str(i) + '.nii.gz').get_data() * 256
				#cv2.imwrite('temp/' + str(i) + '.jpg', slice_img) 
开发者ID:Achilleas,项目名称:pytorch-mri-segmentation-3D,代码行数:24,代码来源:PP.py

示例4: generateTrainValFile_Slices

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def generateTrainValFile_Slices(train_fraction, main_folder = '../Data/MS2017a/'):
	train_folders, val_folders = splitTrainVal_Slices(0.8)

	train_folder_names = [train_folders[i].split(main_folder)[1] for i in range(len(train_folders))]
	val_folder_names = [val_folders[i].split(main_folder)[1] for i in range(len(val_folders))]

	f_train = open(main_folder + 'train_slices.txt', 'w+')
	f_val = open(main_folder + 'val_slices.txt', 'w+')

	for fn in train_folder_names:
		f_train.write(fn + '\n')

	for fn in val_folder_names:
		f_val.write(fn + '\n')

	f_train.close()
	f_val.close()

#Use this to save the images quickly (for testing purposes) 
开发者ID:Achilleas,项目名称:pytorch-mri-segmentation-3D,代码行数:21,代码来源:PP.py

示例5: test_to_nonlinear_grid_crop

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def test_to_nonlinear_grid_crop(self, sphere3_msh):
        import nibabel
        data = sphere3_msh.elm.tag1
        f = mesh_io.ElementData(data, mesh=sphere3_msh)
        affine = np.array([[1, 0, 0, -100.5],
                           [0, 1, 0, -5],
                           [0, 0, 1, 0],
                           [0, 0, 0, 1]], dtype=float)
        x, y, z = np.meshgrid(np.arange(-100, 100),
                              np.arange(-5, 5),
                              np.arange(0, 1),
                              indexing='ij')
        nonl_transform = np.concatenate(
            (x[..., None], y[..., None], z[..., None]), axis=3).astype(float)
        img = nibabel.Nifti1Pair(nonl_transform, affine)
        tempf = tempfile.NamedTemporaryFile(suffix='.nii', delete=False)
        fn = tempf.name
        tempf.close()
        nibabel.save(img, fn)
        interp = f.to_deformed_grid(fn, fn, tags=3, method='assign')
        interp = interp.get_data()
        assert np.isclose(interp[100, 5, 0], 3)
        assert np.isclose(interp[187, 5, 0], 0)
        assert np.isclose(interp[193, 5, 0], 0)
        assert np.isclose(interp[198, 5, 0], 0) 
开发者ID:simnibs,项目名称:simnibs,代码行数:27,代码来源:test_mesh_io.py

示例6: auto_crop_image

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def auto_crop_image(input_name, output_name, reserve):
    nim = nib.load(input_name)
    image = nim.get_data()
    X, Y, Z = image.shape[:3]

    # Detect the bounding box of the foreground
    idx = np.nonzero(image > 0)
    x1, x2 = idx[0].min() - reserve, idx[0].max() + reserve + 1
    y1, y2 = idx[1].min() - reserve, idx[1].max() + reserve + 1
    z1, z2 = idx[2].min() - reserve, idx[2].max() + reserve + 1
    x1, x2 = max(x1, 0), min(x2, X)
    y1, y2 = max(y1, 0), min(y2, Y)
    z1, z2 = max(z1, 0), min(z2, Z)
    print('Bounding box')
    print('  bottom-left corner = ({},{},{})'.format(x1, y1, z1))
    print('  top-right corner = ({},{},{})'.format(x2, y2, z2))

    # Crop the image
    image = image[x1:x2, y1:y2, z1:z2]

    # Update the affine matrix
    affine = nim.affine
    affine[:3, 3] = np.dot(affine, np.array([x1, y1, z1, 1]))[:3]
    nim2 = nib.Nifti1Image(image, affine)
    nib.save(nim2, output_name) 
开发者ID:baiwenjia,项目名称:ukbb_cardiac,代码行数:27,代码来源:image_utils.py

示例7: save_slice_volume

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def save_slice_volume(volume, save_path):
    '''
    the function save volume data to slices in the specific directory
    :param volume: input volume data
    :param save_path:
    :return:
    '''
    shape = volume.shape
    # translate intensity to 0-255
    v_max = np.max(volume)
    v_min = np.min(volume)
    volume_norm = (volume - v_min) / (v_max - v_min)
    volume_norm = (volume_norm * 255).astype("int")
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    for i in range(shape[-1]):
        abs_path = os.path.join(save_path, str(i)+".png")
        cv.imwrite(abs_path, volume_norm[..., i])


# calculate the cube information 
开发者ID:JohnleeHIT,项目名称:Brats2019,代码行数:23,代码来源:utils.py

示例8: _write_raw_fif

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def _write_raw_fif(raw, bids_fname):
    """Save out the raw file in FIF.

    Parameters
    ----------
    raw : mne.io.Raw
        Raw file to save out.
    bids_fname : str | BIDSPath
        The name of the BIDS-specified file where the raw object
        should be saved.

    """
    n_rawfiles = len(raw.filenames)
    if n_rawfiles > 1:
        split_naming = 'bids'
        raw.save(bids_fname, split_naming=split_naming, overwrite=True)
    else:
        # This ensures that single FIF files do not have the split param
        raw.save(bids_fname, split_naming='neuromag', overwrite=True) 
开发者ID:mne-tools,项目名称:mne-bids,代码行数:21,代码来源:write.py

示例9: _write_gifti

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def _write_gifti(pd, opth):
    # TODO: what about pointdata?
    from nibabel.gifti.gifti import GiftiDataArray

    if not pd.has_only_triangle:
        raise ValueError('GIFTI writer only accepts triangles.')

    points = GiftiDataArray(data=pd.Points, intent=INTENT_POINTS)
    cells = GiftiDataArray(data=pd.GetCells2D(), intent=INTENT_CELLS)
    # if data is not None:
    #     data_array = GiftiDataArray(data=data, intent=INTENT_POINTDATA)
    #     gii = nb.gifti.GiftiImage(darrays=[points, cells, data_array])
    # else:
    g = nb.gifti.GiftiImage(darrays=[points, cells])
    nb.save(g, opth)


###############################################################################
# VTK Reader and Writer for GIFTI surfaces
############################################################################### 
开发者ID:MICA-MNI,项目名称:BrainSpace,代码行数:22,代码来源:gifti_support.py

示例10: test_shape

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def test_shape(self, num_workers, dataset_size):
        test_image = nib.Nifti1Image(np.random.randint(0, 2, size=[128, 128, 128]), np.eye(4))
        tempdir = tempfile.mkdtemp()
        nib.save(test_image, os.path.join(tempdir, "test_image1.nii.gz"))
        nib.save(test_image, os.path.join(tempdir, "test_label1.nii.gz"))
        nib.save(test_image, os.path.join(tempdir, "test_extra1.nii.gz"))
        test_data = [
            {
                "image": os.path.join(tempdir, "test_image1.nii.gz"),
                "label": os.path.join(tempdir, "test_label1.nii.gz"),
                "extra": os.path.join(tempdir, "test_extra1.nii.gz"),
            }
        ] * dataset_size
        dataset = CacheDataset(
            data=test_data,
            transform=Compose([LoadNiftid(keys=["image", "label", "extra"])]),
            cache_rate=1,
            num_workers=num_workers,
        )
        shutil.rmtree(tempdir)
        self.assertEqual(len(dataset._cache), dataset.cache_num)
        for i in range(dataset.cache_num):
            self.assertIsNotNone(dataset._cache[i]) 
开发者ID:Project-MONAI,项目名称:MONAI,代码行数:25,代码来源:test_cachedataset_parallel.py

示例11: test_default_none

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def test_default_none(self, img_transform, expected_shape):
        test_image = nib.Nifti1Image(np.random.randint(0, 2, size=(128, 128, 128)), np.eye(4))
        tempdir = tempfile.mkdtemp()
        test_image1 = os.path.join(tempdir, "test_image1.nii.gz")
        test_image2 = os.path.join(tempdir, "test_image2.nii.gz")
        nib.save(test_image, test_image1)
        nib.save(test_image, test_image2)
        test_images = [test_image1, test_image2]
        dataset = ArrayDataset(test_images, img_transform)
        self.assertEqual(len(dataset), 2)
        dataset.set_random_state(1234)
        data1 = dataset[0]
        data2 = dataset[1]
        self.assertTupleEqual(data1.shape, expected_shape)
        self.assertTupleEqual(data2.shape, expected_shape)

        dataset = ArrayDataset(test_images, img_transform)
        dataset.set_random_state(1234)
        _ = dataset[0]
        data2_new = dataset[1]
        np.testing.assert_allclose(data2, data2_new, atol=1e-3)
        shutil.rmtree(tempdir) 
开发者ID:Project-MONAI,项目名称:MONAI,代码行数:24,代码来源:test_arraydataset.py

示例12: test_shape

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def test_shape(self, input_param, filenames, expected_shape):
        test_image = np.random.randint(0, 2, size=[128, 128, 128])
        tempdir = tempfile.mkdtemp()
        for i, name in enumerate(filenames):
            filenames[i] = os.path.join(tempdir, name)
            nib.save(nib.Nifti1Image(test_image, np.eye(4)), filenames[i])
        result = LoadNifti(**input_param)(filenames)

        if isinstance(result, tuple):
            result, header = result
            self.assertTrue("affine" in header)
            np.testing.assert_allclose(header["affine"], np.eye(4))
            if input_param["as_closest_canonical"]:
                np.testing.asesrt_allclose(header["original_affine"], np.eye(4))
        self.assertTupleEqual(result.shape, expected_shape)
        shutil.rmtree(tempdir) 
开发者ID:Project-MONAI,项目名称:MONAI,代码行数:18,代码来源:test_load_nifti.py

示例13: save_landmarks_pts

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def save_landmarks_pts(path_file, landmarks):
    """ save landmarks into a txt file

    we are using VTK pointdata legacy format, ITK compatible::

        <index, point>
        <number of points>
        point1-x point1-y [point1-z]
        point2-x point2-y [point2-z]

    .. seealso:: https://simpleelastix.readthedocs.io/PointBasedRegistration.html

    :param str path_file: path to the output file
    :param landmarks: np.array<np_points, dim>
    :return str: file path
    """
    assert os.path.isdir(os.path.dirname(path_file)), \
        'missing folder "%s"' % os.path.dirname(path_file)
    path_file = os.path.splitext(path_file)[0] + '.pts'
    lines = ['point', str(len(landmarks))]
    lines += [' '.join(str(i) for i in point) for point in landmarks]
    with open(path_file, 'w') as fp:
        fp.write('\n'.join(lines))
    return path_file 
开发者ID:Borda,项目名称:BIRL,代码行数:26,代码来源:data_io.py

示例14: save_landmarks_csv

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def save_landmarks_csv(path_file, landmarks):
    """ save landmarks into a csv file

    we are using simple format::

        ,X,Y
        0,point1-x,point1-y
        1,point2-x,point2-y

    :param str path_file: path to the output file
    :param landmarks: np.array<np_points, dim>
    :return str: file path
    """
    assert os.path.isdir(os.path.dirname(path_file)), \
        'missing folder "%s"' % os.path.dirname(path_file)
    path_file = os.path.splitext(path_file)[0] + '.csv'
    df = pd.DataFrame(landmarks, columns=LANDMARK_COORDS)
    df.index = np.arange(1, len(df) + 1)
    df.to_csv(path_file)
    return path_file 
开发者ID:Borda,项目名称:BIRL,代码行数:22,代码来源:data_io.py

示例15: save_image

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import save [as 别名]
def save_image(path_image, image):
    """ save the image into given path

    :param str path_image: path to the image
    :param image: np.array<height, width, ch>

    >>> # Wrong path
    >>> save_image('./missing-path/any-image.png', np.zeros((10, 20)))
    False
    """
    path_dir = os.path.dirname(path_image)
    if not os.path.isdir(path_dir):
        logging.error('upper folder does not exists: "%s"', path_dir)
        return False
    image = convert_ndarray2image(image)
    image.save(path_image) 
开发者ID:Borda,项目名称:BIRL,代码行数:18,代码来源:data_io.py


注:本文中的nibabel.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。