當前位置: 首頁>>代碼示例>>Python>>正文


Python nibabel.as_closest_canonical方法代碼示例

本文整理匯總了Python中nibabel.as_closest_canonical方法的典型用法代碼示例。如果您正苦於以下問題:Python nibabel.as_closest_canonical方法的具體用法?Python nibabel.as_closest_canonical怎麽用?Python nibabel.as_closest_canonical使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在nibabel的用法示例。


在下文中一共展示了nibabel.as_closest_canonical方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _get_limits

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def _get_limits(nifti_file, only_plot_noise=False):
    if isinstance(nifti_file, str):
        nii = nb.as_closest_canonical(nb.load(nifti_file))
        data = nii.get_data()
    else:
        data = nifti_file

    data_mask = np.logical_not(np.isnan(data))

    if only_plot_noise:
        data_mask = np.logical_and(data_mask, data != 0)
        vmin = np.percentile(data[data_mask], 0)
        vmax = np.percentile(data[data_mask], 61)
    else:
        vmin = np.percentile(data[data_mask], 0.5)
        vmax = np.percentile(data[data_mask], 99.5)

    return vmin, vmax 
開發者ID:poldracklab,項目名稱:mriqc,代碼行數:20,代碼來源:utils.py

示例2: load_unit

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def load_unit(self, unit_id):
        """Loads the image data for display."""

        img_path = self.unit_by_id[unit_id]['image']
        params_path = self.unit_by_id[unit_id]['params']
        try:
            hdr = nib.load(img_path)
            self.hdr_this_unit = nib.as_closest_canonical(hdr)
            self.img_this_unit_raw = self.hdr_this_unit.get_data()
        except Exception as exc:
            print(exc)
            print('Unable to read image at \n\t{}'.format(img_path))
            skip_subject = True
        else:
            check_image_is_4d(self.img_this_unit_raw)
            self.TR_this_unit = self.hdr_this_unit.header.get_zooms()[-1]

            skip_subject = False
            if np.count_nonzero(self.img_this_unit_raw) == 0:
                skip_subject = True
                print('Functional image is empty!')

        return skip_subject 
開發者ID:raamana,項目名稱:visualqc,代碼行數:25,代碼來源:functional_mri.py

示例3: run

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def run(opts):

	img = nib.as_closest_canonical(nib.load(opts.image[0])) # for pesky LR flipping
	data = img.get_data()
	hdr = img.get_header()
	low_threshold, _ = autothreshold(data, threshold_type = opts.thresholdalgorithm)
	print(low_threshold)
	mask = np.zeros_like(data)
	mask[:] = data
	mask[mask < low_threshold] = 0
#	mask[mask != 0] = 1
	nib.save(nib.Nifti1Image(mask.astype(np.float32, order = "C"),affine=img.affine),'temp.nii.gz')
	os.system(os.environ["FSLDIR"] + "/bin/bet temp.nii.gz temp_brain.nii.gz -m -f 0.3")
	betmask = nib.as_closest_canonical(nib.load('temp_brain_mask.nii.gz')).get_data()
	data[betmask!=1] = 0
	if opts.output:
		nib.save(nib.Nifti1Image(data.astype(np.float32, order = "C"),affine=img.affine), opts.output[0])
	elif opts.replace:
		base, name = os.path.split(opts.replace[0])
		os.system("mv %s %s/backup_%s" % (opts.replace[0], base, name))
		nib.save(nib.Nifti1Image(data.astype(np.float32, order = "C"),affine=img.affine), opts.replace[0])
	else:
		nib.save(nib.Nifti1Image(data.astype(np.float32, order = "C"),affine=img.affine),'bet_' + opts.image[0])
	os.system("rm temp*.nii.gz") 
開發者ID:trislett,項目名稱:TFCE_mediation,代碼行數:26,代碼來源:fast_bet.py

示例4: __init__

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def __init__(self, input_filename, gt_filename, cache=True,
                 canonical=False):
        self.input_filename = input_filename
        self.gt_filename = gt_filename
        self.canonical = canonical
        self.cache = cache

        self.input_handle = nib.load(self.input_filename)

        # Unlabeled data (inference time)
        if self.gt_filename is None:
            self.gt_handle = None
        else:
            self.gt_handle = nib.load(self.gt_filename)

        if len(self.input_handle.shape) > 3:
            raise RuntimeError("4-dimensional volumes not supported.")

        # Sanity check for dimensions, should be the same
        input_shape, gt_shape = self.get_pair_shapes()

        if self.gt_handle is not None:
            if not np.allclose(input_shape, gt_shape):
                raise RuntimeError('Input and ground truth with different dimensions.')

        if self.canonical:
            self.input_handle = nib.as_closest_canonical(self.input_handle)

            # Unlabeled data
            if self.gt_handle is not None:
                self.gt_handle = nib.as_closest_canonical(self.gt_handle) 
開發者ID:perone,項目名稱:medicaltorch,代碼行數:33,代碼來源:datasets.py

