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