def _build_nii(self, name): kwargs = {} if name.endswith('_meta'): kwargs['embed_meta'] = True name = name[:-5] if name.endswith('_SAR'): kwargs['voxel_order'] = 'SAR' name = name[:-4] if name == 'two_time_vol': stack = dcmstack.DicomStack(time_order='EchoTime') elif name == 'two_vector_vol': stack = dcmstack.DicomStack(vector_order='EchoTime') else: stack = dcmstack.DicomStack() stack.add_dcm(self.inputs[0]) if name == 'single_slice': return stack.to_nifti(**kwargs) stack.add_dcm(self.inputs[1]) if name == 'single_vol': return stack.to_nifti(**kwargs) stack.add_dcm(self.inputs[2]) stack.add_dcm(self.inputs[3]) if name in ('two_time_vol', 'two_vector_vol'): return stack.to_nifti(**kwargs) assert False # Unknown name
def multicoil_convert(self): """GE specific multicoil converesion. requires partial volume and missing slices check.""" log.debug('multicoil recon') mr.partial_vol_check(self) stacks = [] group_id = 0 for group in self._dcm_groups: group_id += 1 log.debug('multicoil - %2s, %s dicom' % (str(group_id), str(len(group)))) num_positions = len(set([d.SliceLocation for d in group])) if num_positions != self.num_slices: raise DicomError('coil %s has %s unique positions; expected %s' % (group_id, num_positions, self.num_slices)) stack = dcmstack.DicomStack() for dcm in group: meta = MetaExtractor(dcm) stack.add_dcm(dcm, meta) nii_wrp = stack.to_nifti_wrapper() stacks.append(nii_wrp) try: nii_wrp = dcmstack.dcmmeta.NiftiWrapper.from_sequence(stacks) except dcmstack.InvalidStackError as e: raise DicomError( 'cannot reconstruct %s: %s' % (self.filepath, e)) # XXX FAIL! unexpected for recon to fail # raise NIMSDicomError('cannot reconstruct %s: %s' % (self.filepath, e), log_level=logging.ERROR) del self._dcm_groups, self._dcm_list, stacks, stack, dcm nii = nii_wrp.nii_img self.data = {'': nii.get_data()} self.qto_xyz = nii.get_affine() del nii_wrp, nii mr.post_convert(self)
def fastcard_convert(self): """GE fast card conversion.""" log.debug('fast card') stacks = [] group_id = 0 def _split_list(l, size): return [l[i:i + size] for i in range(0, len(l), size)] dcm_groups = _split_list(self._dcm_list, self.total_num_slices / 5) for group in dcm_groups: group_id += 1 num_positions = len(set([d.SliceLocation for d in group])) if num_positions != self.num_slices: raise DicomError('volume %s has %s unique positions; expected %s' % (group_id, num_positions, self.num_slices)) stack = dcmstack.DicomStack() for d in group: meta = MetaExtractor(d) stack.add_dcm(d, meta) nii_wrp = stack.to_nifti_wrapper() stacks.append(nii_wrp) try: nii_wrp = dcmstack.dcmmeta.NiftiWrapper.from_sequence(stacks) except dcmstack.InvalidStackError as e: raise DicomError('cannot reconstruct %s: %s' % (self.filepath, str(e))) nii = nii_wrp.nii_img self.data = {'': nii.get_data()} self.qto_xyz = nii.get_affine() mr.post_convert(self)
def test_single_slice(self): stack = dcmstack.DicomStack() stack.add_dcm(self.inputs[0]) data = stack.get_data() eq_(data.shape, stack.get_shape()) eq_(sha256(data).hexdigest(), '15cfa107ca73810a1c97f1c1872a7a4a05808ba6147e039cef3f63fa08735f5d')
def setUp(self): dcm_path = path.join(test_dir, 'data', 'dcmstack', '2D_16Echo_qT2', 'TE_20_SlcPos_-33.707626341697.dcm') self.dcm = dicom.read_file(dcm_path) self.stack = dcmstack.DicomStack() self.stack.add_dcm(dcm)
def test_pix_overflow(): ds = make_dicom(pix_val=(2**16 - 1)) stack = dcmstack.DicomStack() stack.add_dcm(ds) data = stack.get_data() eq_(np.max(data), (2**16 - 1)) eq_(data.dtype, np.uint16)
def test_vector_var_over_vol(self): self.stack = dcmstack.DicomStack(vector_order='EchoTime') self.stack.add_dcm(self.inputs[0]) self.stack.add_dcm(self.inputs[1]) self.stack.add_dcm(self.inputs[2]) self.stack.add_dcm(self.inputs[3]) self._chk()
def test_three_dim(self): stack = dcmstack.DicomStack() stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) affine = stack.get_affine() ref = np.load(path.join(self.data_dir, 'single_vol_aff.npy')) ok_(np.allclose(affine, ref))
def test_image_collision(): dcm_path = path.join(test_dir, 'data', 'dcmstack', '2D_16Echo_qT2', 'TE_20_SlcPos_-33.707626341697.dcm') dcm = dicom.read_file(dcm_path) stack = dcmstack.DicomStack('EchoTime') stack.add_dcm(dcm) assert_raises(dcmstack.ImageCollisionError, stack.add_dcm, dcm)
def test_allow_dummy(self): del self.inputs[0].Rows del self.inputs[0].Columns stack = dcmstack.DicomStack(allow_dummies=True) stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) shape = stack.get_shape() eq_(shape, (192, 192, 2))
def test_two_time_vol(self, embed=False): stack = dcmstack.DicomStack(time_order='EchoTime') stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) stack.add_dcm(self.inputs[2]) stack.add_dcm(self.inputs[3]) nii = stack.to_nifti() self._chk(nii, 'two_time_vol')
def test_three_dim(self): stack = dcmstack.DicomStack() stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) data = stack.get_data() eq_(data.shape, stack.get_shape()) eq_(sha256(data).hexdigest(), 'ab5225fdbedceeea3442b2c9387e1abcbf398c71f525e0017251849c3cfbf49c')
def test_four_dim(self): stack = dcmstack.DicomStack(time_order='EchoTime') stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) stack.add_dcm(self.inputs[2]) stack.add_dcm(self.inputs[3]) shape = stack.shape eq_(shape, (192, 192, 2, 2))
def test_five_dim(self): stack = dcmstack.DicomStack(vector_order='EchoTime') stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) stack.add_dcm(self.inputs[2]) stack.add_dcm(self.inputs[3]) shape = stack.get_shape() eq_(shape, (192, 192, 2, 1, 2))
def test_single_slice(self): stack = dcmstack.DicomStack() stack.add_dcm(self.inputs[0]) affine = stack.get_affine() ref = np.load(path.join(self.data_dir, 'single_slice_aff.npy')) print affine print ref ok_(np.allclose(affine, ref))
def test_two_vector_vol(self): stack = dcmstack.DicomStack(vector_order='EchoTime') stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) stack.add_dcm(self.inputs[2]) stack.add_dcm(self.inputs[3]) nii = stack.to_nifti() self._chk(nii, 'two_vector_vol')
def test_allow_dummies(self): del self.inputs[0].Rows del self.inputs[0].Columns stack = dcmstack.DicomStack(allow_dummies=True) stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) nii = stack.to_nifti() data = nii.get_data() ok_(np.all(data[:, :, 0] == np.iinfo(np.int16).max))
def test_fsl_hack(): ds = make_dicom({ 'BitsStored': 14, }, 2**14 - 1) stack = dcmstack.DicomStack() stack.add_dcm(ds) data = stack.get_data() eq_(np.max(data), (2**14 - 1)) eq_(data.dtype, np.int16)
def test_only_dummy(self): self.stack = dcmstack.DicomStack(allow_dummies=True) del self.inputs[0].Rows del self.inputs[0].Columns del self.inputs[1].Rows del self.inputs[1].Columns self.stack.add_dcm(self.inputs[0]) self.stack.add_dcm(self.inputs[1]) self._chk()
def test_three_dim(self): stack = dcmstack.DicomStack() stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) data = stack.get_data() eq_(data.shape, stack.get_shape()) eq_( sha256(data).hexdigest(), 'ec60d148734916bb05aa7d73cc76bd0777560518da86d1ac5aa93c8f151cf73f')
def get_data_from_dicom(alldic, Ei): #Ei = Exam_info.Exam_info() mf = dcmstack.make_key_regex_filter(['nothingtoremove']) pg, dicom_file_size, n_ommited = Ei.get_group_stack_from_dic(alldic) all_stack = [] dicom_ok = True for v in pg.itervalues(): my_stack = dcmstack.DicomStack(meta_filter=mf, time_order='InstanceNumber') n_ommited = 0 n_repeat = 0 for vol in v: #vol[0] champs de pydicom vol[1] ordererd dict try: my_stack.add_dcm(vol[0], meta=vol[1]) except dcmstack.IncongruentImageError: n_ommited += 1 dicom_ok = False except dcmstack.ImageCollisionError: n_repeat += 1 dicom_ok = False except Exception as e: log.info("oups dic %s because expection" % (vol[2])) print e n_ommited += 1 dicom_ok = False # dicom_file_size += os.path.getsize(vol[2]) if n_repeat > 0: log.info("Found %d duplicate dicom file", n_repeat) if n_ommited > 0: log.info("Found %d stack incongruent dicom file", n_ommited) try: all_stack.append( my_stack.to_nifti(voxel_order='LAS', embed_meta=True)) except (dcmstack.InvalidStackError, dcmstack.IncongruentImageError) as detail: log.info("INVALIDE STACK because %s ", detail) dicom_ok = False except Exception: log.info("STACK error") dicom_ok = False alldata = [] for nii in all_stack: data = nii.get_data() alldata.append(data) return alldata, dicom_ok
def test_five_dim(self): stack = dcmstack.DicomStack(vector_order='EchoTime') stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) stack.add_dcm(self.inputs[2]) stack.add_dcm(self.inputs[3]) data = stack.get_data() eq_(data.shape, stack.get_shape()) eq_(sha256(data).hexdigest(), 'bb3639a6ece13dc9a11d65f1b09ab3ccaed63b22dcf0f96fb5d3dd8805cc7b8a')
def test_wrong_guess_first(self): #Test situations where the initial guesses are wrong stack = dcmstack.DicomStack() for key in dcmstack.DicomStack.sort_guesses[:-1]: for in_dcm in self.inputs: setattr(in_dcm, key, 0) for idx, in_dcm in enumerate(self.inputs): setattr(in_dcm, dcmstack.DicomStack.sort_guesses[-1], idx) stack.add_dcm(in_dcm) eq_(stack.get_shape(), (192, 192, 2, 2))
def test_single_guess(self): #Test situations where there is only one possible correct guess for key in dcmstack.DicomStack.sort_guesses: stack = dcmstack.DicomStack() for idx, in_dcm in enumerate(self.inputs): setattr(in_dcm, key, self._get_vr_ord(key, idx)) stack.add_dcm(in_dcm) eq_(stack.get_shape(), (192, 192, 2, 2)) for in_dcm in self.inputs: delattr(in_dcm, key)
def test_allow_dummy(self): del self.inputs[0].Rows del self.inputs[0].Columns stack = dcmstack.DicomStack(allow_dummies=True) stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) data = stack.get_data() eq_(data.shape, stack.get_shape()) ok_(np.all(data[:, :, -1] == np.iinfo(np.int16).max)) eq_(sha256(data).hexdigest(), '7d85fbcb60a5021a45df3975613dcb7ac731830e0a268590cc798dc39897c04b')
def test_allow_dummy(self): del self.inputs[0].Rows del self.inputs[0].Columns stack = dcmstack.DicomStack(allow_dummies=True) stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) data = stack.get_data() eq_(data.shape, stack.get_shape()) eq_( sha256(data).hexdigest(), 'ed14cb8694f1c0d542562fecc6fd71bced3810df4fcb857a091c8e8525fbdda6')
def test_five_dim(self): stack = dcmstack.DicomStack(vector_order='EchoTime') stack.add_dcm(self.inputs[0]) stack.add_dcm(self.inputs[1]) stack.add_dcm(self.inputs[2]) stack.add_dcm(self.inputs[3]) data = stack.get_data() eq_(data.shape, stack.get_shape()) eq_( sha256(data).hexdigest(), 'c14d3a8324bdf4b85be05d765c0864b4e2661d7aa716adaf85a28b4102e1992b')
def _run_interface(self, runtime): src_paths = self._get_filelist(self.inputs.dicom_files) include_regexes = dcmstack.default_key_incl_res if isdefined(self.inputs.include_regexes): include_regexes += self.inputs.include_regexes exclude_regexes = dcmstack.default_key_excl_res if isdefined(self.inputs.exclude_regexes): exclude_regexes += self.inputs.exclude_regexes meta_filter = dcmstack.make_key_regex_filter(exclude_regexes, include_regexes) stack = dcmstack.DicomStack(meta_filter=meta_filter) for src_path in src_paths: src_dcm = dicom.read_file(src_path, force=True) stack.add_dcm(src_dcm) nii = stack.to_nifti(embed_meta=True) nw = NiftiWrapper(nii) self.out_path = \ self._get_out_path(nw.meta_ext.get_class_dict(('global', 'const'))) if not self.inputs.embed_meta: nw.remove_extension() nb.save(nii, self.out_path) return runtime
def test_pix_overflow(): ds = make_dicom(pix_val=(2**16 - 1)) # ds = pydicom.dataset.Dataset() # ds.file_meta = pydicom.dataset.Dataset() # ds.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian # ds.is_little_endian = True # ds.ImagePositionPatient = [0.0, 0.0, 0.0] # ds.ImageOrientationPatient = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0] # ds.PixelSpacing = [1.0, 1.0] # ds.SliceThickness = 1.0 # ds.Rows = 16 # ds.Columns = 16 # ds.BitsAllocated = 16 # ds.BitsStored = 16 # ds.PixelRepresentation = 0 # ds.SamplesPerPixel = 1 # ds.PixelData = (np.ones((16, 16), np.uint16) * (2**16 - 1)).tostring() stack = dcmstack.DicomStack() stack.add_dcm(ds) data = stack.get_data() eq_(np.max(data), (2**16 - 1)) eq_(data.dtype, np.uint16)
def standard_convert(self): """Standard reconstruction, works for most manufacturers and scans.""" log.debug('standard recon') partial_vol_check(self) stack = dcmstack.DicomStack() for dcm in self._dcm_list: stack.add_dcm(dcm, MetaExtractor(dcm)) try: nii_wrp = stack.to_nifti_wrapper() except dcmstack.InvalidStackError as e: raise DicomError( 'cannot reconstruct %s: %s' % (self.filepath, e)) # XXX FAIL! unexpect for recon to fail del self._dcm_list, stack, dcm nii = nii_wrp.nii_img self.data = {'': nii.get_data()} self.qto_xyz = nii.get_affine() del nii_wrp, nii post_convert(self)