def dcm2mmap(input_dir, output_mmap): tmp_dcm_files = glob.glob(os.path.join(input_dir, '*')) sorter = gdcm.IPPSorter() sorter.Sort(tmp_dcm_files) dcm_files = sorter.GetFilenames() if not dcm_files: dcm_files = sorted(tmp_dcm_files) r = vtkgdcm.vtkGDCMImageReader() r.SetFileName(dcm_files[0]) r.Update() x, y, z = r.GetOutput().GetDimensions() print x, y, z a_size = len(dcm_files), y, x t = numpy_support.get_numpy_array_type(r.GetDataScalarType()) print t print t, a_size m_dcm = numpy.memmap(output_mmap, mode='w+', dtype='int16', shape=a_size) lp = 0 zspacing = 0 for i, dcm_file in enumerate(dcm_files): r = vtkgdcm.vtkGDCMImageReader() r.SetFileName(dcm_file) r.Update() if lp: zspacing += abs(r.GetImagePositionPatient()[2] - lp) lp = r.GetImagePositionPatient()[2] o = r.GetOutput() d = numpy_support.vtk_to_numpy(o.GetPointData().GetScalars()) m_dcm[i] = d.reshape(y, x) m_dcm.flush() xs, ys, zs = o.GetSpacing() spacing = [xs, ys, zspacing / (len(dcm_files) - 1.0)] if spacing[2] < zs: spacing[2] = zs return m_dcm, spacing
def dcmmf2memmap(dcm_file, orientation): r = vtkgdcm.vtkGDCMImageReader() r.SetFileName(dcm_file) r.Update() temp_file = tempfile.mktemp() o = r.GetOutput() x, y, z = o.GetDimensions() spacing = o.GetSpacing() matrix = numpy.memmap(temp_file, mode='w+', dtype='int16', shape=(z, y, x)) d = numpy_support.vtk_to_numpy(o.GetPointData().GetScalars()) d.shape = z, y, x if orientation == 'CORONAL': matrix.shape = y, z, x for n in xrange(z): matrix[:, n, :] = d[n] elif orientation == 'SAGITTAL': matrix.shape = x, z, y for n in xrange(z): matrix[:, :, n] = d[n] else: matrix[:] = d matrix.flush() scalar_range = matrix.min(), matrix.max() print "ORIENTATION", orientation return matrix, spacing, scalar_range, temp_file
def DICOMReaderToNumpy(directory): file_list = glob.glob(directory + os.sep + '*') file_list = sorted(file_list) ipp = gdcm.IPPSorter() ipp.SetComputeZSpacing(True) ipp.Sort(file_list) file_list = ipp.GetFilenames() array = vtk.vtkStringArray() for x in xrange(len(file_list)): array.InsertValue(x, file_list[x]) read = vtkgdcm.vtkGDCMImageReader() read.SetFileNames(array) read.Update() img = vtk.vtkImageData() img.DeepCopy(read.GetOutput()) img.SetSpacing(1, 1, 1) img.Update() ex = img.GetExtent() image = vtk.util.numpy_support.vtk_to_numpy( img.GetPointData().GetScalars()) image = image.reshape((ex[5] + 1, ex[1] + 1, ex[3] + 1)) return ApplyWindowLevel(image, 2000, 300)
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._reader = vtkgdcm.vtkGDCMImageReader() # NB NB NB: for now we're SWITCHING off the VTK-compatible # Y-flip, until the X-mirror issues can be solved. self._reader.SetFileLowerLeft(1) self._ici = vtk.vtkImageChangeInformation() self._ici.SetInputConnection(0, self._reader.GetOutputPort(0)) # create output MedicalMetaData and populate it with the # necessary bindings. mmd = MedicalMetaData() mmd.medical_image_properties = \ self._reader.GetMedicalImageProperties() mmd.direction_cosines = \ self._reader.GetDirectionCosines() self._output_mmd = mmd module_utils.setup_vtk_object_progress(self, self._reader, 'Reading DICOM data') self._view_frame = None self._file_dialog = None self._config.dicom_filenames = [] # if this is true, module will still try to load set even if # IPP sorting fails by sorting images alphabetically self._config.robust_spacing = False self.sync_module_logic_with_config()
def _handler_file_selected(self, event): # this handler gets called one more time AFTER we've destroyed # the DICOMBrowserViewFrame, so we have to check. if not self._view_frame: return lc = self._view_frame.files_lc idx = lc.GetItemData(event.m_itemIndex) filename = self._item_data_to_file[idx] if filename == self._current_filename: # we're already viewing this filename, don't try to load # again. return # first make sure the image_viewer has a dummy input, so that # any previously connected reader can be deallocated first self._set_image_viewer_dummy_input() # unlike the DICOMReader, we allow the vtkGDCMImageReader to # do its y-flipping here. r = vtkgdcm.vtkGDCMImageReader() r.SetFileName(filename) try: r.Update() except RuntimeWarning, e: # reader generates warning of overlay information can't be # read. We should change the VTK exception support to # just output some text with a warning and not raise an # exception. traceback.print_exc()
def ShowSlice(self, index=0): dicom = self.dicom_list[index] # UPDATE GUI ## Text related to size value = STR_SIZE % (dicom.image.size[0], dicom.image.size[1]) self.text_image_size.SetValue(value) ## Text related to slice position if not (dicom.image.spacing): value1 = '' else: value1 = STR_SPC % (dicom.image.spacing[2]) if dicom.image.orientation_label == 'AXIAL': value2 = STR_LOCAL % (dicom.image.position[2]) elif dicom.image.orientation_label == 'CORONAL': value2 = STR_LOCAL % (dicom.image.position[1]) elif dicom.image.orientation_label == 'SAGITTAL': value2 = STR_LOCAL % (dicom.image.position[0]) else: value2 = '' value = "%s\n%s" % (value1, value2) self.text_image_location.SetValue(value) ## Text related to patient/ acquisiiton data value = STR_PATIENT %(dicom.patient.id,\ dicom.acquisition.protocol_name) self.text_patient.SetValue(value) ## Text related to acquisition date and time value = STR_ACQ % (dicom.acquisition.date, dicom.acquisition.time) self.text_acquisition.SetValue(value) rdicom = vtkgdcm.vtkGDCMImageReader() rdicom.SetFileName(dicom.image.file) rdicom.Update() # ADJUST CONTRAST window_level = dicom.image.level window_width = dicom.image.window colorer = vtk.vtkImageMapToWindowLevelColors() colorer.SetInputConnection(rdicom.GetOutputPort()) colorer.SetWindow(float(window_width)) colorer.SetLevel(float(window_level)) colorer.Update() if self.actor is None: self.actor = vtk.vtkImageActor() self.renderer.AddActor(self.actor) # PLOT IMAGE INTO VIEWER self.actor.SetInputData(colorer.GetOutput()) self.renderer.ResetCamera() self.interactor.Render() # Setting slider position self.slider.SetValue(index)
def ProcessOneFilePublic(filename, outfilename, tmpfile): gdcm.ImageHelper.SetForceRescaleInterceptSlope(True) vtkreader = vtkgdcm.vtkGDCMImageReader() vtkreader.SetFileName(filename) vtkreader.Update() cast = vtk.vtkImageCast() cast.SetInput(vtkreader.GetOutput()) cast.SetOutputScalarTypeToUnsignedShort() # vtkGDCMImageWriter does not support Sequence, so let's write a tmp file first: # Some operation will actually be discarded (we simply need a temp storage) vtkwriter = vtkgdcm.vtkGDCMImageWriter() vtkwriter.SetFileName(tmpfile) vtkwriter.SetMedicalImageProperties(vtkreader.GetMedicalImageProperties()) vtkwriter.SetDirectionCosines(vtkreader.GetDirectionCosines()) print "Format:", vtkreader.GetImageFormat() vtkwriter.SetImageFormat(vtkreader.GetImageFormat()) vtkwriter.SetInput(cast.GetOutput()) #vtkwriter.Update() vtkwriter.Write() # ok now rewrite the exact same file as the original (keep all info) # but use the Pixel Data Element from the written file tmpreader = gdcm.ImageReader() tmpreader.SetFileName(tmpfile) if not tmpreader.Read(): sys.exit(1) reader = gdcm.Reader() reader.SetFileName(filename) if not reader.Read(): sys.exit(1) # Make sure to remove Slope/Rescale to avoid re-execution ds = reader.GetFile().GetDataSet() tags = [ gdcm.Tag(0x0028, 0x1052), gdcm.Tag(0x0028, 0x1053), gdcm.Tag(0x0028, 0x1053), ] for tag in tags: ds.Remove(tag) writer = gdcm.ImageWriter() writer.SetFileName(outfilename) # Pass image from vtk written file writer.SetImage(tmpreader.GetImage()) # pass dataset from initial 'reader' writer.SetFile(reader.GetFile()) if not writer.Write(): sys.exit(1)
def read_dcm_slice_as_np(filename, resolution_percentage=1.0): """ read a dicom slice file and return the slice as numpy ndarray """ dcm_reader = vtkgdcm.vtkGDCMImageReader() dcm_reader.SetFileName(filename) dcm_reader.Update() image = dcm_reader.GetOutput() if resolution_percentage < 1.0: image = ResampleImage2D(image, resolution_percentage=resolution_percentage) dx, dy, dz = image.GetDimensions() im_array = numpy_support.vtk_to_numpy(image.GetPointData().GetScalars()) im_array.shape = dy, dx return im_array
def slotShowDICOMImage(self, item): reader = vtkgdcm.vtkGDCMImageReader() dicom_file = unicode(item.data(QtCore.Qt.UserRole).toString()) reader.SetFileName(dicom_file) reader.Update() imageViewer = vtk.vtkImageViewer() imageViewer.SetInputConnection(reader.GetOutputPort()) self.qvtkWidget.SetRenderWindow(imageViewer.GetRenderWindow()) imageViewer.SetupInteractor(self.qvtkWidget.GetRenderWindow().GetInteractor()) #imageViewer.SetColorLevel(128) #imageViewer.SetColorWindow(256) imageViewer.SetSize(self.qvtkWidget.geometry().width(), self.qvtkWidget.geometry().height())
def dcmmf2mmap(dcm_file, output_mmap): r = vtkgdcm.vtkGDCMImageReader() r.SetFileName(dcm_file) r.Update() o = r.GetOutput() x, y, z = o.GetDimensions() spacing = o.GetSpacing() print o m_dcm = numpy.memmap(output_mmap, mode='w+', dtype='int16', shape=(z, y, x)) d = numpy_support.vtk_to_numpy(o.GetPointData().GetScalars()) d.shape = z, y, x m_dcm[:] = d return m_dcm, spacing
def PrintProgress(object, event): assert event == "ProgressEvent" print("Progress:", object.GetProgress()) if __name__ == "__main__": try: filename = os.sys.argv[1] except: # failure print("Need a filename") sys.exit(1) # setup reader r = vtkgdcm.vtkGDCMImageReader() r.SetFileName(filename) r.AddObserver("ProgressEvent", PrintProgress) r.Update() print(r.GetOutput()) # Write output writer = vtkgdcm.vtkGDCMImageWriter() writer.SetInput(r.GetOutput()) writer.SetMedicalImageProperties(r.GetMedicalImageProperties()) writer.SetFileName("TestvtkGDCMImageWriterPython.dcm") writer.Write() # Test succeed ? #sys.exit(sucess != 1)
def dcm2memmap(files, slice_size, orientation, resolution_percentage): """ From a list of dicom files it creates memmap file in the temp folder and returns it and its related filename. """ message = _("Generating multiplanar visualization...") update_progress = vtk_utils.ShowProgress(len(files) - 1, dialog_type="ProgressDialog") temp_file = tempfile.mktemp() if orientation == 'SAGITTAL': if resolution_percentage == 1.0: shape = slice_size[0], slice_size[1], len(files) else: shape = math.ceil(slice_size[0]*resolution_percentage),\ math.ceil(slice_size[1]*resolution_percentage), len(files) elif orientation == 'CORONAL': if resolution_percentage == 1.0: shape = slice_size[1], len(files), slice_size[0] else: shape = math.ceil(slice_size[1]*resolution_percentage), len(files),\ math.ceil(slice_size[0]*resolution_percentage) else: if resolution_percentage == 1.0: shape = len(files), slice_size[1], slice_size[0] else: shape = len(files), math.ceil(slice_size[1]*resolution_percentage),\ math.ceil(slice_size[0]*resolution_percentage) matrix = numpy.memmap(temp_file, mode='w+', dtype='int16', shape=shape) dcm_reader = vtkgdcm.vtkGDCMImageReader() cont = 0 max_scalar = None min_scalar = None for n, f in enumerate(files): dcm_reader.SetFileName(f) dcm_reader.Update() image = dcm_reader.GetOutput() if resolution_percentage != 1.0: image_resized = ResampleImage2D(image, px=None, py=None,\ resolution_percentage = resolution_percentage, update_progress = None) image = image_resized min_aux, max_aux = image.GetScalarRange() if min_scalar is None or min_aux < min_scalar: min_scalar = min_aux if max_scalar is None or max_aux > max_scalar: max_scalar = max_aux array = numpy_support.vtk_to_numpy(image.GetPointData().GetScalars()) if orientation == 'CORONAL': array.shape = matrix.shape[0], matrix.shape[2] matrix[:, n, :] = array elif orientation == 'SAGITTAL': array.shape = matrix.shape[0], matrix.shape[1] # TODO: Verify if it's necessary to add the slices swapped only in # sagittal rmi or only in # Rasiane's case or is necessary in all # sagittal cases. matrix[:, :, n] = array else: array.shape = matrix.shape[1], matrix.shape[2] matrix[n] = array update_progress(cont, message) cont += 1 matrix.flush() scalar_range = min_scalar, max_scalar return matrix, scalar_range, temp_file
def CreateImageData(self, filelist, zspacing, size, bits): message = _("Generating multiplanar visualization...") if not const.VTK_WARNING: log_path = os.path.join(const.LOG_FOLDER, 'vtkoutput.txt') fow = vtk.vtkFileOutputWindow() fow.SetFileName(log_path) ow = vtk.vtkOutputWindow() ow.SetInstance(fow) x, y = size px, py = utils.predict_memory(len(filelist), x, y, bits) utils.debug("Image Resized to >>> %f x %f" % (px, py)) if (x == px) and (y == py): const.REDUCE_IMAGEDATA_QUALITY = 0 else: const.REDUCE_IMAGEDATA_QUALITY = 1 if not (const.REDUCE_IMAGEDATA_QUALITY): update_progress = vtk_utils.ShowProgress( 1, dialog_type="ProgressDialog") array = vtk.vtkStringArray() for x in xrange(len(filelist)): if not self.running: return False array.InsertValue(x, filelist[x]) if not self.running: return False reader = vtkgdcm.vtkGDCMImageReader() reader.SetFileNames(array) reader.AddObserver( "ProgressEvent", lambda obj, evt: update_progress(reader, message)) reader.Update() if not self.running: reader.AbortExecuteOn() return False # The zpacing is a DicomGroup property, so we need to set it imagedata = vtk.vtkImageData() imagedata.DeepCopy(reader.GetOutput()) spacing = imagedata.GetSpacing() imagedata.SetSpacing(spacing[0], spacing[1], zspacing) else: update_progress = vtk_utils.ShowProgress( 2 * len(filelist), dialog_type="ProgressDialog") # Reformat each slice and future append them appender = vtk.vtkImageAppend() appender.SetAppendAxis(2) #Define Stack in Z # Reformat each slice for x in xrange(len(filelist)): # TODO: We need to check this automatically according # to each computer's architecture # If the resolution of the matrix is too large if not self.running: return False reader = vtkgdcm.vtkGDCMImageReader() reader.SetFileName(filelist[x]) reader.AddObserver( "ProgressEvent", lambda obj, evt: update_progress(reader, message)) reader.Update() #Resample image in x,y dimension slice_imagedata = ResampleImage2D(reader.GetOutput(), px, py, update_progress) #Stack images in Z axes appender.AddInput(slice_imagedata) #appender.AddObserver("ProgressEvent", lambda obj,evt:update_progress(appender)) appender.Update() # The zpacing is a DicomGroup property, so we need to set it if not self.running: return False imagedata = vtk.vtkImageData() imagedata.DeepCopy(appender.GetOutput()) spacing = imagedata.GetSpacing() imagedata.SetSpacing(spacing[0], spacing[1], zspacing) imagedata.AddObserver( "ProgressEvent", lambda obj, evt: update_progress(imagedata, message)) imagedata.Update() return imagedata
def create_dicom_thumbnails(filename, window=None, level=None): rvtk = vtkgdcm.vtkGDCMImageReader() rvtk.SetFileName(filename) rvtk.Update() img = rvtk.GetOutput() if window is None or level is None: _min, _max = img.GetScalarRange() window = _max - _min level = _min + window / 2 dx, dy, dz = img.GetDimensions() if dz > 1: thumbnail_paths = [] for i in xrange(dz): img_slice = ExtractVOI(img, 0, dx-1, 0, dy-1, i, i+1) colorer = vtk.vtkImageMapToWindowLevelColors() colorer.SetInputData(img_slice) colorer.SetWindow(window) colorer.SetLevel(level) colorer.SetOutputFormatToRGB() colorer.Update() resample = vtk.vtkImageResample() resample.SetInputData(colorer.GetOutput()) 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.SetInputData(resample.GetOutput()) write_png.SetFileName(thumbnail_path) write_png.Write() thumbnail_paths.append(thumbnail_path) return thumbnail_paths else: colorer = vtk.vtkImageMapToWindowLevelColors() colorer.SetInputData(img) colorer.SetWindow(window) colorer.SetLevel(level) colorer.SetOutputFormatToRGB() colorer.Update() resample = vtk.vtkImageResample() resample.SetInputData(colorer.GetOutput()) 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.SetInputData(resample.GetOutput()) write_png.SetFileName(thumbnail_path) write_png.Write() return thumbnail_path
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)
def ProcessOneFilePrivate(filename, outfilename, tmpfile): vtkreader = vtkgdcm.vtkGDCMImageReader() vtkreader.SetFileName(filename) vtkreader.Update() # (2005,1409) DS 4 0.0 # (2005,140a) DS 16 1.52283272283272 # (2005,0014) LO 26 Philips MR Imaging DD 005 tag1 = gdcm.PrivateTag(0x2005, 0x09, "Philips MR Imaging DD 005") tag2 = gdcm.PrivateTag(0x2005, 0x0a, "Philips MR Imaging DD 005") # Need to access some private tags, reread the file (for now): reader = gdcm.Reader() reader.SetFileName(filename) if not reader.Read(): sys.exit(1) ds = reader.GetFile().GetDataSet() el1 = ds.GetDataElement(tag1) el2 = ds.GetDataElement(tag2) #pf = gdcm.PythonFilter() #pf.SetFile( reader.GetFile() ) #print el1.GetTag() print el1.GetByteValue() v1 = eval(el1.GetByteValue().GetBuffer()) print el2.GetByteValue() v2 = eval(el2.GetByteValue().GetBuffer()) print v1 shift = v1 print v2 scale = v2 ss = vtk.vtkImageShiftScale() ss.SetInput(vtkreader.GetOutput()) # because VTK image shift / scale convention is inverted from DICOM make sure shift is 0 assert shift == 0 ss.SetShift(shift) ss.SetScale(scale) ss.SetOutputScalarTypeToUnsignedShort() ss.Update() # vtkGDCMImageWriter does not support Sequence, so let's write a tmp file first: # Some operation will actually be discarded (we simply need a temp storage) vtkwriter = vtkgdcm.vtkGDCMImageWriter() vtkwriter.SetFileName(tmpfile) vtkwriter.SetMedicalImageProperties(vtkreader.GetMedicalImageProperties()) vtkwriter.SetDirectionCosines(vtkreader.GetDirectionCosines()) vtkwriter.SetImageFormat(reader.GetImageFormat()) # do not pass shift/scale again vtkwriter.SetInput(ss.GetOutput()) #vtkwriter.Update() vtkwriter.Write() # ok now rewrite the exact same file as the original (keep all info) # but use the Pixel Data Element from the written file tmpreader = gdcm.ImageReader() tmpreader.SetFileName(tmpfile) if not tmpreader.Read(): sys.exit(1) writer = gdcm.ImageWriter() writer.SetFileName(outfilename) # Pass image from vtk written file writer.SetImage(tmpreader.GetImage()) # pass dataset from initial 'reader' writer.SetFile(reader.GetFile()) if not writer.Write(): sys.exit(1)