Ejemplo n.º 1
0
def ImageConverter(input_filename,
                   output_filename,
                   processing_log='',
                   overwrite=False):
    # Python 2/3 compatible input
    from six.moves import input

    # Check if output exists and should overwrite
    if os.path.isfile(output_filename) and not overwrite:
        result = input('File \"{}\" already exists. Overwrite? [y/n]: '.format(
            output_filename))
        if result.lower() not in ['y', 'yes']:
            print('Not overwriting. Exiting...')
            os.sys.exit()

    # Read input
    if not os.path.isfile(input_filename):
        os.sys.exit('[ERROR] Cannot find file \"{}\"'.format(input_filename))

    reader = get_vtk_reader(input_filename)
    if reader is None:
        os.sys.exit('[ERROR] Cannot find reader for file \"{}\"'.format(
            input_filename))

    print('Reading input image ' + input_filename)
    reader.SetFileName(input_filename)
    reader.Update()

    # Create writer
    writer = get_vtk_writer(output_filename)
    if writer is None:
        os.sys.exit('[ERROR] Cannot find writer for file \"{}\"'.format(
            output_filename))
    writer.SetInputConnection(reader.GetOutputPort())
    writer.SetFileName(output_filename)

    # Setup processing log
    final_processing_log = ''
    if len(processing_log) > 0 and type(reader) == type(
            vtkbone.vtkboneAIMReader):
        final_processing_log = reader.GetProcessingLog(
        ) + os.linesep + processing_log
    elif type(reader) == type(vtkbone.vtkboneAIMReader):
        final_processing_log = reader.GetProcessingLog()
    elif len(processing_log) > 0:
        final_processing_log = processing_log

    # Handle edge cases for each output file type
    handle_filetype_writing_special_cases(writer,
                                          processing_log=final_processing_log)

    print('Saving image ' + output_filename)
    writer.Update()
Ejemplo n.º 2
0
def write_mask(reader, mask, mask_fn, label, software, version):

    processing_log = (
        reader.GetProcessingLog() + os.linesep +
        f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {label} created by {software}, version {version}."
    )

    writer = get_vtk_writer(mask_fn)
    if writer is None:
        raise RuntimeError(f'Cannot find writer for file {mask_fn}')

    writer.SetFileName(mask_fn)
    writer.SetInputData(mask)
    handle_filetype_writing_special_cases(writer,
                                          processing_log=processing_log)

    writer.Update()
