def anonymize(data_dir, save_dir, logger=None, i=None): state = None if i is not None and not i % 10: print('Process: ', i) num = 0 for root, _, files in os.walk(data_dir): for f in files: if os.path.splitext(f)[-1] not in EXTEN: try: src_path = os.path.join(root, f) ds = pydicom.dcmread(src_path) for tag, vr, v in ATTRIBUTE: ds[tag] = pydicom.DataElement(tag, vr, v) save_path = src_path.replace(data_dir, save_dir) # save_path = os.path.join(save_dir, ds.PatientID, ds.StudyDate, ds.StudyInstanceUID, ds.SeriesInstanceUID, str(ds.InstanceNumber)+'.dcm') if not os.path.exists(os.path.dirname(save_path)): os.makedirs(os.path.dirname(save_path)) ds.save_as(save_path) except Exception as e: state = 'PT_DT_0001' if logger is not None: logger.info("\n") logger.info(state + ": " + str(e)) logger.info("Error path: ", os.path.join(root, f)) # else: # print("Error path: ", os.path.join(root, f)) return state
def test_RuleHandler() -> None: ds = pydicom.Dataset() tag = 0x00000001 ds[tag] = pydicom.DataElement(value=b"1", tag=tag, VR="CS") handler = RuleHandler(lambda _: "x") handler(ds, tag) assert ds[tag].value == "x"
def diffcom(file1, file2): """Compare DICOM file1 with DICOM file2. file1 is often the earlier, whereas file2 is the later. """ if not __check_file(file1): return if not __check_file(file2): return ds1 = pydicom.dcmread(file1) ds2 = pydicom.dcmread(file2) it1 = iter(ds1) it2 = iter(ds2) EOD = pydicom.DataElement(0xFFFFFFFF, 'PN', 'Guard') elem1 = next(it1, EOD) elem2 = next(it2, EOD) while elem1 != EOD or elem2 != EOD: if elem1.tag == elem2.tag: __print_elem(elem1, elem2) elem1 = next(it1, EOD) elem2 = next(it2, EOD) while elem1.tag < elem2.tag: __print_elem(elem1) elem1 = next(it1, EOD) while elem1.tag > elem2.tag: __print_elem(element2=elem2) elem2 = next(it2, EOD)
def testRetrieve(self): ds = pydicom.dcmread("tests/data/testDICOM_01.dcm") self.assertEqual(retrieveFromDataset(["Modality"], ds), "MR") self.assertEqual(retrieveFromDataset(["(0008, 0060)"], ds), "MR") self.assertEqual(retrieveFromDataset(["ImageType"], ds), ['ORIGINAL', 'PRIMARY', 'M_FFE', 'M', 'FFE']) self.assertEqual(retrieveFromDataset(["ImageType", "3"], ds), "M") self.assertEqual(retrieveFromDataset(["(0008, 1111)", "0", "(0008, 0005)"], ds), "ISO_IR 100") self.assertIsNone(retrieveFromDataset(["ABC"], ds, fail_on_not_found=False)) self.assertIsNone(retrieveFromDataset(["ABC"], ds, fail_on_not_found=True, fail_on_last_not_found=False)) with self.assertRaises(KeyError): retrieveFromDataset(["ABC"], ds) with self.assertRaises(KeyError): retrieveFromDataset(["(0008, 1111)", "0", "ABC"], ds, fail_on_not_found=True) self.assertIsNone(retrieveFromDataset(["ImageType", "9"], ds, fail_on_not_found=False)) self.assertIsNone(retrieveFromDataset(["ImageType", "9"], ds, fail_on_not_found=True, fail_on_last_not_found=False)) with self.assertRaises(KeyError): retrieveFromDataset(["ImageType", "9"], ds) exp = extractStruct(ds) self.assertEqual(exp["ImageType"], ['ORIGINAL', 'PRIMARY', 'M_FFE', 'M', 'FFE']) self.assertEqual(combineDateTime(ds, "Study"), datetime(2001, 1, 1, 11, 33, 22)) self.assertIsNone(combineDateTime(ds, "Acquisition")) ds.add(pydicom.DataElement("AcquisitionDateTime", "DT", "19920304112233")) self.assertEqual(combineDateTime(ds, "Acquisition"), datetime(1992, 3, 4, 11, 22, 33)) del ds["StudyTime"] self.assertIsNone(combineDateTime(ds, "Study"))
def insertTag(dataset, tag, value, type): if tag in dataset: dataset[tag].value = value else: dataset[tag] = pydicom.DataElement(tag, type, value)
bits = m_.flatten() padded_bits = _sdiv(len(bits), 8) * 8 if len(bits) < padded_bits: bits = np.append( bits, np.zeros((padded_bits - len(bits), ), dtype=np.uint8)) if slice_.is_little_endian: bits = np.reshape(bits, (-1, 8)) bits = np.fliplr(bits) bytes_ = np.packbits(bits) # set new seriesinstanceuid slice_[0x0020, 0x000e] = pydicom.DataElement((0x0020, 0x000e), "UI", uid_gen) slice_[0x0008, 0x0018] = pydicom.DataElement( (0x0008, 0x0018), "UI", pydicom.uid.generate_uid()) # update series description slice_[0x0008, 0x103e].value = str( slice_[0x0008, 0x103e].value) + " (Volumetrie)" # set DICOM elements # TODO check if overlay exists if (0x6000, 0x3000) in slice_: print("Warning: Overwriting existing overlay!") overlay_data = pydicom.DataElement((0x6000, 0x3000), "OW", bytes_.tobytes()) slice_[0x6000, 0x3000] = overlay_data
def process_plan(filename,fig): dataset = pydicom.dcmread(filename) source_dataset=[] xs=[] ys=[] zs=[] ts=[] print(dataset[0x300a, 0x004]) #<-- example of nested tag access print(dataset[0x300a, 0x006]) #<-- example of nested tag access print(dataset[0x300a, 0x007]) #<-- example of nested tag access print(dataset[0x0008, 0x0018]) #<-- example of nested tag access dataset[0x0020,0x0011].value="9" #dataset[0x0020,0x000d].value=str(rand.randint(1,10000)) instance_rand=str(rand.randint(1,10000)) dataset[0x0020,0x000e].value=instance_rand # <-- creating a new random series instance dataset[0x300c,0x0002][0][0x0008,0x1155].value=instance_rand # <-- replacing the reference value new_UID=str(rand.randint(1,10000)) dataset[0x0008, 0x0018].value=new_UID #<-- creating a new random SOP instance UID print('Maximum number of catheters in dataset =',dataset[0x300a, 0x0230][0][0x300a, 0x0280].VM) # prints the number of catheters while True: # example of infinite loops using try and except to catch only numbers line = input('Please enter the catheter number> ') try: # if line == 'done': # break catnum = int(line.lower()) if catnum >= 1 and catnum <= dataset[0x300a, 0x0230][0][0x300a, 0x0280].VM: break else: print('Please select a value between 1 and the max number of catheters:') except: print('Please select a value between 1 and the max number of catheters:') catheter=dataset[0x300a, 0x0230][0][0x300a, 0x0280][catnum-1] tipcat = np.asarray(catheter[0x1001,0x1080][0][0x1001,0x1083].value) # this variable holds the tip of the catheter print('tip catheter=',tipcat) #print('Coordinates of the first point=',catheter[0x300a, 0x02d0][0][0x300a, 0x02d4].value) xoffset=dataset[0x300a, 0x0230][0][0x300a, 0x0280][catnum-1][0x300a, 0x02d0][0][0x300a, 0x02d4].value[0] yoffset=dataset[0x300a, 0x0230][0][0x300a, 0x0280][catnum-1][0x300a, 0x02d0][0][0x300a, 0x02d4].value[1] print('xoffset=',xoffset) print('yoffset=',yoffset) source_dataset=[] xs=[] ys=[] zs=[] ts=[] for pos in dataset[0x300a, 0x0230][0][0x300a, 0x0280][catnum-1][0x300a, 0x02d0]: # print(pos[0x300a, 0x02d4]) # position (x,y,z) # print(pos[0x300a, 0x02d6]) # weight time # print(pos[0x300a, 0x0112]) # control point index # source_dataset.append([ elem[0x300a, 0x0282].value, elem[0x300a, 0x0284].value, elem[0x300a, 0x0286].value, pos[0x300a, 0x02d4].value, pos[0x300a, 0x02d6].value]) x, y, z = pos[0x300a, 0x02d4].value source_dataset.append([catheter[0x300a, 0x0282].value, catheter[0x300a, 0x0284].value, catheter[0x300a, 0x0286].value, pos[0x300a, 0x0112].value, x, y, z, pos[0x300a, 0x02d6].value]) source_dataset = np.asarray(source_dataset) coords=np.transpose(source_dataset[:,4:7]) for i in range(1, source_dataset.shape[0], 2): x = source_dataset[i, 4] y = source_dataset[i, 5] z = source_dataset[i, 6] tw = source_dataset[i, 7] - source_dataset[i - 1, 7] xs.append(x) ys.append(y) zs.append(z) ts.append(tw / 100 * source_dataset[i, 2]) #for matplotlib3d ax.scatter(xs, ys, zs, s=ts, label='Catheter(o)='+str(catnum)) # print(ts) while True: # example of infinite loops using try and except to catch only numbers line = input('Please enter the offset value in the z direction [cm]> ') try: # if line == 'done': # break offset = float(line.lower()) break except: print('Please enter a valid option:') zoffset=(offset - tipcat[2]) #the point offset in the z direction is the value of the offset minus the tip of the catheter location coords_offset=np.zeros_like(coords) coords_offset[0,:]=coords[0,:]-xoffset coords_offset[1,:]=coords[1,:]-yoffset coords_offset[2,:]=coords[2,:]+zoffset # preparing the catheter for rotation tipcat_offset = np.zeros_like(tipcat) tipcat_offset[0] = tipcat[0] - xoffset tipcat_offset[1] = tipcat[1] - yoffset tipcat_offset[2] = tipcat[2] + zoffset print('zoffset=',zoffset) #here we update the catheter values where the bending occurs needle=catheter[0x1001,0x1080] # catheter[0x300a, 0x0291].value='M117X0004-CAT' # changing the type of catheter from virtual # dataset[0x1001, 0x10af][0][0x1001,0x10c2].value=-10 #testing this value # print(catheter[0x300a, 0x0291]) x_dup,y_dup,z_dup=needle[0][0x10011083].value #we extract these coordinates from the tip and create another set located at the point where the catheter bends dup_elem=pydicom.Dataset()#creating a point where the catheter bends dup_elem.add_new(0x10010010,'LO',needle[0][0x1001,0x0010].value) dup_elem.add_new(0x10011081,'SL',needle[0][0x1001,0x1081].value+1) dup_elem.add_new(0x10011082,'SL',0) # dup_elem.add_new(0x10011083,'DS',[x_dup,y_dup,z_dup-zoffset]) dup_elem.add_new(0x10011083,'DS',[x_dup,y_dup,-zoffset]) print('elbow point z value=',-zoffset) seq_needle=pydicom.DataElement(0x10011080,'SQ',[needle[0],dup_elem,needle[1],needle[2],needle[3]]) for needle_point in seq_needle[2:]: needle_point[0x1001,0x1081].value=needle_point[0x1001,0x1081].value+1 # needle_point[0x1001,0x1082].value=needle_point[0x1001,0x1082].value+1 dataset[0x300a, 0x0230][0][0x300a, 0x0280][catnum-1][0x1001,0x1080]=seq_needle # del(dataset[0x300c,0x0080]) #deleting the dose dependency (not necessary in a live catheter from Oncentra) #print('needle=',*dataset[0x300a, 0x0230][0][0x300a, 0x0280][catnum-1][0x1001,0x1080],sep='\n') while True: # example of infinite loops using try and except to catch only numbers line = input('Please enter the theta value [deg]> ') try: # if line == 'done': # break theta = float(line.lower()) break except: print('Please enter a valid option:') r1 = R.from_euler('x', theta, degrees=True) coords_rot1=np.matmul(np.asarray(r1.as_dcm()),coords_offset) tipcatrot1=np.matmul(np.asarray(r1.as_dcm()),tipcat_offset) print('coords_offset=',coords_offset,'r1=',r1) exit(0) while True: # example of infinite loops using try and except to catch only numbers line = input('Please enter the phi value [deg]> ') try: # if line == 'done': # break phi = float(line.lower()) break except: print('Please enter a valid option:') r2 = R.from_euler('z', phi, degrees=True) coords_rot2 = np.matmul(np.asarray(r2.as_dcm()), coords_rot1) tipcatrot2 = np.matmul(np.asarray(r2.as_dcm()), tipcatrot1) coords_f=coords # creating the array from the initial coordinates in order to "bend" the needle from a certain offset for i in range(0,np.shape(coords)[1]): if coords_f[2,i]>tipcat[2]-zoffset: coords_f[0,i]=coords_rot2[0,i]+xoffset coords_f[1,i]=coords_rot2[1,i]+yoffset coords_f[2,i]=coords_rot2[2,i]-zoffset tipcat_f = np.zeros_like(tipcat) tipcat_f[0] = tipcatrot2[0] + xoffset tipcat_f[1] = tipcatrot2[1] + yoffset tipcat_f[2] = tipcatrot2[2] - zoffset catheter[0x1001, 0x1080][0][0x1001, 0x1083].value = [tipcat_f[0], tipcat_f[1], tipcat_f[2]] print('theta=',theta,'phi=',phi) print('post-transformation',coords_f) print(tipcat, tipcatrot1,tipcat_f) # exit(0) # print(ts) ax.scatter(coords_f[0,:], coords_f[1,:], coords_f[2,:], s=ts,label='Catheter(m)='+str(catnum)) ax.legend() k=0 for pos in dataset[0x300a, 0x0230][0][0x300a, 0x0280][catnum-1][0x300a, 0x02d0]: # print(pos[0x300a, 0x02d4]) # position (x,y,z) #print('after transformation=',pos[0x300a, 0x02d6]) # weight time # print(pos[0x300a, 0x0112]) # control point index # source_dataset.append([ elem[0x300a, 0x0282].value, elem[0x300a, 0x0284].value, elem[0x300a, 0x0286].value, pos[0x300a, 0x02d4].value, pos[0x300a, 0x02d6].value]) pos[0x300a, 0x02d4].value=[coords_f[0,k],coords_f[1,k],coords_f[2,k]] k=k+1 while True: # example of infinite loops using try and except to catch only numbers line = input('Please enter a comment for the output file> ') try: # if line == 'done': # break desc = str(line.lower()) break except: print('Please enter a valid option:') date=dt.date.today().strftime('%Y%m%d') now=dt.datetime.now().strftime('%H%M%S') dataset[0x300a, 0x004].value=desc dataset[0x300a, 0x006].value=date dataset[0x300a, 0x007].value=now dirname = os.path.dirname(filename) dataset.save_as(dirname+'/mod-plan.dcm')
def name(self) -> str: try: return pydicom.DataElement(self.tag, "US", None).name except Exception: return "Unnamed"
def clean_meta(dcm): dcm.add(dicom.DataElement((0x0008, 0x0023), 'DA', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0008, 0x0033), 'TM', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0008, 0x1050), 'PN', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0008, 0x1070), 'PN', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0010, 0x0030), 'DA', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0010, 0x1000), 'LO', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0010, 0x1040), 'LO', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0010, 0x2154), 'SH', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0010, 0x2160), 'SH', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0010, 0x2180), 'SH', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0010, 0x21b0), 'LT', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0010, 0x21f0), 'LO', EMPTY_VALUE)) dcm.add(dicom.DataElement((0x0038, 0x0500), 'LO', EMPTY_VALUE)) return dcm