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


Python nibabel.Nifti1Image方法代码示例

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


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

示例1: betaseries_file

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [as 别名]
def betaseries_file(tmpdir_factory,
                    deriv_betaseries_fname=deriv_betaseries_fname):
    bfile = tmpdir_factory.mktemp("beta").ensure(deriv_betaseries_fname)
    np.random.seed(3)
    num_trials = 40
    tgt_corr = 0.1
    bs1 = np.random.rand(num_trials)
    # create another betaseries with a target correlation
    bs2 = minimize(lambda x: abs(tgt_corr - pearsonr(bs1, x)[0]),
                   np.random.rand(num_trials)).x

    # two identical beta series
    bs_data = np.array([[[bs1, bs2]]])

    # the nifti image
    bs_img = nib.Nifti1Image(bs_data, np.eye(4))
    bs_img.to_filename(str(bfile))

    return bfile 
开发者ID:HBClab,项目名称:NiBetaSeries,代码行数:21,代码来源:conftest.py

示例2: generateImgSlicesFolder

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [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 Nifti1Image [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: quickSave

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [as 别名]
def quickSave(img, wmh, gif, n):
    nft_img = nib.Nifti1Image(img.squeeze(), np.eye(4))
    nib.save(nft_img, n + '_img.nii.gz')
    nft_img = nib.Nifti1Image(wmh.squeeze(), np.eye(4))
    nib.save(nft_img, n + '_wmh.nii.gz')
    if gif is not None:
        nft_img = nib.Nifti1Image(gif.squeeze(), np.eye(4))
        nib.save(nft_img, n + '_gif.nii.gz')

#------------------------------------------------------------------------------
#END OF SLICES PREPROCESSING
#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
#3D PREPROCESSING
#------------------------------------------------------------------------------
#go through every 3D object from training set and every patch of size NxNxN
#save resulting 3D volumes in one of the two folders based on what the center pixel of the image is 
开发者ID:Achilleas,项目名称:pytorch-mri-segmentation-3D,代码行数:20,代码来源:PP.py

示例5: mosaic_to_nii

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [as 别名]
def mosaic_to_nii(dcm_data):
    ''' Get Nifti file from Siemens

    Parameters
    ----------
    dcm_data : ``dicom.DataSet``
       DICOM header / image as read by ``dicom`` package

    Returns
    -------
    img : ``Nifti1Image``
       Nifti image object
    '''
    import nibabel as nib
    dcm_w = wrapper_from_data(dcm_data)
    if not dcm_w.is_mosaic:
        raise DicomReadError('data does not appear to be in mosaic format')
    data = dcm_w.get_data()
    aff = np.dot(DPCS_TO_TAL, dcm_w.get_affine())
    return nib.Nifti1Image(data, aff) 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:22,代码来源:dicomreaders.py

示例6: niwrite

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [as 别名]
def niwrite(data,affine, name , header=None):
	data[np.isnan(data)]=0
	stdout.write(" + Writing file: %s ...." % name) 
	
	thishead = header
	if thishead == None:
		thishead = head.copy()
		thishead.set_data_shape(list(data.shape))

	outni = nib.Nifti1Image(data,affine,header=thishead)
	outni.set_data_dtype('float64')
	outni.to_filename(name)
	

	print 'done.'

	return outni 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:19,代码来源:t2smap.py

示例7: test_calc_dAdt_nifti

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [as 别名]
def test_calc_dAdt_nifti(self, sphere3_msh):
        affine = np.array([[5., 0., 0., -300],
                           [0., 5., 0., -200],
                           [0., 0., 5., 0.],
                           [0., 0., 0., 1]])
        field = np.ones((121, 81, 41, 3))
        field[..., 1] = 2
        field[..., 2] = 3
        img = nib.Nifti1Image(field, affine)
        coil_matrix = np.array([[0., 1., 0., 0],
                                [1., 0., 0., 0],
                                [0., 0., 1., -100.],
                                [0., 0., 0., 1]])
        dadt = coil._calculate_dadt_nifti(sphere3_msh, img, coil_matrix, 1e6, None)
        sphere3_msh.nodedata.append(dadt)
        assert np.allclose(dadt.value[:, 0], 2e6, atol=1e-6)
        assert np.allclose(dadt.value[:, 1], 1e6, atol=1e-6)
        assert np.allclose(dadt.value[:, 2], 3e6, atol=1e-6) 
开发者ID:simnibs,项目名称:simnibs,代码行数:20,代码来源:test_coil.py

示例8: auto_crop_image

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [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

示例9: test_get_clusters_table

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [as 别名]
def test_get_clusters_table():
    shape = (9, 10, 11)
    data = np.zeros(shape)
    data[2:4, 5:7, 6:8] = 5.
    stat_img = nib.Nifti1Image(data, np.eye(4))

    # test one cluster extracted
    cluster_table = get_clusters_table(stat_img, 4, 0)
    assert len(cluster_table) == 1

    # test empty table on high stat threshold
    cluster_table = get_clusters_table(stat_img, 6, 0)
    assert len(cluster_table) == 0

    # test empty table on high cluster threshold
    cluster_table = get_clusters_table(stat_img, 4, 9)
    assert len(cluster_table) == 0 
开发者ID:nilearn,项目名称:nistats,代码行数:19,代码来源:test_reporting.py

示例10: test_load_spacingd

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [as 别名]
def test_load_spacingd(self, filename):
        data = {"image": filename}
        data_dict = LoadNiftid(keys="image")(data)
        data_dict = AddChanneld(keys="image")(data_dict)
        t = time.time()
        res_dict = Spacingd(keys="image", pixdim=(1, 0.2, 1), diagonal=True, padding_mode="zeros")(data_dict)
        t1 = time.time()
        print(f"time monai: {t1 - t}")
        anat = nibabel.Nifti1Image(data_dict["image"][0], data_dict["image_meta_dict"]["original_affine"])
        ref = resample_to_output(anat, (1, 0.2, 1), order=1)
        t2 = time.time()
        print(f"time scipy: {t2 - t1}")
        self.assertTrue(t2 >= t1)
        np.testing.assert_allclose(res_dict["image_meta_dict"]["affine"], ref.affine)
        np.testing.assert_allclose(res_dict["image"].shape[1:], ref.shape)
        np.testing.assert_allclose(ref.get_fdata(), res_dict["image"][0], atol=0.05) 
开发者ID:Project-MONAI,项目名称:MONAI,代码行数:18,代码来源:test_load_spacing_orientation.py

示例11: test_load_spacingd_rotate

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [as 别名]
def test_load_spacingd_rotate(self, filename):
        data = {"image": filename}
        data_dict = LoadNiftid(keys="image")(data)
        data_dict = AddChanneld(keys="image")(data_dict)
        affine = data_dict["image_meta_dict"]["affine"]
        data_dict["image_meta_dict"]["original_affine"] = data_dict["image_meta_dict"]["affine"] = (
            np.array([[0, 0, 1, 0], [0, 1, 0, 0], [-1, 0, 0, 0], [0, 0, 0, 1]]) @ affine
        )
        t = time.time()
        res_dict = Spacingd(keys="image", pixdim=(1, 2, 3), diagonal=True, padding_mode="zeros")(data_dict)
        t1 = time.time()
        print(f"time monai: {t1 - t}")
        anat = nibabel.Nifti1Image(data_dict["image"][0], data_dict["image_meta_dict"]["original_affine"])
        ref = resample_to_output(anat, (1, 2, 3), order=1)
        t2 = time.time()
        print(f"time scipy: {t2 - t1}")
        self.assertTrue(t2 >= t1)
        np.testing.assert_allclose(res_dict["image_meta_dict"]["affine"], ref.affine)
        if "anatomical" not in filename:
            np.testing.assert_allclose(res_dict["image"].shape[1:], ref.shape)
            np.testing.assert_allclose(ref.get_fdata(), res_dict["image"][0], atol=0.05)
        else:
            # different from the ref implementation (shape computed by round
            # instead of ceil)
            np.testing.assert_allclose(ref.get_fdata()[..., :-1], res_dict["image"][0], atol=0.05) 
开发者ID:Project-MONAI,项目名称:MONAI,代码行数:27,代码来源:test_load_spacing_orientation.py

示例12: test_shape

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [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

示例13: test_default_none

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [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

示例14: test_dataloading

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [as 别名]
def test_dataloading(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)
        loader = DataLoader(dataset, batch_size=10, num_workers=1)
        imgs = next(iter(loader))  # test batching
        np.testing.assert_allclose(imgs.shape, [2] + list(expected_shape))

        dataset.set_random_state(1234)
        new_imgs = next(iter(loader))  # test batching
        np.testing.assert_allclose(imgs, new_imgs, atol=1e-3) 
开发者ID:Project-MONAI,项目名称:MONAI,代码行数:20,代码来源:test_arraydataset.py

示例15: read_callosum_templates

# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import Nifti1Image [as 别名]
def read_callosum_templates(resample_to=False):
    """Load AFQ callosum templates from file

    Returns
    -------
    dict with: keys: names of template ROIs and values: nibabel Nifti1Image
    objects from each of the ROI nifti files.
    """
    files, folder = fetch_callosum_templates()
    template_dict = {}
    for f in files:
        img = nib.load(op.join(folder, f))
        if resample_to:
            if isinstance(resample_to, str):
                resample_to = nib.load(resample_to)
            img = nib.Nifti1Image(reg.resample(img.get_fdata(),
                                               resample_to,
                                               img.affine,
                                               resample_to.affine),
                                  resample_to.affine)
        template_dict[f.split('.')[0]] = img
    return template_dict 
开发者ID:yeatmanlab,项目名称:pyAFQ,代码行数:24,代码来源:data.py


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