def test_dicom_class_validate(self): mu = mudicom.load(self.fnames[0]) dcm = mu.validate() self.assertEqual(len(dcm['errors']), 6) self.assertEqual(len(dcm['warnings']), 18) mu = mudicom.load(self.fnames[1]) dcm = mu.validate() self.assertEqual(len(dcm['errors']), 7) self.assertEqual(len(dcm['warnings']), 18)
def test_get_numpy(self): for fname in self.fnames: mu = mudicom.load(fname) img = mu.image gnp = img.numpy self.assertIsInstance(gnp, numpy.ndarray) self.assertEqual(gnp.dtype, numpy.float)
def test_get_element(self): for fname in self.fnames: mu = mudicom.load(fname) #reader = mu.read() self.assertIsInstance(mu.find(0x004, 0x1220), list) self.assertIsInstance(mu.find(name="Modality"), list) self.assertIsInstance(mu.find(VR="PN"), list)
def test_walk_dataset(self): for fname in self.fnames: mu = mudicom.load(fname) #reader = mu.read() tags = list(mu.walk(lambda ds: ds.GetTag())) self.assertIsInstance(tags, list) self.assertIsNot(len(tags), 0) for tag in tags: self.assertIsInstance(tag, gdcm.Tag) tags = list(mu.walk(lambda ds: None)) self.assertIsInstance(tags, list) for tag in tags: self.assertEqual(tag, None) tags = list(mu.walk(lambda ds: False)) self.assertIsInstance(tags, list) for tag in tags: self.assertFalse(tag) tags = list(mu.walk(lambda ds: True)) self.assertIsInstance(tags, list) for tag in tags: self.assertTrue(tag)
def dcm2thumbnail(source_path, target_path, resize_row=128, resize_col=128): # define output dict_return = {} dict_return['status'] = 1 dict_return['paths'] = target_path filename = source_path.split(os.path.sep)[-1] if filename.split('.')[-1] == 'dcm': filename = filename[0:len(filename) - 4] if target_path[-1] != os.path.sep: target_path += os.path.sep # get usefull dicom information try: dcm_head = dicom.read_file(source_path) except IOError: dict_return['status'] = 0 print('read dicom error') return dict_return rescale_intercept = dcm_head.RescaleIntercept rescale_slope = dcm_head.RescaleSlope # get original pixel try: mud = mudicom.load(source_path) except mudicom.exceptions.InvalidDicom: dict_return['status'] = 0 print('read mudicom error') return dict_return pixel_ori = (mud.image).numpy pixel_ori = pixel_ori.astype(np.int16) # pixel to HU value pixel_hu = copy.deepcopy(pixel_ori) pixel_hu = (rescale_slope * pixel_hu.astype(np.float64)).astype(np.int16) pixel_hu += np.int16(rescale_intercept) pixel_hu = np.array(pixel_hu, dtype=np.int16) # adjust window default_img = adjust_window(pixel_hu, *(40, 400)) default_img = scipy.misc.imresize(default_img, (resize_row, resize_col), 'nearest') # return status try: scipy.misc.imsave(target_path + filename + '.jpg', default_img) except IOError: dict_return['status'] = 0 return dict_return dict_return['paths'] = target_path + filename + '.jpg' return dict_return
def test_get_dataset(self): for fname in self.fnames: mu = mudicom.load(fname) ds = mu.read() self.assertIsInstance(ds, list) self.assertIsNot(len(ds), 0) for element in ds: self.assertTrue(hasattr(element, "name")) self.assertTrue(hasattr(element, "value")) self.assertTrue(hasattr(element, "VR")) self.assertTrue(hasattr(element, "VL")) self.assertTrue(hasattr(element, "tag")) self.assertTrue("group" in element.tag) self.assertTrue("element" in element.tag) self.assertTrue("str" in element.tag)
def GetPixelByTransferSyntax(self): if self.ts == uid.ImplicitVRLittleEndian or self.ts == uid.JPEGLossless: self.ds.decompress() self.pixel = self.ds.pixel_array elif self.ts == uid.ExplicitVRLittleEndian or self.ts == uid.JPEG2000Lossy: import mudicom mu = mudicom.load(self.fPath) # returns array of data elements as dicts mu.read() # creates image object img = mu.image # before v0.1.0 this was mu.image() # returns numpy array self.pixel = img.numpy # before v0.1.0 this was mu.numpy()fileFolder else: print self.ts + " can not support Transfer Syntax" return return self.pixel
q[1] = max(q[1],1) tf=[[0,0,0,0,0],[q[0],0,0,0,0],[q[1],1,1,1,0.5],[data.max(),1,1,1,1]] actor_list = volumeRender(data, tf=tf, spacing=img.GetSpacing()) vtk_basic(actor_list) 下面一个不错的软件: https://github.com/bastula/dicompyler 还有一个python的库mudicom,https://github.com/neurosnap/mudicom [python] view plain copy import mudicom mu = mudicom.load("mudicom/tests/dicoms/ex1.dcm") # returns array of data elements as dicts mu.read() # returns dict of errors and warnings for DICOM mu.validate() # basic anonymization mu.anonymize() # save anonymization mu.save_as("dicom.dcm") # creates image object img = mu.image # before v0.1.0 this was mu.image() # returns numpy array
# import cv2 import numpy as np from matplotlib import pyplot as plt # from PIL import Image from skimage.color import rgb2gray from skimage.filters import threshold_mean from skimage import util from skimage.filters import median from skimage.morphology import disk, skeletonize, binary_dilation, binary_erosion, binary_closing # from skimage.exposure import equalize_adapthist # ds = dicom.read_file("2d_angiogram_2.dcm") img_id = 1 mu = mudicom.load("2d_angiogram_" + str(img_id) + ".dcm") mu_out = mu.image pixel_array = mu_out.numpy # with open("pixel_array", "w") as f: # np.save(f, pixel_array) # exit() i = 1 # fig2, ax = plt.subplots(2, 2, figsize=(10, 8)) fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) fig.set_size_inches(5.12, 5.12) ax.set_axis_off()
if event.key == 'j': previous_slice(ax) elif event.key == 'k': next_slice(ax) fig.canvas.draw() def previous_slice(ax): volume = ax.volume ax.index = (ax.index - 1) % volume.shape[0] # wrap around using % ax.images[0].set_array(volume[ax.index]) def next_slice(ax): volume = ax.volume ax.index = (ax.index + 1) % volume.shape[0] ax.images[0].set_array(volume[ax.index]) fpath = "/home/j_69/Fiducial Localization - MRI Scans/pvc/Sequential Scan/DICOM/PA1/ST1/SE2" ## edit this accordingly slices = 176 ## edit this accordingly mu = [] arry = [] for i in range(1, slices): mu.append(dicom.load(fpath + "/IM" + str(i))) arry.append(mu[i - 1].image.numpy) multi_slice_viewer(np.array(arry)) plt.show()
view_pointcloud(surfaceVoxels_ref, color='y') plt.show() ##multi_slice_viewer(voxel_ndarray_ref) ##plt.show() ### Using Rawfloating image, as patient data missing for this view directory_flo1 = "/home/j_69/Fiducial Localization - MRI Scans/glass/Glass Scan Coronal 0.9 mm/DICOM/PA1/ST1/SE2" ## edit this accordingly slices = 256 ## edit this accordingly mu = [] arry = [] for i in range(1, slices): mu.append(mudicom.load(directory_flo1 + "/IM" + str(i))) arry.append(mu[i - 1].image.numpy) voxel_ndarray_flo1 = np.array(arry) surfaceVoxels_flo1 = getSurfaceVoxels(voxel_ndarray_flo1) print surfaceVoxels_flo1 view_pointcloud(surfaceVoxels_ref, color='b') plt.show() print("Applying ICP...") ijkmat = icp(surfaceVoxels_ref, surfaceVoxels_flo1, max_iterations=40) print(ijkmat) """ voxel_ndarray_flo1 = snd.rotate(voxel_ndarray_ref,15)
def test_animation_numpy_shape(self): mu = mudicom.load(self.fnames[2]) image = mu.image self.assertEqual(len(image.numpy.shape), 3) self.assertEqual(image.numpy.shape[0], 76)
def _generate_data_elements(self, filename): mu = mudicom.load(uploaded_dicoms.path(filename)) return [DicomDataElement(e) for e in mu.find()]