Beispiel #1
0
    def updateHeader(self, hdrdict):
        """Deprecated method only here for backward compatibility.

        Please refer to NiftiFormat.updateFromDict()
        """
        warn(
            "updateHeader function is deprecated and will be removed with "
            "PyNIfTI 1.0.  Please use updateFromDict instead.",
            DeprecationWarning,
        )
        NiftiFormat.updateFromDict(self, hdrdict)
Beispiel #2
0
 def can_load(self):
     loadable = False
     try:
         NiftiFormat(self._filename)
         loadable = True
     except:
         pass
     return loadable
Beispiel #3
0
    def __init__(self, source, header=None, load=False, **kwargs):
        """
        :Parameters:
          source: str | ndarray
            If source is a string, it is assumed to be a filename and an
            attempt will be made to open the corresponding NIfTI file.
            In case of an ndarray the array data will be used for the to be
            created nifti image and a matching nifti header is generated.
            If an object of a different type is supplied as 'source' a
            ValueError exception will be thrown.
          header: dict
            Additional header data might be supplied. However,
            dimensionality and datatype are determined from the ndarray and
            not taken from a header dictionary.
          load: Boolean
            If set to True the image data will be loaded into memory. This
            is only useful if loading a NIfTI image from file.
            This flag is almost useless, as the data will be loaded
            automatically whenever it is accessed.
          **kwargs:
            Additional stuff is passed to :class:`~nifti.format.NiftiFormat`.
        """
        # setup all nifti header related stuff
        NiftiFormat.__init__(self, source, header, **kwargs)

        # where the data will go to
        self._data = None

        # load data
        if type(source) == N.ndarray:
            # assign data from source array
            self._data = source[:]
        elif type(source) in (str, unicode):
            # only load image data from file if requested
            if load:
                self.load()
        else:
            raise ValueError, "Unsupported source type. Only NumPy arrays and filename " + "string are supported."
Beispiel #4
0
    def __del__(self):
        self.unload()

        # it is required to call base class destructors!
        NiftiFormat.__del__(self)
Beispiel #5
0
 def getFilename(self):
     """Please see :meth:`nifti.format.NiftiFormat.getFilename`
     for the documentation."""
     return NiftiFormat.getFilename(self)
Beispiel #6
0
    def __del__(self):
        self._data.flush()

        # it is required to call base class destructors!
        NiftiFormat.__del__(self)
Beispiel #7
0
    def load_metadata(self, index=0):
        format = NiftiFormat(self._filename)

        metadata = {}

        # Get the number of dimensions in the image from the extent
        nb_dimensions = len(format.extent)
        for i in range(max(len(format.extent) - 3, 0)):
            if format.extent[-1] == 1:
                nb_dimensions -= 1
            else:
                break
        # Get spacing and origin for those dimensions. Reverse to keep the order
        # of the numpy array
        metadata["spacing"] = format.asDict()["pixdim"][1:nb_dimensions + 1]
        metadata["spacing"].reverse()
        metadata["spacing"] = numpy.asarray(metadata["spacing"])

        if format.asDict()["scl_slope"] != 0:
            metadata["slope"] = format.asDict()["scl_slope"]
            metadata["shift"] = format.asDict()["scl_inter"]

        metadata["header"] = format.asDict()
        metadata["annotations"] = ObservableList()

        #########################
        # Diffusion information #
        #########################

        # Load gradient direction file
        base_name = os.path.splitext(self._filename)[0]
        if base_name.endswith(".nii"):
            base_name = os.path.splitext(base_name)[0]
        gradient_candidates = [
            base_name + ".bvecs",  # /foo/bar/image.bvecs
            base_name + ".bvec",  # /foo/bar/image.bvec
            os.path.join(os.path.dirname(self._filename),
                         "bvecs"),  # /foo/bar/bvecs
            os.path.join(os.path.dirname(self._filename),
                         "bvec")  # /foo/bar/bvec
        ]
        gradient_file = None
        for candidate in gradient_candidates:
            if os.path.isfile(candidate):
                gradient_file = candidate
                break

        # Load b-values file
        bvalue_candidates = [
            base_name + ".bvals",  # /foo/bar/image.bvals
            base_name + ".bval",  # /foo/bar/image.bval
            os.path.join(os.path.dirname(self._filename),
                         "bval"),  # /foo/bar/bvals
            os.path.join(os.path.dirname(self._filename),
                         "bvals")  # /foo/bar/bval
        ]
        bvalue_file = None
        for candidate in bvalue_candidates:
            if os.path.isfile(candidate):
                bvalue_file = candidate
                break

        if None not in [gradient_file, bvalue_file]:
            gradients = numpy.loadtxt(gradient_file, dtype=numpy.single)
            bvalues = numpy.loadtxt(bvalue_file, dtype=numpy.single)

            gradients = gradients.T

            mr_diffusion_sequence = []
            for index, gradient in enumerate(gradients):
                dataset = medipy.io.dicom.DataSet()
                dataset.diffusion_directionality = "DIRECTIONAL"

                dataset.diffusion_bvalue = bvalues[index]

                gradient_dataset = medipy.io.dicom.DataSet()
                gradient_dataset.diffusion_gradient_orientation = gradient
                dataset.diffusion_gradient_direction_sequence = [
                    gradient_dataset
                ]

                mr_diffusion_sequence.append(dataset)

            metadata["mr_diffusion_sequence"] = mr_diffusion_sequence

        return metadata