示例5: apply_transform

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def apply_transform(self, sample: Subject) -> dict:
        for image_dict in sample.get_images(intensity_only=False):
            affine = image_dict[AFFINE]
            if nib.aff2axcodes(affine) == tuple('RAS'):
                continue
            array = image_dict[DATA][0].numpy()
            nii = nib.Nifti1Image(array, affine)
            reoriented = nib.as_closest_canonical(nii)
            array = reoriented.get_fdata(dtype=np.float32)
            # https://github.com/facebookresearch/InferSent/issues/99#issuecomment-446175325
            array = array.copy()[np.newaxis, ...]
            image_dict[DATA] = torch.from_numpy(array)
            image_dict[AFFINE] = reoriented.affine
        return sample 
開發者ID:fepegar,項目名稱:torchio,代碼行數:16,代碼來源:to_canonical.py

示例6: read_image

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def read_image(img_spec,
               error_msg='image',
               num_dims=3,
               reorient_canonical=True):
    """Image reader. Removes stray values close to zero (smaller than 5 %ile)."""

    if isinstance(img_spec, str):
        if pexists(realpath(img_spec)):
            hdr = nib.load(img_spec)
            # trying to stick to an orientation
            if reorient_canonical:
                hdr = nib.as_closest_canonical(hdr)
            img = hdr.get_data()
        else:
            raise IOError('Given path to {} does not exist!\n\t{}'
                          ''.format(error_msg, img_spec))
    elif isinstance(img_spec, np.ndarray):
        img = img_spec
    else:
        raise ValueError('Invalid input specified! '
                         'Input either a path to image data, '
                         'or provide 3d Matrix directly.')

    if num_dims == 3:
        img = check_image_is_3d(img)
    elif num_dims == 4:
        check_image_is_4d(img)
    else:
        raise ValueError('Requested check for {} dims - allowed: 3 or 4!')

    if not np.issubdtype(img.dtype, np.float64):
        img = img.astype('float32')

    return img 
開發者ID:raamana,項目名稱:visualqc,代碼行數:36,代碼來源:utils.py

示例7: _run_interface

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def _run_interface(self, runtime):
        # Load images, orient as RAS, collect shape and zoom data
        in_names = np.array(self.inputs.t1w_list)
        orig_imgs = np.vectorize(nb.load)(in_names)
        reoriented = np.vectorize(nb.as_closest_canonical)(orig_imgs)
        all_zooms = np.array([img.header.get_zooms()[:3] for img in reoriented])
        all_shapes = np.array([img.shape[:3] for img in reoriented])

        # Identify images that would require excessive up-sampling
        valid = np.ones(all_zooms.shape[0], dtype=bool)
        while valid.any():
            target_zooms = all_zooms[valid].min(axis=0)
            scales = all_zooms[valid] / target_zooms
            if np.all(scales < self.inputs.max_scale):
                break
            valid[valid] ^= np.any(scales == scales.max(), axis=1)

        # Ignore dropped images
        valid_fnames = np.atleast_1d(in_names[valid]).tolist()
        self._results["t1w_valid_list"] = valid_fnames

        # Set target shape information
        target_zooms = all_zooms[valid].min(axis=0)
        target_shape = all_shapes[valid].max(axis=0)

        self._results["target_zooms"] = tuple(target_zooms.tolist())
        self._results["target_shape"] = tuple(target_shape.tolist())

        # Create report
        dropped_images = in_names[~valid]
        segment = self._generate_segment(dropped_images, target_shape, target_zooms)
        out_report = os.path.join(runtime.cwd, "report.html")
        with open(out_report, "w") as fobj:
            fobj.write(segment)

        self._results["out_report"] = out_report

        return runtime 
開發者ID:nipreps,項目名稱:niworkflows,代碼行數:40,代碼來源:images.py

示例8: reorient

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def reorient(in_file, newpath=None):
    """Reorient Nifti files to RAS."""
    out_file = fname_presuffix(in_file, suffix="_ras", newpath=newpath)
    nb.as_closest_canonical(nb.load(in_file)).to_filename(out_file)
    return out_file 
開發者ID:nipreps,項目名稱:niworkflows,代碼行數:7,代碼來源:images.py

示例9: read_volume

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def read_volume(filepath, dtype=None, return_affine=False, to_ras=False):
    """Return numpy array of data from a neuroimaging file."""
    img = nib.load(filepath)
    if to_ras:
        img = nib.as_closest_canonical(img)
    data = img.get_fdata(caching="unchanged")
    if dtype is not None:
        data = data.astype(dtype)
    return data if not return_affine else (data, img.affine) 
開發者ID:neuronets,項目名稱:nobrainer,代碼行數:11,代碼來源:io.py

示例10: reorient

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def reorient(filename):
    img = nibabel.load(filename)
    img = nibabel.as_closest_canonical(img)
    nibabel.save(img, filename) 
開發者ID:MIC-DKFZ,項目名稱:nnUNet,代碼行數:6,代碼來源:Task062_NIHPancreas.py

示例11: reorient_to_RAS

# 需要導入模塊: import nibabel [as 別名]
# 或者: from nibabel import as_closest_canonical [as 別名]
def reorient_to_RAS(img_fname: str, output_fname: str = None):
    img = nib.load(img_fname)
    canonical_img = nib.as_closest_canonical(img)
    if output_fname is None:
        output_fname = img_fname
    nib.save(canonical_img, output_fname) 
開發者ID:MIC-DKFZ,項目名稱:nnUNet,代碼行數:8,代碼來源:sanity_checks.py


注:本文中的nibabel.as_closest_canonical方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。