def TestStringFilter(filename, verbose=False): r = gdcm.Reader() r.SetFileName(filename) success = r.Read() if (not success): return 1 file = r.GetFile() ds = file.GetDataSet() # Change gdcm struct into something swig can digest: pds = gdcm.PythonDataSet(ds) sf = gdcm.StringFilter() pds.Start() # Make iterator go at beginning dic1 = {} dic2 = {} sf.SetFile(file) # extremely important while (not pds.IsAtEnd()): t = str(pds.GetCurrent().GetTag()) res = sf.ToStringPair(pds.GetCurrent().GetTag()) dic2[t] = res[1] dic1[res[0]] = res[1] pds.Next() #print dic1 #print dic2 try: print "Pixel Representation=", dic2['(0028,0103)'] except KeyError: print "Tag not found in dataset" return 0
def __init__(self, dcm_path): try: self.dcm_path = dcm_path pygdcm.gdcm_Reader = gdcm.ImageReader() pygdcm.gdcm_Reader.SetFileName(self.dcm_path) file = pygdcm.gdcm_Reader.GetFile() self.dataset = file.GetDataSet() self.strFilter = gdcm.StringFilter() self.strFilter.SetFile(pygdcm.gdcm_Reader.GetFile()) self.image_u16 = [] except Exception as e: print(traceback.print_exc()) return
def _read_all_tags(self, filename): r = gdcm.Reader(filename) r.Read() f = r.GetFile() ds = file.GetDataSet() pds = gdcm.PythonDataSet(ds) sf = gdcm.StringFilter() pds.Start() # Make iterator go at begining dic = {} sf.SetFile(f) # extremely important while (not pds.IsAtEnd()): res = sf.ToStringPair(pds.GetCurrent().GetTag()) dic[res[0]] = res[1] pds.Next() return dic
def __init__(self, fname): self.fname = fname self.file_name, self.file_extension = os.path.splitext(fname) reader = gdcm.Reader() reader.SetFileName(fname) if not reader.Read(): raise InvalidDicom("Not a valid DICOM file") self._file = reader.GetFile() self._header = self._file.GetHeader() self._dataset = self._file.GetDataSet() self._str_filter = gdcm.StringFilter() self._str_filter.SetFile(self._file) self._image = None self._anon_obj = None self._errors = None self._warnings = None
def run(self): grouper = self.grouper reader = gdcm.ImageReader() if _has_win32api: try: reader.SetFileName( utils.encode(win32api.GetShortPathName(self.filepath), const.FS_ENCODE)) except TypeError: reader.SetFileName(win32api.GetShortPathName(self.filepath)) else: try: reader.SetFileName(utils.encode(self.filepath, const.FS_ENCODE)) except TypeError: reader.SetFileName(self.filepath) if (reader.Read()): file = reader.GetFile() # Retrieve data set dataSet = file.GetDataSet() # Retrieve header header = file.GetHeader() stf = gdcm.StringFilter() stf.SetFile(file) field_dict = {} data_dict = {} tag = gdcm.Tag(0x0008, 0x0005) ds = reader.GetFile().GetDataSet() if ds.FindDataElement(tag): encoding_value = str( ds.GetDataElement(tag).GetValue()).split('\\')[0] if encoding_value.startswith("Loaded"): encoding = "ISO_IR 100" else: try: encoding = const.DICOM_ENCODING_TO_PYTHON[ encoding_value] except KeyError: encoding = 'ISO_IR 100' else: encoding = "ISO_IR 100" # Iterate through the Header iterator = header.GetDES().begin() while (not iterator.equal(header.GetDES().end())): dataElement = iterator.next() if not dataElement.IsUndefinedLength(): tag = dataElement.GetTag() data = stf.ToStringPair(tag) stag = tag.PrintAsPipeSeparatedString() group = str(tag.GetGroup()) field = str(tag.GetElement()) tag_labels[stag] = data[0] if not group in data_dict.keys(): data_dict[group] = {} if not (utils.VerifyInvalidPListCharacter(data[1])): data_dict[group][field] = utils.decode( data[1], encoding) else: data_dict[group][field] = "Invalid Character" # Iterate through the Data set iterator = dataSet.GetDES().begin() while (not iterator.equal(dataSet.GetDES().end())): dataElement = iterator.next() if not dataElement.IsUndefinedLength(): tag = dataElement.GetTag() # if (tag.GetGroup() == 0x0009 and tag.GetElement() == 0x10e3) \ # or (tag.GetGroup() == 0x0043 and tag.GetElement() == 0x1027): # continue data = stf.ToStringPair(tag) stag = tag.PrintAsPipeSeparatedString() group = str(tag.GetGroup()) field = str(tag.GetElement()) tag_labels[stag] = data[0] if not group in data_dict.keys(): data_dict[group] = {} if not (utils.VerifyInvalidPListCharacter(data[1])): data_dict[group][field] = utils.decode( data[1], encoding, 'replace') else: data_dict[group][field] = "Invalid Character" # -------------- To Create DICOM Thumbnail ----------- try: data = data_dict[str(0x028)][str(0x1050)] level = [float(value) for value in data.split('\\')][0] data = data_dict[str(0x028)][str(0x1051)] window = [float(value) for value in data.split('\\')][0] except (KeyError, ValueError): level = None window = None if _has_win32api: thumbnail_path = imagedata_utils.create_dicom_thumbnails( win32api.GetShortPathName(self.filepath), window, level) else: thumbnail_path = imagedata_utils.create_dicom_thumbnails( self.filepath, window, level) #------ Verify the orientation -------------------------------- img = reader.GetImage() direc_cosines = img.GetDirectionCosines() orientation = gdcm.Orientation() try: _type = orientation.GetType(tuple(direc_cosines)) except TypeError: _type = orientation.GetType(direc_cosines) label = orientation.GetLabel(_type) # ---------- Refactory -------------------------------------- data_dict['invesalius'] = {'orientation_label': label} # ------------------------------------------------------------- dict_file[self.filepath] = data_dict #---------- Verify is DICOMDir ------------------------------- is_dicom_dir = 1 try: if (data_dict[str(0x002)][str(0x002)] != "1.2.840.10008.1.3.10"): #DICOMDIR is_dicom_dir = 0 except (KeyError): is_dicom_dir = 0 if not (is_dicom_dir): parser = dicom.Parser() parser.SetDataImage(dict_file[self.filepath], self.filepath, thumbnail_path) dcm = dicom.Dicom() #self.l.acquire() dcm.SetParser(parser) grouper.AddFile(dcm)
def run(self): grouper = self.grouper reader = gdcm.ImageReader() reader.SetFileName(self.filepath) if (reader.Read()): file = reader.GetFile() # Retrieve data set dataSet = file.GetDataSet() # Retrieve header header = file.GetHeader() stf = gdcm.StringFilter() field_dict = {} data_dict = {} tag = gdcm.Tag(0x0008, 0x0005) ds = reader.GetFile().GetDataSet() if ds.FindDataElement(tag): encoding_value = str( ds.GetDataElement(tag).GetValue()).split('\\')[0] if encoding_value.startswith("Loaded"): encoding = "ISO_IR 100" else: try: encoding = const.DICOM_ENCODING_TO_PYTHON[ encoding_value] except KeyError: encoding = 'ISO_IR 100' else: encoding = "ISO_IR 100" # Iterate through the Header iterator = header.GetDES().begin() while (not iterator.equal(header.GetDES().end())): dataElement = iterator.next() stf.SetFile(file) tag = dataElement.GetTag() data = stf.ToStringPair(tag) stag = tag.PrintAsPipeSeparatedString() group = str(tag.GetGroup()) field = str(tag.GetElement()) tag_labels[stag] = data[0] if not group in data_dict.keys(): data_dict[group] = {} if not (utils.VerifyInvalidPListCharacter(data[1])): data_dict[group][field] = data[1].decode(encoding) else: data_dict[group][field] = "Invalid Character" # Iterate through the Data set iterator = dataSet.GetDES().begin() while (not iterator.equal(dataSet.GetDES().end())): dataElement = iterator.next() stf.SetFile(file) tag = dataElement.GetTag() data = stf.ToStringPair(tag) stag = tag.PrintAsPipeSeparatedString() group = str(tag.GetGroup()) field = str(tag.GetElement()) tag_labels[stag] = data[0] if not group in data_dict.keys(): data_dict[group] = {} if not (utils.VerifyInvalidPListCharacter(data[1])): data_dict[group][field] = data[1].decode( encoding, 'replace') else: data_dict[group][field] = "Invalid Character" # -------------- To Create DICOM Thumbnail ----------- rvtk = vtkgdcm.vtkGDCMImageReader() rvtk.SetFileName(self.filepath) rvtk.Update() try: data = data_dict[str(0x028)][str(0x1050)] level = [float(value) for value in data.split('\\')][0] data = data_dict[str(0x028)][str(0x1051)] window = [float(value) for value in data.split('\\')][0] except (KeyError): level = 300.0 window = 2000.0 colorer = vtk.vtkImageMapToWindowLevelColors() colorer.SetInputConnection(rvtk.GetOutputPort()) colorer.SetWindow(float(window)) colorer.SetLevel(float(level)) colorer.SetOutputFormatToRGB() colorer.Update() resample = vtk.vtkImageResample() resample.SetInputConnection(colorer.GetOutputPort()) resample.SetAxisMagnificationFactor(0, 0.25) resample.SetAxisMagnificationFactor(1, 0.25) resample.SetAxisMagnificationFactor(2, 1) resample.Update() thumbnail_path = tempfile.mktemp() write_png = vtk.vtkPNGWriter() write_png.SetInputConnection(resample.GetOutputPort()) write_png.SetFileName(thumbnail_path) write_png.Write() #------ Verify the orientation -------------------------------- img = reader.GetImage() direc_cosines = img.GetDirectionCosines() orientation = gdcm.Orientation() try: type = orientation.GetType(tuple(direc_cosines)) except TypeError: type = orientation.GetType(direc_cosines) label = orientation.GetLabel(type) # ---------- Refactory -------------------------------------- data_dict['invesalius'] = {'orientation_label': label} # ------------------------------------------------------------- dict_file[self.filepath] = data_dict #---------- Verify is DICOMDir ------------------------------- is_dicom_dir = 1 try: if (data_dict[str(0x002)][str(0x002)] != "1.2.840.10008.1.3.10"): #DICOMDIR is_dicom_dir = 0 except (KeyError): is_dicom_dir = 0 if not (is_dicom_dir): parser = dicom.Parser() parser.SetDataImage(dict_file[self.filepath], self.filepath, thumbnail_path) dcm = dicom.Dicom() #self.l.acquire() dcm.SetParser(parser) grouper.AddFile(dcm)
# If the reader fails to read the file, we should stop ! if not r.Read(): print ("Not a valid DICOM file") # Get the DICOM File structure file = r.GetFile() # Get the DataSet part of the file dataset = file.GetDataSet() # Ok let's print it ! #print dataset # Use StringFilter to print a particular Tag: sf = gdcm.StringFilter() sf.SetFile(r.GetFile()) # Check if Attribute exist #print dataset.FindDataElement(gdcm.Tag(0x0008, 0x2218)) # Let's print it as string pair: #print sf.ToStringPair(gdcm.Tag(0x18, 0x1110))[1] #prints just the value for this dicom element #print sf.ToStringPair(gdcm.Tag(0x28, 0x0030))[1] #this is just a function to test getting the user inputted acc# to query the database. #TODO: This function will be rewrittent to get the dicom header from the database using the #user inputted accession number.