Ejemplo n.º 3
0
def ExtractFields(input_model,
                  output_image,
                  field_name,
                  outside_value=0.0,
                  lower_threshold=0.0,
                  upper_threshold=0.0,
                  output_type='float'):

    # Python 2/3 compatible input
    from six.moves import input

    # Check requested output type
    output_type = output_type.lower()
    if output_type not in EXTRACT_FIELDS_SUPPORTED_TYPES.keys():
        print('Valid output types: {}'.format(', '.join(
            EXTRACT_FIELDS_SUPPORTED_TYPES.keys())))
        os.sys.exit(
            '[ERROR] Requested type {} not supported'.format(output_type))

    # Read input
    if not os.path.isfile(input_model):
        os.sys.exit('[ERROR] Cannot find file \"{}\"'.format(input_model))

    # Test field name
    if field_name not in valid_fields():
        print('Valid field names: {}'.format(valid_fields()))
        os.sys.exit('[ERROR] Please provide a valid field name')

    print('Reading elements into image array')
    image, spacing, origin, n_elements = field_to_image(
        input_model, field_name, outside_value)
    print('  Spacing:            {}'.format(spacing))
    print('  Origin:             {}'.format(origin))
    print('  Dimensions:         {}'.format(image.shape))
    print('  Number of elements: {}'.format(n_elements))
    print('')

    # Convert to VTK
    print('Converting to vtkImageData')
    vtkImage = numpy_to_vtkImageData(image, spacing, origin)
    print('')

    if output_type == 'float':
        print('Not rescaling data')
    else:
        print('Rescaling data into {} dynamic range'.format(output_type))
        # Hack to get data type range
        source = vtk.vtkImageEllipsoidSource()
        source.SetWholeExtent(0, 1, 0, 1, 0, 0)
        source.SetCenter(0, 0, 0)
        source.SetRadius(0, 0, 0)
        source.SetOutputScalarType(EXTRACT_FIELDS_SUPPORTED_TYPES[output_type])
        source.Update()

        # Compute min/max
        if lower_threshold == upper_threshold:
            scalar_range = vtkImage.GetScalarRange()
        else:
            scalar_range = [lower_threshold, upper_threshold]
        dtype_range = [0, source.GetOutput().GetScalarTypeMax()]
        print(' Image range:  {}'.format(vtkImage.GetScalarRange()))
        print(' Input range:  {}'.format(scalar_range))
        print(' Output range: {}'.format(dtype_range))

        # Note the equation for shift/scale:
        #   u = (v + ScalarShift)*ScalarScale
        m = float(dtype_range[1] - dtype_range[0]) / float(scalar_range[1] -
                                                           scalar_range[0])
        b = float(dtype_range[1] - m * scalar_range[1])
        b = b / m

        print(' Shift: {}'.format(b))
        print(' Scale: {}'.format(m))

        scaler = vtk.vtkImageShiftScale()
        scaler.SetInputData(vtkImage)
        scaler.SetShift(b)
        scaler.SetScale(m)
        scaler.ClampOverflowOn()
        scaler.SetOutputScalarType(EXTRACT_FIELDS_SUPPORTED_TYPES[output_type])
        scaler.Update()
        vtkImage = scaler.GetOutput()

        print(' Output image range:  {}'.format(vtkImage.GetScalarRange()))
    print('')

    # Write image
    print('Saving image ' + output_image)
    writer = get_vtk_writer(output_image)
    if writer is None:
        os.sys.exit(
            '[ERROR] Cannot find writer for file \"{}\"'.format(output_image))
    writer.SetInputData(vtkImage)
    writer.SetFileName(output_image)
    writer.Update()
Ejemplo n.º 4
0
 def test_get_tif(self):
     '''tif filetype returns None'''
     expected = type(vtk.vtkTIFFWriter())
     self.assertEqual(type(get_vtk_writer('test.Tif')), expected)
Ejemplo n.º 5
0
 def test_get_jpg(self):
     '''jpg filetype returns None'''
     expected = type(vtk.vtkJPEGWriter())
     self.assertEqual(type(get_vtk_writer('test.jpG')), expected)
Ejemplo n.º 6
0
 def test_get_png(self):
     '''png filetype returns None'''
     expected = type(vtk.vtkPNGWriter())
     self.assertEqual(type(get_vtk_writer('test.pNg')), expected)
Ejemplo n.º 7
0
 def test_get_mnc(self):
     '''mnc filetype returns None'''
     expected = type(vtk.vtkMINCImageWriter())
     self.assertEqual(type(get_vtk_writer('test.mnC')), expected)
Ejemplo n.º 8
0
 def test_get_bmp(self):
     '''bmp filetype returns None'''
     expected = type(vtk.vtkBMPWriter())
     self.assertEqual(type(get_vtk_writer('test.Bmp')), expected)
Ejemplo n.º 9
0
 def test_get_mhd(self):
     '''mhd filetype returns None'''
     expected = type(vtk.vtkMetaImageWriter())
     self.assertEqual(type(get_vtk_writer('test.mHd')), expected)
Ejemplo n.º 10
0
 def test_get_nii_gz(self):
     '''nii.gz filetype returns None'''
     expected = type(vtk.vtkNIFTIImageWriter())
     self.assertEqual(type(get_vtk_writer('test.nIi.gZ')), expected)
Ejemplo n.º 11
0
 def test_get_aim(self):
     '''AIM filetype returns None'''
     expected = type(vtkbone.vtkboneAIMWriter())
     self.assertEqual(type(get_vtk_writer('test25a.AiM')), expected)
Ejemplo n.º 12
0
 def test_get_unknown_filetype(self):
     '''Unknown filetype returns None'''
     expected = None
     self.assertEqual(get_vtk_writer('fake_file.bad.type'), expected)
Ejemplo n.º 13
0
 def test_get_empty(self):
     '''Empty string returns None'''
     expected = None
     self.assertEqual(get_vtk_writer(''), expected)