Image::Pointer
VolumeVisualizationImagePreprocessor::Process(
  Image::Pointer m_originalCT, Image::Pointer m_originalLiverMask)
{
  VVP_INFO << "Processing...";

  // converting mitk image -> itk image
  CTImage::Pointer CTImageWork = CTImage::New();
  CastToItkImage( m_originalCT, CTImageWork );

  // converting mitk image -> itk image
  BinImage::Pointer BinImageMask = BinImage::New();
  CastToItkImage( m_originalLiverMask, BinImageMask );
  
  DetermineBoundingBox( BinImageMask );
  
  if( m_MaxX < m_MinX
   || m_MaxY < m_MinY
   || m_MaxZ < m_MinZ )
    return 0;
  
  CTImageWork = Gaussian(Crop( CTImageWork ));
  BinImageMask = Crop( BinImageMask );

  CTImage::Pointer itkResult =Composite(CTImageWork,BinImageMask,Dilate(BinImageMask),Erode(BinImageMask));

  mitk::Image::Pointer mitkResult= mitk::Image::New();
               mitk::CastToMitkImage( itkResult, mitkResult ); //TODO here we can perhaps save memory

  VVP_INFO << "Finished...";

  return mitkResult;
}
Exemplo n.º 2
0
void mitk::FastMarchingTool::ConfirmSegmentation()
{
  // combine preview image with current working segmentation
  if (dynamic_cast<mitk::Image*>(m_ResultImageNode->GetData()))
  {
    //logical or combination of preview and segmentation slice
    OutputImageType::Pointer workingImageSliceInITK = OutputImageType::New();

    mitk::Image::Pointer workingImageSlice;
    mitk::Image::Pointer workingImage = dynamic_cast<mitk::Image*>(this->m_ToolManager->GetWorkingData(0)->GetData());
    if(workingImage->GetTimeGeometry()->CountTimeSteps() > 1)
    {
      mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
      timeSelector->SetInput( workingImage );
      timeSelector->SetTimeNr( m_CurrentTimeStep );
      timeSelector->UpdateLargestPossibleRegion();
      // todo: make GetAffectedWorkingSlice dependant of current time step
      workingImageSlice = GetAffectedWorkingSlice( m_PositionEvent );
      CastToItkImage( workingImageSlice, workingImageSliceInITK );
    }
    else
    {
      workingImageSlice = GetAffectedWorkingSlice( m_PositionEvent );
      CastToItkImage( workingImageSlice, workingImageSliceInITK );
    }

    typedef itk::OrImageFilter<OutputImageType, OutputImageType> OrImageFilterType;
    OrImageFilterType::Pointer orFilter = OrImageFilterType::New();

    orFilter->SetInput(0, m_ThresholdFilter->GetOutput());
    orFilter->SetInput(1, workingImageSliceInITK);
    orFilter->Update();

    mitk::Image::Pointer segmentationResult = mitk::Image::New();

    mitk::CastToMitkImage(orFilter->GetOutput(), segmentationResult);
    segmentationResult->GetGeometry()->SetOrigin(workingImageSlice->GetGeometry()->GetOrigin());
    segmentationResult->GetGeometry()->SetIndexToWorldTransform(workingImageSlice->GetGeometry()->GetIndexToWorldTransform());

    //write to segmentation volume and hide preview image
    // again, current time step is not considered
    this->WriteBackSegmentationResult(m_PositionEvent, segmentationResult );
    this->m_ResultImageNode->SetVisibility(false);

    this->ClearSeeds();
  }

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  m_ToolManager->ActivateTool(-1);
}
  void GenerateData_3DImage_CompareToReference()
  {
    int upperThr = 255;
    int lowerThr = 60;

    int outsideVal = 0;
    int insideVal = 100;

    us::ServiceReference<OclResourceService> ref = GetModuleContext()->GetServiceReference<OclResourceService>();
    OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
    resources->GetContext(); //todo why do i need to call this before GetMaximumImageSize()?
    if(resources->GetMaximumImageSize(2, CL_MEM_OBJECT_IMAGE3D) == 0)
    {
      //GPU device does not support 3D images. Skip this test.
      MITK_INFO << "Skipping test.";
      return;
    }

    try{

      m_oclBinaryFilter->SetInput( m_Random3DImage );
      m_oclBinaryFilter->SetUpperThreshold( upperThr );
      m_oclBinaryFilter->SetLowerThreshold( lowerThr );
      m_oclBinaryFilter->SetOutsideValue( outsideVal );
      m_oclBinaryFilter->SetInsideValue( insideVal );
      m_oclBinaryFilter->Update();

      mitk::Image::Pointer outputImage = mitk::Image::New();
      outputImage = m_oclBinaryFilter->GetOutput();

      // reference computation
      //This is not optimal here, but since we use a random image
      //we cannot know the reference image at this point.
      typedef itk::Image< unsigned char, 3> ImageType;
      typedef itk::BinaryThresholdImageFilter< ImageType, ImageType > ThresholdFilterType;

      ImageType::Pointer itkInputImage = ImageType::New();
      CastToItkImage( m_Random3DImage, itkInputImage );

      ThresholdFilterType::Pointer refThrFilter = ThresholdFilterType::New();
      refThrFilter->SetInput( itkInputImage );
      refThrFilter->SetLowerThreshold( lowerThr );
      refThrFilter->SetUpperThreshold( upperThr );
      refThrFilter->SetOutsideValue( outsideVal );
      refThrFilter->SetInsideValue( insideVal );
      refThrFilter->Update();
      mitk::Image::Pointer referenceImage = mitk::Image::New();
      mitk::CastToMitkImage(refThrFilter->GetOutput(), referenceImage);

      MITK_ASSERT_EQUAL( referenceImage, outputImage,
                         "OclBinaryThresholdFilter should be equal to regular itkBinaryThresholdImageFilter.");
    }
    catch(mitk::Exception &e)
    {
      std::string errorMessage = "Caught unexpected exception ";
      errorMessage.append(e.what());
      CPPUNIT_FAIL(errorMessage.c_str());
    }

  }
Exemplo n.º 4
0
void mitk::ContourUtils::ItkCopyFilledContourToSlice( itk::Image<TPixel,VImageDimension>* originalSlice, const Image* filledContourSlice, int overwritevalue )
{
  typedef itk::Image<TPixel,VImageDimension> SliceType;

  typename SliceType::Pointer filledContourSliceITK;
  CastToItkImage( filledContourSlice, filledContourSliceITK );

  // now the original slice and the ipSegmentation-painted slice are in the same format, and we can just copy all pixels that are non-zero
  typedef itk::ImageRegionIterator< SliceType >       OutputIteratorType;
  typedef itk::ImageRegionConstIterator< SliceType >   InputIteratorType;

  InputIteratorType inputIterator( filledContourSliceITK, filledContourSliceITK->GetLargestPossibleRegion() );
  OutputIteratorType outputIterator( originalSlice, originalSlice->GetLargestPossibleRegion() );

  outputIterator.GoToBegin();
  inputIterator.GoToBegin();

  while ( !outputIterator.IsAtEnd() )
  {
    if ( inputIterator.Get() != 0 )
    {
      outputIterator.Set( overwritevalue );
    }

    ++outputIterator;
    ++inputIterator;
  }
}
Exemplo n.º 5
0
void mitk::TbssImage::SetDisplayIndexForRendering(int displayIndex)
{
  MITK_INFO << "displayindex: " << displayIndex;
  int index = displayIndex;
  int vecLength = m_Image->GetVectorLength();
  index = index > vecLength-1 ? vecLength-1 : index;
  if( m_DisplayIndex != index )
  {
    typedef itk::Image<float,3> ImgType;
    ImgType::Pointer img = ImgType::New();
    CastToItkImage(this, img);

    itk::ImageRegionIterator<ImgType> itw (img, img->GetLargestPossibleRegion() );
    itw.GoToBegin();

    itk::ImageRegionConstIterator<ImageType> itr (m_Image, m_Image->GetLargestPossibleRegion() );
    itr.GoToBegin();

    while(!itr.IsAtEnd())
    {
      itw.Set(itr.Get().GetElement(index));
      ++itr;
      ++itw;
    }
  }

  m_DisplayIndex = index;
}
void mitk::CorrectorAlgorithm::GenerateData()
{
  Image::Pointer inputImage = const_cast<Image*>(ImageToImageFilter::GetInput(0));

  if (inputImage.IsNull() || inputImage->GetDimension() != 2)
  {
    itkExceptionMacro("CorrectorAlgorithm needs a 2D image as input.");
  }

  if (m_Contour.IsNull())
  {
    itkExceptionMacro("CorrectorAlgorithm needs a Contour object as input.");
  }

  // copy the input (since m_WorkingImage will be changed later)
  m_WorkingImage = inputImage;

  TimeGeometry::Pointer originalGeometry = NULL;

  if (inputImage->GetTimeGeometry() )
  {
    originalGeometry = inputImage->GetTimeGeometry()->Clone();
    m_WorkingImage->SetTimeGeometry( originalGeometry );
  }
  else
  {
    itkExceptionMacro("Original image does not have a 'Time sliced geometry'! Cannot copy.");
  }

  Image::Pointer temporarySlice;
  // Convert to ipMITKSegmentationTYPE (because TobiasHeimannCorrectionAlgorithm relys on that data type)
  {
    itk::Image< ipMITKSegmentationTYPE, 2 >::Pointer correctPixelTypeImage;
    CastToItkImage( m_WorkingImage, correctPixelTypeImage );
    assert (correctPixelTypeImage.IsNotNull() );

    // possible bug in CastToItkImage ?
    // direction maxtrix is wrong/broken/not working after CastToItkImage, leading to a failed assertion in
    // mitk/Core/DataStructures/mitkSlicedGeometry3D.cpp, 479:
    // virtual void mitk::SlicedGeometry3D::SetSpacing(const mitk::Vector3D&): Assertion `aSpacing[0]>0 && aSpacing[1]>0 && aSpacing[2]>0' failed
    // solution here: we overwrite it with an unity matrix
    itk::Image< ipMITKSegmentationTYPE, 2 >::DirectionType imageDirection;
    imageDirection.SetIdentity();
    //correctPixelTypeImage->SetDirection(imageDirection);

    temporarySlice = this->GetOutput();
    //  temporarySlice = ImportItkImage( correctPixelTypeImage );
    m_FillColor = 1;
    m_EraseColor = 0;
    ImprovedHeimannCorrectionAlgorithm(correctPixelTypeImage);
    CastToMitkImage( correctPixelTypeImage, temporarySlice );
  }
  temporarySlice->SetTimeGeometry(originalGeometry);
}
Exemplo n.º 7
0
void mitk::CollectionGrayOpening::PerformGrayOpening(mitk::DataCollection *dataCollection,
                                                     std::string name,
                                                     std::string suffix)
{
  for (size_t patient = 0; patient < dataCollection->Size(); ++patient)
  {
    DataCollection *dataPatient = dynamic_cast<DataCollection *>(dataCollection->GetData(patient).GetPointer());
    if (dataPatient == nullptr)
      MITK_ERROR << "PerformGrayOpening - Structure of DataCollection is invalid at patient level. Data inconsistent!";

    if (dataPatient->Size() == 0)
      MITK_ERROR << "Empty Patient Collective. Probably Fatal.";

    for (size_t timeStep = 0; timeStep < dataPatient->Size(); ++timeStep)
    {
      DataCollection *dataTimeStep = dynamic_cast<DataCollection *>(dataPatient->GetData(timeStep).GetPointer());
      if (dataTimeStep == nullptr)
        MITK_ERROR
          << "DilateBinaryByName- Structure of DataCollection is invalid at time step level. Data inconsistent!";

      // BinaryImage::Pointer itkImage = BinaryImage::New();
      ImageType::Pointer itkImage = ImageType::New();
      Image::Pointer tmp = dataTimeStep->GetMitkImage(name).GetPointer();
      if (tmp.IsNull())
        MITK_ERROR << "null";
      CastToItkImage(tmp, itkImage);
      if (itkImage.IsNull())
        MITK_ERROR << "Image " << name << " does not exist. Fatal.";

      typedef itk::FlatStructuringElement<3> StructuringElementType;
      StructuringElementType::RadiusType elementRadius;
      elementRadius.Fill(1);
      elementRadius[2] = 0;
      StructuringElementType structuringElement = StructuringElementType::Box(elementRadius);

      typedef itk::GrayscaleMorphologicalOpeningImageFilter<ImageType, ImageType, StructuringElementType>
        DilateImageFilterType;

      DilateImageFilterType::Pointer dilateFilter0 = DilateImageFilterType::New();
      dilateFilter0->SetInput(itkImage);
      dilateFilter0->SetKernel(structuringElement);
      dilateFilter0->Update();

      DilateImageFilterType::Pointer dilateFilter1 = DilateImageFilterType::New();
      dilateFilter1->SetInput(dilateFilter0->GetOutput());
      dilateFilter1->SetKernel(structuringElement);
      dilateFilter1->Update();

      Image::Pointer dil = GrabItkImageMemory(dilateFilter1->GetOutput());
      dataTimeStep->AddData(dil.GetPointer(), name + suffix, "");
    }
  }
}
void mitk::ShapeBasedInterpolationAlgorithm::InterpolateIntermediateSlice(itk::Image<TPixel, VImageDimension>* result,
                                                                             const mitk::Image::Pointer &lower,
                                                                             const mitk::Image::Pointer &upper,
                                                                             float ratio)
{
  typedef itk::Image<TPixel, VImageDimension> ResultImageType;

  typename DistanceFilterImageType::Pointer lowerITK = DistanceFilterImageType::New();
  typename DistanceFilterImageType::Pointer upperITK = DistanceFilterImageType::New();

  CastToItkImage(lower, lowerITK);
  CastToItkImage(upper, upperITK);

  itk::ImageRegionConstIteratorWithIndex<DistanceFilterImageType> lowerIter (lowerITK, lowerITK->GetLargestPossibleRegion());

  lowerIter.GoToBegin();

  if (!lowerITK->GetLargestPossibleRegion().IsInside(upperITK->GetLargestPossibleRegion()) ||
      !lowerITK->GetLargestPossibleRegion().IsInside(result->GetLargestPossibleRegion()))
  {
    // TODO Exception etc.
    MITK_ERROR << "The regions of the slices for the 2D interpolation are not equally sized!";
    return;
  }

  float weight[2] = {1.0f-ratio, ratio};

  while (!lowerIter.IsAtEnd())
  {
    typename DistanceFilterImageType::PixelType lowerPixelVal = lowerIter.Get();
    typename DistanceFilterImageType::PixelType upperPixelVal = upperITK->GetPixel(lowerIter.GetIndex());

    typename DistanceFilterImageType::PixelType intermediatePixelVal =
        (weight [0] * upperPixelVal + weight [1] * lowerPixelVal > 0 ? 0 : 1);

    result->SetPixel(lowerIter.GetIndex(), static_cast<TPixel>(intermediatePixelVal));

    ++lowerIter;
  }
}
Exemplo n.º 9
0
void mitk::PixelManipulationTool::ITKPixelManipulation( itk::Image<TPixel, VImageDimension>* originalImage, Image* maskImage, Image* newImage, int newValue)
{

  typedef itk::Image< TPixel, VImageDimension> itkImageType;
  typedef itk::Image< unsigned char, 3> itkMaskType;
  typename itkImageType::Pointer itkImage;
  typename itkMaskType::Pointer itkMask;
  CastToItkImage( newImage, itkImage);
  CastToItkImage( maskImage, itkMask);

  typedef itk::ImageRegionConstIterator< itkImageType >     InputIteratorType;
  typedef itk::ImageRegionIterator< itkImageType >     OutputIteratorType;
  typedef itk::ImageRegionConstIterator< itkMaskType > MaskIteratorType;

  MaskIteratorType maskIterator ( itkMask, itkMask->GetLargestPossibleRegion() );
  InputIteratorType inputIterator( originalImage, originalImage->GetLargestPossibleRegion() );
  OutputIteratorType outputIterator( itkImage, itkImage->GetLargestPossibleRegion() );

  inputIterator.GoToBegin();
  outputIterator.GoToBegin();
  maskIterator.GoToBegin();

  while (!outputIterator.IsAtEnd())
  {
    if (maskIterator.Get())
    {
      if (m_FixedValue)
        outputIterator.Set(newValue);
      else
        outputIterator.Set( inputIterator.Get()+ newValue);
    }
    else
      outputIterator.Set( inputIterator.Get());

    ++inputIterator;
    ++outputIterator;
    ++maskIterator;
  }
}
Exemplo n.º 10
0
void mitk::CorrectorAlgorithm::ItkCalculateDifferenceImage( itk::Image<TPixel, VImageDimension>* originalImage, Image* modifiedMITKImage )
{
  typedef itk::Image<ipMITKSegmentationTYPE, VImageDimension>                     ModifiedImageType;
  typedef itk::Image<short signed int, VImageDimension>                           DiffImageType;
  typedef itk::ImageRegionConstIterator< itk::Image<TPixel,VImageDimension> >     OriginalSliceIteratorType;
  typedef itk::ImageRegionConstIterator< ModifiedImageType >                      ModifiedSliceIteratorType;
  typedef itk::ImageRegionIterator< DiffImageType >                               DiffSliceIteratorType;

  typename ModifiedImageType::Pointer modifiedImage;
  CastToItkImage( modifiedMITKImage, modifiedImage );
  
  // create new image as a copy of the input
  // this new image is the output of this filter class
  typename DiffImageType::Pointer diffImage;
  m_DifferenceImage = Image::New();
  PixelType pixelType( typeid(short signed int) );
  m_DifferenceImage->Initialize( pixelType, 2, modifiedMITKImage->GetDimensions() );
  CastToItkImage( m_DifferenceImage, diffImage );

  // iterators over both input images (original and modified) and the output image (diff)
  ModifiedSliceIteratorType modifiedIterator( modifiedImage, diffImage->GetLargestPossibleRegion() );
  OriginalSliceIteratorType originalIterator( originalImage, diffImage->GetLargestPossibleRegion() );
  DiffSliceIteratorType         diffIterator( diffImage,     diffImage->GetLargestPossibleRegion() );

  modifiedIterator.GoToBegin();
  originalIterator.GoToBegin();
  diffIterator.GoToBegin();
 
  while ( !diffIterator.IsAtEnd() )
  {
    short signed int difference = static_cast<short signed int>( static_cast<signed int>(modifiedIterator.Get()) - 
                                                          static_cast<signed int>(originalIterator.Get())); // not good for bigger values ?!
    diffIterator.Set( difference );
    
    ++modifiedIterator;
    ++originalIterator;
    ++diffIterator;
  }
}
Exemplo n.º 11
0
void mitk::FastMarchingTool3D::ConfirmSegmentation()
{
  // combine preview image with current working segmentation
  if (dynamic_cast<mitk::Image*>(m_ResultImageNode->GetData()))
  {
    //logical or combination of preview and segmentation slice
    OutputImageType::Pointer segmentationImageInITK = OutputImageType::New();

    mitk::Image::Pointer workingImage = dynamic_cast<mitk::Image*>(GetTargetSegmentationNode()->GetData());
    if(workingImage->GetTimeSlicedGeometry()->GetTimeSteps() > 1)
    {
      mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
      timeSelector->SetInput( workingImage );
      timeSelector->SetTimeNr( m_CurrentTimeStep );
      timeSelector->UpdateLargestPossibleRegion();
      CastToItkImage( timeSelector->GetOutput(), segmentationImageInITK );
    }
    else
    {
      CastToItkImage( workingImage, segmentationImageInITK );
    }

    typedef itk::OrImageFilter<OutputImageType, OutputImageType> OrImageFilterType;
    OrImageFilterType::Pointer orFilter = OrImageFilterType::New();

    orFilter->SetInput(0, m_ThresholdFilter->GetOutput());
    orFilter->SetInput(1, segmentationImageInITK);
    orFilter->Update();

    //set image volume in current time step from itk image
    workingImage->SetVolume( (void*)(m_ThresholdFilter->GetOutput()->GetPixelContainer()->GetBufferPointer()), m_CurrentTimeStep);
    this->m_ResultImageNode->SetVisibility(false);
    this->ClearSeeds();
    workingImage->Modified();
  }

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
Exemplo n.º 12
0
void mitk::OverwriteSliceImageFilter::ItkImageProcessing(const itk::Image<TPixel1, VImageDimension1> *inputImage,
                                                         itk::Image<TPixel2, VImageDimension2> *outputImage)
{
  typedef itk::Image<TPixel1, VImageDimension1> SliceImageType;
  typedef itk::Image<short signed int, VImageDimension1> DiffImageType;
  typedef itk::Image<TPixel2, VImageDimension2> VolumeImageType;

  typedef itk::ImageSliceIteratorWithIndex<VolumeImageType> OutputSliceIteratorType;
  typedef itk::ImageRegionConstIterator<SliceImageType> InputSliceIteratorType;
  typedef itk::ImageRegionIterator<DiffImageType> DiffSliceIteratorType;

  typename VolumeImageType::RegionType sliceInVolumeRegion;

  sliceInVolumeRegion = outputImage->GetLargestPossibleRegion();
  sliceInVolumeRegion.SetSize(m_SliceDimension, 1);             // just one slice
  sliceInVolumeRegion.SetIndex(m_SliceDimension, m_SliceIndex); // exactly this slice, please

  OutputSliceIteratorType outputIterator(outputImage, sliceInVolumeRegion);
  outputIterator.SetFirstDirection(m_Dimension0);
  outputIterator.SetSecondDirection(m_Dimension1);

  InputSliceIteratorType inputIterator(inputImage, inputImage->GetLargestPossibleRegion());

  typename DiffImageType::Pointer diffImage;
  CastToItkImage(m_SliceDifferenceImage, diffImage);
  DiffSliceIteratorType diffIterator(diffImage, diffImage->GetLargestPossibleRegion());

  // iterate over output slice (and over input slice simultaneously)
  outputIterator.GoToBegin();
  inputIterator.GoToBegin();
  diffIterator.GoToBegin();
  while (!outputIterator.IsAtEnd())
  {
    while (!outputIterator.IsAtEndOfSlice())
    {
      while (!outputIterator.IsAtEndOfLine())
      {
        diffIterator.Set(static_cast<short signed int>(inputIterator.Get() -
                                                       outputIterator.Get())); // oh oh, not good for bigger values
        outputIterator.Set((TPixel2)inputIterator.Get());
        ++outputIterator;
        ++inputIterator;
        ++diffIterator;
      }
      outputIterator.NextLine();
    }
    outputIterator.NextSlice();
  }
}
Exemplo n.º 13
0
void mitk::FastMarchingTool3D::Initialize()
{
  m_ReferenceImage = dynamic_cast<mitk::Image*>(m_ToolManager->GetReferenceData(0)->GetData());
  if(m_ReferenceImage->GetTimeSlicedGeometry()->GetTimeSteps() > 1)
  {
    mitk::ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New();
    timeSelector->SetInput( m_ReferenceImage );
    timeSelector->SetTimeNr( m_CurrentTimeStep );
    timeSelector->UpdateLargestPossibleRegion();
    m_ReferenceImage = timeSelector->GetOutput();
  }
  CastToItkImage(m_ReferenceImage, m_ReferenceImageAsITK);
  m_SmoothFilter->SetInput( m_ReferenceImageAsITK );
  m_NeedUpdate = true;
}
void mitk::OverwriteDirectedPlaneImageFilter::ItkSliceOverwriting(itk::Image<TPixel, VImageDimension> *input3D)
{
    typedef itk::Image<TPixel, VImageDimension - 1> SliceImageType;
    typedef itk::Image<TPixel, VImageDimension> VolumeImageType;

    typedef itk::ImageSliceIteratorWithIndex<VolumeImageType> OutputSliceIteratorType;
    typedef itk::ImageRegionConstIterator<SliceImageType> SliceIteratorType;

    typename SliceImageType::Pointer sliceImage = SliceImageType::New();
    CastToItkImage(m_SliceImage, sliceImage);

    SliceIteratorType sliceIterator(sliceImage, sliceImage->GetLargestPossibleRegion());

    sliceIterator.GoToBegin();

    Point3D currentPointIn2D;
    Point3D worldPointIn3D;

    // Here we just iterate over the slice which must be written into the 3D volumen and set the corresponding pixel in
    // our 3D volume
    while (!sliceIterator.IsAtEnd())
    {
        currentPointIn2D[0] = sliceIterator.GetIndex()[0] + 0.5;
        currentPointIn2D[1] = sliceIterator.GetIndex()[1] + 0.5;
        currentPointIn2D[2] = 0;

        m_PlaneGeometry->IndexToWorld(currentPointIn2D, worldPointIn3D);

        typename itk::Image<TPixel, VImageDimension>::IndexType outputIndex;
        m_ImageGeometry3D->WorldToIndex(worldPointIn3D, outputIndex);

        // Only access ITK image if it's inside
        if (m_ImageGeometry3D->IsIndexInside(outputIndex))
        {
            input3D->SetPixel(outputIndex, (TPixel)sliceIterator.Get());
        }

        ++sliceIterator;
    }
}
Exemplo n.º 15
0
    void mitk::BinaryThresholdULTool::ITKThresholding( itk::Image<TPixel, VImageDimension>* originalImage, Image* segmentation, unsigned int timeStep )
{
  ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New();
  timeSelector->SetInput( segmentation );
  timeSelector->SetTimeNr( timeStep );
  timeSelector->UpdateLargestPossibleRegion();
  Image::Pointer segmentation3D = timeSelector->GetOutput();

  typedef itk::Image< Tool::DefaultSegmentationDataType, 3> SegmentationType; // this is sure for new segmentations
  SegmentationType::Pointer itkSegmentation;
  CastToItkImage( segmentation3D, itkSegmentation );

  // iterate over original and segmentation
  typedef itk::ImageRegionConstIterator< itk::Image<TPixel, VImageDimension> >     InputIteratorType;
  typedef itk::ImageRegionIterator< SegmentationType >     SegmentationIteratorType;

  InputIteratorType inputIterator( originalImage, originalImage->GetLargestPossibleRegion() );
  SegmentationIteratorType outputIterator( itkSegmentation, itkSegmentation->GetLargestPossibleRegion() );

  inputIterator.GoToBegin();
  outputIterator.GoToBegin();

  while (!outputIterator.IsAtEnd())
  {
    if ( (signed)inputIterator.Get() >= m_CurrentLowerThresholdValue && (signed)inputIterator.Get() <= m_CurrentUpperThresholdValue )
    {
      outputIterator.Set( 1 );
    }
    else
    {
      outputIterator.Set( 0 );
    }

    ++inputIterator;
    ++outputIterator;
  }
}
Exemplo n.º 16
0
void mitk::BinaryThresholdULTool::UpdatePreview()
{
  typedef itk::Image<int, 3> ImageType;
  typedef itk::Image<unsigned char, 3> SegmentationType;
  typedef itk::BinaryThresholdImageFilter<ImageType, SegmentationType> ThresholdFilterType;
  mitk::Image::Pointer thresholdimage = dynamic_cast<mitk::Image*> (m_NodeForThresholding->GetData());
  if(thresholdimage)
  {
    ImageType::Pointer itkImage = ImageType::New();
    CastToItkImage(thresholdimage, itkImage);
    ThresholdFilterType::Pointer filter = ThresholdFilterType::New();
    filter->SetInput(itkImage);
    filter->SetLowerThreshold(m_CurrentLowerThresholdValue);
    filter->SetUpperThreshold(m_CurrentUpperThresholdValue);
    filter->SetInsideValue(1);
    filter->SetOutsideValue(0);
    filter->Update();

    mitk::Image::Pointer new_image = mitk::Image::New();
    CastToMitkImage(filter->GetOutput(), new_image);
    m_ThresholdFeedbackNode->SetData(new_image);
  }
  RenderingManager::GetInstance()->RequestUpdateAll();
}
Exemplo n.º 17
0
void mitk::FastMarchingTool::ConfirmSegmentation()
{
  // combine preview image with current working segmentation
  if (dynamic_cast<mitk::Image *>(m_ResultImageNode->GetData()))
  {
    // logical or combination of preview and segmentation slice

    mitk::Image::Pointer workingImageSlice;
    mitk::Image::Pointer workingImage = dynamic_cast<mitk::Image *>(this->m_ToolManager->GetWorkingData(0)->GetData());
    workingImageSlice = GetAffectedImageSliceAs2DImage(m_WorkingPlane, workingImage, m_CurrentTimeStep);

    mitk::Image::Pointer segmentationResult = mitk::Image::New();

    bool isDeprecatedUnsignedCharSegmentation =
      (workingImage->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR);

    if (isDeprecatedUnsignedCharSegmentation)
    {
      typedef itk::Image<unsigned char, 2> OutputUCharImageType;
      OutputUCharImageType::Pointer workingImageSliceInITK = OutputUCharImageType::New();

      CastToItkImage(workingImageSlice, workingImageSliceInITK);

      typedef itk::OrImageFilter<OutputImageType, OutputUCharImageType, OutputUCharImageType> OrImageFilterType;
      OrImageFilterType::Pointer orFilter = OrImageFilterType::New();

      orFilter->SetInput1(m_ThresholdFilter->GetOutput());
      orFilter->SetInput2(workingImageSliceInITK);
      orFilter->Update();

      mitk::CastToMitkImage(orFilter->GetOutput(), segmentationResult);
    }
    else
    {
      OutputImageType::Pointer workingImageSliceInITK = OutputImageType::New();

      CastToItkImage(workingImageSlice, workingImageSliceInITK);

      typedef itk::OrImageFilter<OutputImageType, OutputImageType> OrImageFilterType;
      OrImageFilterType::Pointer orFilter = OrImageFilterType::New();

      orFilter->SetInput(0, m_ThresholdFilter->GetOutput());
      orFilter->SetInput(1, workingImageSliceInITK);
      orFilter->Update();

      mitk::CastToMitkImage(orFilter->GetOutput(), segmentationResult);
    }

    segmentationResult->GetGeometry()->SetOrigin(workingImageSlice->GetGeometry()->GetOrigin());
    segmentationResult->GetGeometry()->SetIndexToWorldTransform(
      workingImageSlice->GetGeometry()->GetIndexToWorldTransform());

    // write to segmentation volume and hide preview image
    // again, current time step is not considered
    this->WriteBackSegmentationResult(m_WorkingPlane, segmentationResult, m_CurrentTimeStep);
    this->m_ResultImageNode->SetVisibility(false);

    this->ClearSeeds();
  }

  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  m_ToolManager->ActivateTool(-1);
}
Exemplo n.º 18
0
void InternalWritePreviewOnWorkingImage(itk::Image<TPixel, VImageDimension> *targetSlice,
                                        const mitk::Image *sourceSlice,
                                        mitk::Image *originalImage,
                                        int overwritevalue)
{
  typedef itk::Image<TPixel, VImageDimension> SliceType;

  typename SliceType::Pointer sourceSliceITK;
  CastToItkImage(sourceSlice, sourceSliceITK);

  // now the original slice and the ipSegmentation-painted slice are in the same format, and we can just copy all pixels
  // that are non-zero
  typedef itk::ImageRegionIterator<SliceType> OutputIteratorType;
  typedef itk::ImageRegionConstIterator<SliceType> InputIteratorType;

  InputIteratorType inputIterator(sourceSliceITK, sourceSliceITK->GetLargestPossibleRegion());
  OutputIteratorType outputIterator(targetSlice, targetSlice->GetLargestPossibleRegion());

  outputIterator.GoToBegin();
  inputIterator.GoToBegin();

  mitk::LabelSetImage *workingImage = dynamic_cast<mitk::LabelSetImage *>(originalImage);
  assert(workingImage);

  int activePixelValue = workingImage->GetActiveLabel()->GetValue();

  if (activePixelValue == 0) // if exterior is the active label
  {
    while (!outputIterator.IsAtEnd())
    {
      if (inputIterator.Get() != 0)
      {
        outputIterator.Set(overwritevalue);
      }
      ++outputIterator;
      ++inputIterator;
    }
  }
  else if (overwritevalue != 0) // if we are not erasing
  {
    while (!outputIterator.IsAtEnd())
    {
      int targetValue = static_cast<int>(outputIterator.Get());
      if (inputIterator.Get() != 0)
      {
        if (!workingImage->GetLabel(targetValue)->GetLocked())
        {
          outputIterator.Set(overwritevalue);
        }
      }
      if (targetValue == overwritevalue)
      {
        outputIterator.Set(inputIterator.Get());
      }

      ++outputIterator;
      ++inputIterator;
    }
  }
  else // if we are erasing
  {
    while (!outputIterator.IsAtEnd())
    {
      const int targetValue = outputIterator.Get();
      if (inputIterator.Get() != 0)
      {
        if (targetValue == activePixelValue)
          outputIterator.Set(overwritevalue);
      }

      ++outputIterator;
      ++inputIterator;
    }
  }
}
Exemplo n.º 19
0
/**
 1 Determine which slice is clicked into
 2 Determine if the user clicked inside or outside of the segmentation
 3 Depending on the pixel value under the mouse click position, two different things happen: (separated out into OnMousePressedInside and OnMousePressedOutside)
   3.1 Create a skeletonization of the segmentation and try to find a nice cut
     3.1.1 Call a ipSegmentation algorithm to create a nice cut
     3.1.2 Set the result of this algorithm as the feedback contour
   3.2 Initialize region growing
     3.2.1 Determine memory offset inside the original image
     3.2.2 Determine initial region growing parameters from the level window settings of the image
     3.2.3 Perform a region growing (which generates a new feedback contour)
 */
bool mitk::RegionGrowingTool::OnMousePressed ( StateMachineAction*, InteractionEvent* interactionEvent )
{
  mitk::InteractionPositionEvent* positionEvent = dynamic_cast<mitk::InteractionPositionEvent*>( interactionEvent );
  //const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
  if (!positionEvent) return false;

  m_LastEventSender = positionEvent->GetSender();
  m_LastEventSlice = m_LastEventSender->GetSlice();

  //ToolLogger::SetVerboseness(3);

  MITK_DEBUG << "OnMousePressed" << std::endl;
  if ( FeedbackContourTool::CanHandleEvent(interactionEvent) > 0.0 )
  {
    MITK_DEBUG << "OnMousePressed: FeedbackContourTool says ok" << std::endl;

    // 1. Find out which slice the user clicked, find out which slice of the toolmanager's reference and working image corresponds to that
    if (positionEvent)
    {
      MITK_DEBUG << "OnMousePressed: got positionEvent" << std::endl;

      m_ReferenceSlice = FeedbackContourTool::GetAffectedReferenceSlice( positionEvent );
      m_WorkingSlice   = FeedbackContourTool::GetAffectedWorkingSlice( positionEvent );

      if ( m_WorkingSlice.IsNotNull() ) // can't do anything without the segmentation
      {
        MITK_DEBUG << "OnMousePressed: got working slice" << std::endl;

        // 2. Determine if the user clicked inside or outside of the segmentation
          const Geometry3D* workingSliceGeometry = m_WorkingSlice->GetGeometry();
          Point3D mprojectedPointIn2D;
          workingSliceGeometry->WorldToIndex( positionEvent->GetPositionInWorld(), mprojectedPointIn2D);
          itk::Index<2> projectedPointInWorkingSlice2D;
          projectedPointInWorkingSlice2D[0] = static_cast<int>( mprojectedPointIn2D[0] - 0.5 );
          projectedPointInWorkingSlice2D[1] = static_cast<int>( mprojectedPointIn2D[1] - 0.5 );

          if ( workingSliceGeometry->IsIndexInside( projectedPointInWorkingSlice2D ) )
          {
            MITK_DEBUG << "OnMousePressed: point " << positionEvent->GetPositionInWorld() << " (index coordinates " << projectedPointInWorkingSlice2D << ") IS in working slice" << std::endl;

            // Convert to ipMITKSegmentationTYPE (because getting pixels relys on that data type)
            itk::Image< ipMITKSegmentationTYPE, 2 >::Pointer correctPixelTypeImage;
            CastToItkImage( m_WorkingSlice, correctPixelTypeImage );
            assert (correctPixelTypeImage.IsNotNull() );

          // possible bug in CastToItkImage ?
          // direction maxtrix is wrong/broken/not working after CastToItkImage, leading to a failed assertion in
          // mitk/Core/DataStructures/mitkSlicedGeometry3D.cpp, 479:
          // virtual void mitk::SlicedGeometry3D::SetSpacing(const mitk::Vector3D&): Assertion `aSpacing[0]>0 && aSpacing[1]>0 && aSpacing[2]>0' failed
          // solution here: we overwrite it with an unity matrix
          itk::Image< ipMITKSegmentationTYPE, 2 >::DirectionType imageDirection;
          imageDirection.SetIdentity();
          correctPixelTypeImage->SetDirection(imageDirection);

          Image::Pointer temporarySlice = Image::New();
        //  temporarySlice = ImportItkImage( correctPixelTypeImage );
          CastToMitkImage( correctPixelTypeImage, temporarySlice );

          mitkIpPicDescriptor* workingPicSlice = mitkIpPicNew();
          CastToIpPicDescriptor(temporarySlice, workingPicSlice);

          int initialWorkingOffset = projectedPointInWorkingSlice2D[1] * workingPicSlice->n[0] + projectedPointInWorkingSlice2D[0];

          if ( initialWorkingOffset < static_cast<int>( workingPicSlice->n[0] * workingPicSlice->n[1] ) &&
               initialWorkingOffset >= 0 )
          {
            // 3. determine the pixel value under the last click
            bool inside = static_cast<ipMITKSegmentationTYPE*>(workingPicSlice->data)[initialWorkingOffset] != 0;
            m_PaintingPixelValue = inside ? 0 : 1; // if inside, we want to remove a part, otherwise we want to add something

            if ( m_LastWorkingSeed >= static_cast<int>( workingPicSlice->n[0] * workingPicSlice->n[1] ) ||
                 m_LastWorkingSeed < 0 )
            {
              inside = false;
            }

            if ( m_ReferenceSlice.IsNotNull() )
            {
              MITK_DEBUG << "OnMousePressed: got reference slice" << std::endl;

              m_OriginalPicSlice = mitkIpPicNew();
              CastToIpPicDescriptor(m_ReferenceSlice, m_OriginalPicSlice);

              // 3.1. Switch depending on the pixel value
              if (inside)
              {
                OnMousePressedInside( NULL, interactionEvent, workingPicSlice, initialWorkingOffset);
              }
              else
              {
                OnMousePressedOutside( NULL, interactionEvent);
              }
            }
          }
        }
      }
    }
  }

  MITK_DEBUG << "end OnMousePressed" << std::endl;
  return true;
}
Exemplo n.º 20
0
/*!
\brief Modify input tractogram: fiber resampling, compression, pruning and transformation.
*/
int main(int argc, char* argv[])
{
    mitkCommandLineParser parser;

    parser.setTitle("Tract Density");
    parser.setCategory("Fiber Tracking and Processing Methods");
    parser.setDescription("Generate tract density image, fiber envelope or fiber endpoints image.");
    parser.setContributor("MIC");

    parser.setArgumentPrefix("--", "-");
    parser.addArgument("input", "i", mitkCommandLineParser::String, "Input:", "input fiber bundle (.fib)", us::Any(), false);
    parser.addArgument("output", "o", mitkCommandLineParser::String, "Output:", "output image", us::Any(), false);
    parser.addArgument("binary", "", mitkCommandLineParser::Bool, "Binary output:", "calculate binary tract envelope", us::Any());
    parser.addArgument("endpoints", "", mitkCommandLineParser::Bool, "Output endpoints image:", "calculate image of fiber endpoints instead of mask", us::Any());
    parser.addArgument("reference_image", "", mitkCommandLineParser::String, "Reference image:", "output image will have geometry of this reference image", us::Any());


    std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
    if (parsedArgs.size()==0)
        return EXIT_FAILURE;

    bool binary = false;
    if (parsedArgs.count("binary"))
        binary = us::any_cast<bool>(parsedArgs["binary"]);

    bool endpoints = false;
    if (parsedArgs.count("endpoints"))
        endpoints = us::any_cast<bool>(parsedArgs["endpoints"]);

    std::string reference_image = "";
    if (parsedArgs.count("reference_image"))
        reference_image = us::any_cast<std::string>(parsedArgs["reference_image"]);

    std::string inFileName = us::any_cast<std::string>(parsedArgs["input"]);
    std::string outFileName = us::any_cast<std::string>(parsedArgs["output"]);

    try
    {
        mitk::FiberBundle::Pointer fib = LoadFib(inFileName);

        mitk::Image::Pointer ref_img;
        MITK_INFO << reference_image;
        if (!reference_image.empty())
            ref_img = dynamic_cast<mitk::Image*>(mitk::IOUtil::Load(reference_image)[0].GetPointer());

        if (endpoints)
        {
            typedef unsigned int OutPixType;
            typedef itk::Image<OutPixType, 3> OutImageType;

            typedef itk::TractsToFiberEndingsImageFilter< OutImageType > ImageGeneratorType;
            ImageGeneratorType::Pointer generator = ImageGeneratorType::New();
            generator->SetFiberBundle(fib);

            if (ref_img.IsNotNull())
            {
                OutImageType::Pointer itkImage = OutImageType::New();
                CastToItkImage(ref_img, itkImage);
                generator->SetInputImage(itkImage);
                generator->SetUseImageGeometry(true);

            }
            generator->Update();

            // get output image
            typedef itk::Image<OutPixType,3> OutType;
            OutType::Pointer outImg = generator->GetOutput();
            mitk::Image::Pointer img = mitk::Image::New();
            img->InitializeByItk(outImg.GetPointer());
            img->SetVolume(outImg->GetBufferPointer());

            mitk::IOUtil::Save(img, outFileName );
        }
        else if (binary)
        {
            typedef unsigned char OutPixType;
            typedef itk::Image<OutPixType, 3> OutImageType;

            itk::TractDensityImageFilter< OutImageType >::Pointer generator = itk::TractDensityImageFilter< OutImageType >::New();
            generator->SetFiberBundle(fib);
            generator->SetBinaryOutput(binary);
            generator->SetOutputAbsoluteValues(false);
            generator->SetWorkOnFiberCopy(false);

            if (ref_img.IsNotNull())
            {
                OutImageType::Pointer itkImage = OutImageType::New();
                CastToItkImage(ref_img, itkImage);
                generator->SetInputImage(itkImage);
                generator->SetUseImageGeometry(true);

            }
            generator->Update();

            // get output image
            typedef itk::Image<OutPixType,3> OutType;
            OutType::Pointer outImg = generator->GetOutput();
            mitk::Image::Pointer img = mitk::Image::New();
            img->InitializeByItk(outImg.GetPointer());
            img->SetVolume(outImg->GetBufferPointer());

            mitk::IOUtil::Save(img, outFileName );
        }
        else
        {
            typedef float OutPixType;
            typedef itk::Image<OutPixType, 3> OutImageType;

            itk::TractDensityImageFilter< OutImageType >::Pointer generator = itk::TractDensityImageFilter< OutImageType >::New();
            generator->SetFiberBundle(fib);
            generator->SetBinaryOutput(binary);
            generator->SetOutputAbsoluteValues(false);
            generator->SetWorkOnFiberCopy(false);

            if (ref_img.IsNotNull())
            {
                OutImageType::Pointer itkImage = OutImageType::New();
                CastToItkImage(ref_img, itkImage);
                generator->SetInputImage(itkImage);
                generator->SetUseImageGeometry(true);

            }
            generator->Update();

            // get output image
            typedef itk::Image<OutPixType,3> OutType;
            OutType::Pointer outImg = generator->GetOutput();
            mitk::Image::Pointer img = mitk::Image::New();
            img->InitializeByItk(outImg.GetPointer());
            img->SetVolume(outImg->GetBufferPointer());

            mitk::IOUtil::Save(img, outFileName );
        }

    }
    catch (itk::ExceptionObject e)
    {
        std::cout << e;
        return EXIT_FAILURE;
    }
    catch (std::exception e)
    {
        std::cout << e.what();
        return EXIT_FAILURE;
    }
    catch (...)
    {
        std::cout << "ERROR!?!";
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
void QmitkBasicImageProcessing::StartButtonClicked()
{
  if(!m_SelectedImageNode->GetNode()) return;

  this->BusyCursorOn();

  mitk::Image::Pointer newImage;

  try
  {
    newImage = dynamic_cast<mitk::Image*>(m_SelectedImageNode->GetNode()->GetData());
  }
  catch ( std::exception &e )
  {
  QString exceptionString = "An error occured during image loading:\n";
  exceptionString.append( e.what() );
    QMessageBox::warning( NULL, "Basic Image Processing", exceptionString , QMessageBox::Ok, QMessageBox::NoButton );
    this->BusyCursorOff();
    return;
  }

  // check if input image is valid, casting does not throw exception when casting from 'NULL-Object'
  if ( (! newImage) || (newImage->IsInitialized() == false) )
  {
    this->BusyCursorOff();

    QMessageBox::warning( NULL, "Basic Image Processing", "Input image is broken or not initialized. Returning.", QMessageBox::Ok, QMessageBox::NoButton );
    return;
  }

  // check if operation is done on 4D a image time step
  if(newImage->GetDimension() > 3)
  {
    mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
    timeSelector->SetInput(newImage);
    timeSelector->SetTimeNr( ((QmitkSliderNavigatorWidget*)m_Controls->sliceNavigatorTime)->GetPos() );
    timeSelector->Update();
    newImage = timeSelector->GetOutput();
  }



  // check if image or vector image
  ImageType::Pointer itkImage = ImageType::New();
  VectorImageType::Pointer itkVecImage = VectorImageType::New();

  int isVectorImage = newImage->GetPixelType().GetNumberOfComponents();

  if(isVectorImage > 1)
  {
    CastToItkImage( newImage, itkVecImage );
  }
  else
  {
    CastToItkImage( newImage, itkImage );
  }

  std::stringstream nameAddition("");

  int param1 = m_Controls->sbParam1->value();
  int param2 = m_Controls->sbParam2->value();
  double dparam1 = m_Controls->dsbParam1->value();
  double dparam2 = m_Controls->dsbParam2->value();
  double dparam3 = m_Controls->dsbParam3->value();

  try{

  switch (m_SelectedAction)
  {

  case GAUSSIAN:
    {
      GaussianFilterType::Pointer gaussianFilter = GaussianFilterType::New();
      gaussianFilter->SetInput( itkImage );
      gaussianFilter->SetVariance( param1 );
      gaussianFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(gaussianFilter->GetOutput())->Clone();
      nameAddition << "_Gaussian_var_" << param1;
      std::cout << "Gaussian filtering successful." << std::endl;
      break;
    }

  case MEDIAN:
    {
      MedianFilterType::Pointer medianFilter = MedianFilterType::New();
      MedianFilterType::InputSizeType size;
      size.Fill(param1);
      medianFilter->SetRadius( size );
      medianFilter->SetInput(itkImage);
      medianFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(medianFilter->GetOutput())->Clone();
      nameAddition << "_Median_radius_" << param1;
      std::cout << "Median Filtering successful." << std::endl;
      break;
    }

  case TOTALVARIATION:
    {
      if(isVectorImage > 1)
      {
        VectorTotalVariationFilterType::Pointer TVFilter
          = VectorTotalVariationFilterType::New();
        TVFilter->SetInput( itkVecImage.GetPointer() );
        TVFilter->SetNumberIterations(param1);
        TVFilter->SetLambda(double(param2)/1000.);
        TVFilter->UpdateLargestPossibleRegion();

        newImage = mitk::ImportItkImage(TVFilter->GetOutput())->Clone();
      }
      else
      {
        ImagePTypeToFloatPTypeCasterType::Pointer floatCaster = ImagePTypeToFloatPTypeCasterType::New();
        floatCaster->SetInput( itkImage );
        floatCaster->Update();
        FloatImageType::Pointer fImage = floatCaster->GetOutput();

        TotalVariationFilterType::Pointer TVFilter
          = TotalVariationFilterType::New();
        TVFilter->SetInput( fImage.GetPointer() );
        TVFilter->SetNumberIterations(param1);
        TVFilter->SetLambda(double(param2)/1000.);
        TVFilter->UpdateLargestPossibleRegion();

        newImage = mitk::ImportItkImage(TVFilter->GetOutput())->Clone();
      }

      nameAddition << "_TV_Iter_" << param1 << "_L_" << param2;
      std::cout << "Total Variation Filtering successful." << std::endl;
      break;
    }

  case DILATION:
    {
      BallType binaryBall;
      binaryBall.SetRadius( param1 );
      binaryBall.CreateStructuringElement();

      DilationFilterType::Pointer dilationFilter = DilationFilterType::New();
      dilationFilter->SetInput( itkImage );
      dilationFilter->SetKernel( binaryBall );
      dilationFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(dilationFilter->GetOutput())->Clone();
      nameAddition << "_Dilated_by_" << param1;
      std::cout << "Dilation successful." << std::endl;
      break;
    }

  case EROSION:
    {
      BallType binaryBall;
      binaryBall.SetRadius( param1 );
      binaryBall.CreateStructuringElement();

      ErosionFilterType::Pointer erosionFilter = ErosionFilterType::New();
      erosionFilter->SetInput( itkImage );
      erosionFilter->SetKernel( binaryBall );
      erosionFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(erosionFilter->GetOutput())->Clone();
      nameAddition << "_Eroded_by_" << param1;
      std::cout << "Erosion successful." << std::endl;
      break;
    }

  case OPENING:
    {
      BallType binaryBall;
      binaryBall.SetRadius( param1 );
      binaryBall.CreateStructuringElement();

      OpeningFilterType::Pointer openFilter = OpeningFilterType::New();
      openFilter->SetInput( itkImage );
      openFilter->SetKernel( binaryBall );
      openFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(openFilter->GetOutput())->Clone();
      nameAddition << "_Opened_by_" << param1;
      std::cout << "Opening successful." << std::endl;
      break;
    }

  case CLOSING:
    {
      BallType binaryBall;
      binaryBall.SetRadius( param1 );
      binaryBall.CreateStructuringElement();

      ClosingFilterType::Pointer closeFilter = ClosingFilterType::New();
      closeFilter->SetInput( itkImage );
      closeFilter->SetKernel( binaryBall );
      closeFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(closeFilter->GetOutput())->Clone();
      nameAddition << "_Closed_by_" << param1;
      std::cout << "Closing successful." << std::endl;
      break;
    }

  case GRADIENT:
    {
      GradientFilterType::Pointer gradientFilter = GradientFilterType::New();
      gradientFilter->SetInput( itkImage );
      gradientFilter->SetSigma( param1 );
      gradientFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(gradientFilter->GetOutput())->Clone();
      nameAddition << "_Gradient_sigma_" << param1;
      std::cout << "Gradient calculation successful." << std::endl;
      break;
    }

  case LAPLACIAN:
    {
      // the laplace filter requires a float type image as input, we need to cast the itkImage
      // to correct type
      ImagePTypeToFloatPTypeCasterType::Pointer caster = ImagePTypeToFloatPTypeCasterType::New();
      caster->SetInput( itkImage );
      caster->Update();
      FloatImageType::Pointer fImage = caster->GetOutput();

      LaplacianFilterType::Pointer laplacianFilter = LaplacianFilterType::New();
      laplacianFilter->SetInput( fImage );
      laplacianFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(laplacianFilter->GetOutput())->Clone();
      nameAddition << "_Second_Derivative";
      std::cout << "Laplacian filtering successful." << std::endl;
      break;
    }

  case SOBEL:
    {
      // the sobel filter requires a float type image as input, we need to cast the itkImage
      // to correct type
      ImagePTypeToFloatPTypeCasterType::Pointer caster = ImagePTypeToFloatPTypeCasterType::New();
      caster->SetInput( itkImage );
      caster->Update();
      FloatImageType::Pointer fImage = caster->GetOutput();

      SobelFilterType::Pointer sobelFilter = SobelFilterType::New();
      sobelFilter->SetInput( fImage );
      sobelFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(sobelFilter->GetOutput())->Clone();
      nameAddition << "_Sobel";
      std::cout << "Edge Detection successful." << std::endl;
      break;
    }

  case THRESHOLD:
    {
      ThresholdFilterType::Pointer thFilter = ThresholdFilterType::New();
      thFilter->SetLowerThreshold(param1 < param2 ? param1 : param2);
      thFilter->SetUpperThreshold(param2 > param1 ? param2 : param1);
      thFilter->SetInsideValue(1);
      thFilter->SetOutsideValue(0);
      thFilter->SetInput(itkImage);
      thFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(thFilter->GetOutput())->Clone();
      nameAddition << "_Threshold";
      std::cout << "Thresholding successful." << std::endl;
      break;
    }

  case INVERSION:
    {
      InversionFilterType::Pointer invFilter = InversionFilterType::New();
      mitk::ScalarType min = newImage->GetScalarValueMin();
      mitk::ScalarType max = newImage->GetScalarValueMax();
      invFilter->SetMaximum( max + min );
      invFilter->SetInput(itkImage);
      invFilter->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(invFilter->GetOutput())->Clone();
      nameAddition << "_Inverted";
      std::cout << "Image inversion successful." << std::endl;
      break;
    }

  case DOWNSAMPLING:
    {
      ResampleImageFilterType::Pointer downsampler = ResampleImageFilterType::New();
      downsampler->SetInput( itkImage );

      NearestInterpolatorType::Pointer interpolator = NearestInterpolatorType::New();
      downsampler->SetInterpolator( interpolator );

      downsampler->SetDefaultPixelValue( 0 );

      ResampleImageFilterType::SpacingType spacing = itkImage->GetSpacing();
      spacing *= (double) param1;
      downsampler->SetOutputSpacing( spacing );

      downsampler->SetOutputOrigin( itkImage->GetOrigin() );
      downsampler->SetOutputDirection( itkImage->GetDirection() );

      ResampleImageFilterType::SizeType size = itkImage->GetLargestPossibleRegion().GetSize();
      for ( int i = 0; i < 3; ++i )
      {
        size[i] /= param1;
      }
      downsampler->SetSize( size );
      downsampler->UpdateLargestPossibleRegion();

      newImage = mitk::ImportItkImage(downsampler->GetOutput())->Clone();
      nameAddition << "_Downsampled_by_" << param1;
      std::cout << "Downsampling successful." << std::endl;
      break;
    }

  case FLIPPING:
    {
      FlipImageFilterType::Pointer flipper = FlipImageFilterType::New();
      flipper->SetInput( itkImage );
      itk::FixedArray<bool, 3> flipAxes;
      for(int i=0; i<3; ++i)
      {
        if(i == param1)
        {
          flipAxes[i] = true;
        }
        else
        {
          flipAxes[i] = false;
        }
      }
      flipper->SetFlipAxes(flipAxes);
      flipper->UpdateLargestPossibleRegion();
      newImage = mitk::ImportItkImage(flipper->GetOutput())->Clone();
      std::cout << "Image flipping successful." << std::endl;
      break;
    }

  case RESAMPLING:
    {
      std::string selectedInterpolator;
      ResampleImageFilterType::Pointer resampler = ResampleImageFilterType::New();
      switch (m_SelectedInterpolation)
      {
      case LINEAR:
        {
          LinearInterpolatorType::Pointer interpolator = LinearInterpolatorType::New();
          resampler->SetInterpolator(interpolator);
          selectedInterpolator = "Linear";
          break;
        }
      case NEAREST:
        {
          NearestInterpolatorType::Pointer interpolator = NearestInterpolatorType::New();
          resampler->SetInterpolator(interpolator);
          selectedInterpolator = "Nearest";
          break;
        }
      default:
        {
          LinearInterpolatorType::Pointer interpolator = LinearInterpolatorType::New();
          resampler->SetInterpolator(interpolator);
          selectedInterpolator = "Linear";
          break;
        }
      }
      resampler->SetInput( itkImage );
      resampler->SetOutputOrigin( itkImage->GetOrigin() );

      ImageType::SizeType input_size = itkImage->GetLargestPossibleRegion().GetSize();
      ImageType::SpacingType input_spacing = itkImage->GetSpacing();

      ImageType::SizeType output_size;
      ImageType::SpacingType output_spacing;

      output_size[0] = input_size[0] * (input_spacing[0] / dparam1);
      output_size[1] = input_size[1] * (input_spacing[1] / dparam2);
      output_size[2] = input_size[2] * (input_spacing[2] / dparam3);
      output_spacing [0] = dparam1;
      output_spacing [1] = dparam2;
      output_spacing [2] = dparam3;

      resampler->SetSize( output_size );
      resampler->SetOutputSpacing( output_spacing );
      resampler->SetOutputDirection( itkImage->GetDirection() );

      resampler->UpdateLargestPossibleRegion();

      ImageType::Pointer resampledImage = resampler->GetOutput();

      newImage = mitk::ImportItkImage( resampledImage );
      nameAddition << "_Resampled_" << selectedInterpolator;
      std::cout << "Resampling successful." << std::endl;
      break;
    }


  case RESCALE:
    {
      FloatImageType::Pointer floatImage = FloatImageType::New();
      CastToItkImage( newImage, floatImage );
      itk::RescaleIntensityImageFilter<FloatImageType,FloatImageType>::Pointer filter = itk::RescaleIntensityImageFilter<FloatImageType,FloatImageType>::New();
      filter->SetInput(0, floatImage);
      filter->SetOutputMinimum(dparam1);
      filter->SetOutputMaximum(dparam2);
      filter->Update();
      floatImage = filter->GetOutput();

      newImage = mitk::Image::New();
      newImage->InitializeByItk(floatImage.GetPointer());
      newImage->SetVolume(floatImage->GetBufferPointer());
      nameAddition << "_Rescaled";
      std::cout << "Rescaling successful." << std::endl;

      break;
    }

  default:
    this->BusyCursorOff();
    return;
  }
  }
  catch (...)
  {
    this->BusyCursorOff();
    QMessageBox::warning(NULL, "Warning", "Problem when applying filter operation. Check your input...");
    return;
  }

  newImage->DisconnectPipeline();

  // adjust level/window to new image
  mitk::LevelWindow levelwindow;
  levelwindow.SetAuto( newImage );
  mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New();
  levWinProp->SetLevelWindow( levelwindow );

  // compose new image name
  std::string name = m_SelectedImageNode->GetNode()->GetName();
  if (name.find(".pic.gz") == name.size() -7 )
  {
    name = name.substr(0,name.size() -7);
  }
  name.append( nameAddition.str() );

  // create final result MITK data storage node
  mitk::DataNode::Pointer result = mitk::DataNode::New();
  result->SetProperty( "levelwindow", levWinProp );
  result->SetProperty( "name", mitk::StringProperty::New( name.c_str() ) );
  result->SetData( newImage );

  // for vector images, a different mapper is needed
  if(isVectorImage > 1)
  {
    mitk::VectorImageMapper2D::Pointer mapper =
      mitk::VectorImageMapper2D::New();
    result->SetMapper(1,mapper);
  }

  // reset GUI to ease further processing
//  this->ResetOneImageOpPanel();

  // add new image to data storage and set as active to ease further processing
  GetDefaultDataStorage()->Add( result, m_SelectedImageNode->GetNode() );
  if ( m_Controls->cbHideOrig->isChecked() == true )
    m_SelectedImageNode->GetNode()->SetProperty( "visible", mitk::BoolProperty::New(false) );
  // TODO!! m_Controls->m_ImageSelector1->SetSelectedNode(result);

  // show the results
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  this->BusyCursorOff();
}
bool mitk::SetRegionTool::OnMousePressed ( StateMachineAction*, InteractionEvent* interactionEvent )
{
  mitk::InteractionPositionEvent* positionEvent = dynamic_cast<mitk::InteractionPositionEvent*>( interactionEvent );
  //const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
  if (!positionEvent) return false;

  m_LastEventSender = positionEvent->GetSender();
  m_LastEventSlice = m_LastEventSender->GetSlice();
  int timeStep = positionEvent->GetSender()->GetTimeStep();

  // 1. Get the working image
  Image::Pointer workingSlice   = FeedbackContourTool::GetAffectedWorkingSlice( positionEvent );
  if ( workingSlice.IsNull() ) return false; // can't do anything without the segmentation

  // if click was outside the image, don't continue
  const BaseGeometry* sliceGeometry = workingSlice->GetGeometry();
  itk::Index<2> projectedPointIn2D;
  sliceGeometry->WorldToIndex( positionEvent->GetPositionInWorld(), projectedPointIn2D );
  if ( !sliceGeometry->IsIndexInside( projectedPointIn2D ) )
  {
    MITK_ERROR << "point apparently not inside segmentation slice" << std::endl;
    return false; // can't use that as a seed point
  }

    // Convert to ipMITKSegmentationTYPE (because ipMITKSegmentationGetContour8N relys on that data type)
    itk::Image< ipMITKSegmentationTYPE, 2 >::Pointer correctPixelTypeImage;
    CastToItkImage( workingSlice, correctPixelTypeImage );
    assert (correctPixelTypeImage.IsNotNull() );

  // possible bug in CastToItkImage ?
  // direction maxtrix is wrong/broken/not working after CastToItkImage, leading to a failed assertion in
  // mitk/Core/DataStructures/mitkSlicedGeometry3D.cpp, 479:
  // virtual void mitk::SlicedGeometry3D::SetSpacing(const mitk::Vector3D&): Assertion `aSpacing[0]>0 && aSpacing[1]>0 && aSpacing[2]>0' failed
  // solution here: we overwrite it with an unity matrix
  itk::Image< ipMITKSegmentationTYPE, 2 >::DirectionType imageDirection;
  imageDirection.SetIdentity();
  correctPixelTypeImage->SetDirection(imageDirection);

    Image::Pointer temporarySlice = Image::New();
  //  temporarySlice = ImportItkImage( correctPixelTypeImage );
    CastToMitkImage( correctPixelTypeImage, temporarySlice );


  // check index positions
  mitkIpPicDescriptor* originalPicSlice = mitkIpPicNew();
  CastToIpPicDescriptor( temporarySlice, originalPicSlice );

  int m_SeedPointMemoryOffset = projectedPointIn2D[1] * originalPicSlice->n[0] + projectedPointIn2D[0];

  if ( m_SeedPointMemoryOffset >= static_cast<int>( originalPicSlice->n[0] * originalPicSlice->n[1] ) ||
       m_SeedPointMemoryOffset < 0 )
  {
    MITK_ERROR << "Memory offset calculation if mitk::SetRegionTool has some serious flaw! Aborting.." << std::endl;
    return false;
  }

  // 2. Determine the contour that surronds the selected "piece of the image"

  // find a contour seed point
  unsigned int oneContourOffset = static_cast<unsigned int>( m_SeedPointMemoryOffset ); // safe because of earlier check if m_SeedPointMemoryOffset < 0

  /**
    * The logic of finding a starting point for the contour is the following:
    *
    *  - If the initial seed point is 0, we are either inside a hole or outside of every segmentation.
    *    We move to the right until we hit a 1, which must be part of a contour.
    *
    *  - If the initial seed point is 1, then ...
    *    we now do the same (running to the right) until we hit a 1
    *
    *  In both cases the found contour point is used to extract a contour and
    *  then a test is applied to find out if the initial seed point is contained
    *  in the contour. If this is the case, filling should be applied, otherwise
    *  nothing is done.
    */
  unsigned int size = originalPicSlice->n[0] * originalPicSlice->n[1];
/*
  unsigned int rowSize = originalPicSlice->n[0];
*/
  ipMITKSegmentationTYPE* data = static_cast<ipMITKSegmentationTYPE*>(originalPicSlice->data);

  if ( data[oneContourOffset] == 0 ) // initial seed 0
  {
    for ( ; oneContourOffset < size; ++oneContourOffset )
    {
      if ( data[oneContourOffset] > 0 ) break;
    }
  }
  else if ( data[oneContourOffset] == 1 ) // initial seed 1
  {
    unsigned int lastValidPixel = size-1; // initialization, will be changed lateron
    bool inSeg = true;    // inside segmentation?
    for ( ; oneContourOffset < size; ++oneContourOffset )
    {
      if ( ( data[oneContourOffset] == 0 ) && inSeg ) // pixel 0 and inside-flag set: this happens at the first pixel outside a filled region
      {
        inSeg = false;
        lastValidPixel = oneContourOffset - 1; // store the last pixel position inside a filled region
        break;
      }
      else // pixel 1, inside-flag doesn't matter: this happens while we are inside a filled region
      {
        inSeg = true; // first iteration lands here
      }

    }
    oneContourOffset = lastValidPixel;
  }
  else
  {
    MITK_ERROR << "Fill/Erase was never intended to work with other than binary images." << std::endl;
    m_FillContour = false;
    return false;
  }

  if (oneContourOffset == size) // nothing found until end of slice
  {
    m_FillContour = false;
    return false;
  }

  int numberOfContourPoints( 0 );
  int newBufferSize( 0 );
  //MITK_INFO << "getting contour from offset " << oneContourOffset << " ("<<oneContourOffset%originalPicSlice->n[0]<<","<<oneContourOffset/originalPicSlice->n[0]<<")"<<std::endl;
  float* contourPoints = ipMITKSegmentationGetContour8N( originalPicSlice, oneContourOffset, numberOfContourPoints, newBufferSize ); // memory allocated with malloc

  //MITK_INFO << "contourPoints " << contourPoints << " (N="<<numberOfContourPoints<<")"<<std::endl;
  assert(contourPoints == NULL || numberOfContourPoints > 0);

  bool cursorInsideContour = ipMITKSegmentationIsInsideContour( contourPoints, numberOfContourPoints, projectedPointIn2D[0], projectedPointIn2D[1]);

  // decide if contour should be filled or not
  m_FillContour = cursorInsideContour;

  if (m_FillContour)
  {
    // copy point from float* to mitk::Contour
    ContourModel::Pointer contourInImageIndexCoordinates = ContourModel::New();
    contourInImageIndexCoordinates->Expand(timeStep + 1);
    contourInImageIndexCoordinates->SetClosed(true, timeStep);
    Point3D newPoint;
    for (int index = 0; index < numberOfContourPoints; ++index)
    {
      newPoint[0] = contourPoints[ 2 * index + 0 ] - 0.5;
      newPoint[1] = contourPoints[ 2 * index + 1] - 0.5;
      newPoint[2] = 0;

      contourInImageIndexCoordinates->AddVertex(newPoint, timeStep);
    }

    m_SegmentationContourInWorldCoordinates = FeedbackContourTool::BackProjectContourFrom2DSlice( workingSlice->GetGeometry(), contourInImageIndexCoordinates, true ); // true, correct the result from ipMITKSegmentationGetContour8N

    // 3. Show the contour
    FeedbackContourTool::SetFeedbackContour( *m_SegmentationContourInWorldCoordinates );

    FeedbackContourTool::SetFeedbackContourVisible(true);
    mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
  }

  // always generate a second contour, containing the whole image (used when CTRL is pressed)
  {
    // copy point from float* to mitk::Contour
    ContourModel::Pointer contourInImageIndexCoordinates = ContourModel::New();
    contourInImageIndexCoordinates->Expand(timeStep + 1);
    contourInImageIndexCoordinates->SetClosed(true, timeStep);
    Point3D newPoint;
    newPoint[0] = 0; newPoint[1] = 0; newPoint[2] = 0.0;
    contourInImageIndexCoordinates->AddVertex( newPoint, timeStep );
    newPoint[0] = originalPicSlice->n[0]; newPoint[1] = 0; newPoint[2] = 0.0;
    contourInImageIndexCoordinates->AddVertex( newPoint, timeStep );
    newPoint[0] = originalPicSlice->n[0]; newPoint[1] = originalPicSlice->n[1]; newPoint[2] = 0.0;
    contourInImageIndexCoordinates->AddVertex( newPoint, timeStep );
    newPoint[0] = 0; newPoint[1] = originalPicSlice->n[1]; newPoint[2] = 0.0;
    contourInImageIndexCoordinates->AddVertex( newPoint, timeStep );

    m_WholeImageContourInWorldCoordinates = FeedbackContourTool::BackProjectContourFrom2DSlice( workingSlice->GetGeometry(), contourInImageIndexCoordinates, true ); // true, correct the result from ipMITKSegmentationGetContour8N

    // 3. Show the contour
    FeedbackContourTool::SetFeedbackContour( *m_SegmentationContourInWorldCoordinates );

    FeedbackContourTool::SetFeedbackContourVisible(true);
    mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
  }


  free(contourPoints);

  return true;
}
Exemplo n.º 23
0
void mitk::SetRegionTool::OnMousePressed(StateMachineAction *, InteractionEvent *interactionEvent)
{
  auto *positionEvent = dynamic_cast<mitk::InteractionPositionEvent *>(interactionEvent);
  if (!positionEvent)
    return;

  m_LastEventSender = positionEvent->GetSender();
  m_LastEventSlice = m_LastEventSender->GetSlice();

  // 1. Get the working image
  Image::Pointer workingSlice = FeedbackContourTool::GetAffectedWorkingSlice(positionEvent);
  if (workingSlice.IsNull())
    return; // can't do anything without the segmentation

  // if click was outside the image, don't continue
  const BaseGeometry *sliceGeometry = workingSlice->GetGeometry();
  itk::Index<3> projectedPointIn2D;
  sliceGeometry->WorldToIndex(positionEvent->GetPositionInWorld(), projectedPointIn2D);
  if (!sliceGeometry->IsIndexInside(projectedPointIn2D))
  {
    MITK_ERROR << "point apparently not inside segmentation slice" << std::endl;
    return; // can't use that as a seed point
  }

  typedef itk::Image<DefaultSegmentationDataType, 2> InputImageType;
  typedef InputImageType::IndexType IndexType;
  typedef itk::ConnectedThresholdImageFilter<InputImageType, InputImageType> RegionGrowingFilterType;
  RegionGrowingFilterType::Pointer regionGrower = RegionGrowingFilterType::New();

  // convert world coordinates to image indices
  IndexType seedIndex;
  sliceGeometry->WorldToIndex(positionEvent->GetPositionInWorld(), seedIndex);

  // perform region growing in desired segmented region
  InputImageType::Pointer itkImage = InputImageType::New();
  CastToItkImage(workingSlice, itkImage);
  regionGrower->SetInput(itkImage);
  regionGrower->AddSeed(seedIndex);

  InputImageType::PixelType bound = itkImage->GetPixel(seedIndex);

  regionGrower->SetLower(bound);
  regionGrower->SetUpper(bound);
  regionGrower->SetReplaceValue(1);

  itk::BinaryFillholeImageFilter<InputImageType>::Pointer fillHolesFilter =
    itk::BinaryFillholeImageFilter<InputImageType>::New();

  fillHolesFilter->SetInput(regionGrower->GetOutput());
  fillHolesFilter->SetForegroundValue(1);

  // Store result and preview
  mitk::Image::Pointer resultImage = mitk::GrabItkImageMemory(fillHolesFilter->GetOutput());
  resultImage->SetGeometry(workingSlice->GetGeometry());
  // Get the current working color
  DataNode *workingNode(m_ToolManager->GetWorkingData(0));
  if (!workingNode)
    return;

  mitk::ImageToContourModelFilter::Pointer contourextractor = mitk::ImageToContourModelFilter::New();
  contourextractor->SetInput(resultImage);
  contourextractor->Update();

  mitk::ContourModel::Pointer awesomeContour = contourextractor->GetOutput();
  FeedbackContourTool::SetFeedbackContour(awesomeContour);
  FeedbackContourTool::SetFeedbackContourVisible(true);
  mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());
}
void QmitkAdaptiveRegionGrowingToolGUI::ITKThresholding(itk::Image<TPixel, VImageDimension>* itkImage)
{
  mitk::Image::Pointer originalSegmentation = dynamic_cast<mitk::Image*>(this->m_RegionGrow3DTool->
                                                                         GetTargetSegmentationNode()->GetData());

  int timeStep = mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1") )->GetTimeStep();

  if (originalSegmentation)
  {
    typedef itk::Image<TPixel, VImageDimension> InputImageType;
    typedef itk::Image<unsigned char, VImageDimension> SegmentationType;


    //select single 3D volume if we have more than one time step
    typename SegmentationType::Pointer originalSegmentationInITK = SegmentationType::New();
    if(originalSegmentation->GetTimeGeometry()->CountTimeSteps() > 1)
    {
      mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
      timeSelector->SetInput( originalSegmentation );
      timeSelector->SetTimeNr( timeStep );
      timeSelector->UpdateLargestPossibleRegion();
      CastToItkImage( timeSelector->GetOutput(), originalSegmentationInITK );
    }
    else //use original
    {
      CastToItkImage( originalSegmentation, originalSegmentationInITK );
    }

    //Fill current preiview image in segmentation image
    originalSegmentationInITK->FillBuffer(0);
    itk::ImageRegionIterator<SegmentationType> itOutput( originalSegmentationInITK, originalSegmentationInITK->GetLargestPossibleRegion() );
    itk::ImageRegionIterator<InputImageType> itInput( itkImage, itkImage->GetLargestPossibleRegion() );
    itOutput.GoToBegin();
    itInput.GoToBegin();

    //calculate threhold from slider value
    int currentTreshold = 0;
    if (m_CurrentRGDirectionIsUpwards)
    {
      currentTreshold = m_UPPERTHRESHOLD - m_Controls.m_PreviewSlider->value() + 1;
    }
    else
    {
      currentTreshold = m_Controls.m_PreviewSlider->value() - m_LOWERTHRESHOLD;
    }

    //iterate over image and set pixel in segmentation according to thresholded labeled image
    while( !itOutput.IsAtEnd() && !itInput.IsAtEnd() )
    {
      //Use threshold slider to determine if pixel is set to 1
      if( itInput.Value() != 0 && itInput.Value() > currentTreshold )
      {
        itOutput.Set( 1 );
      }

      ++itOutput;
      ++itInput;
    }


    //combine current working segmentation image with our region growing result
    originalSegmentation->SetVolume( (void*)(originalSegmentationInITK->GetPixelContainer()->GetBufferPointer()), timeStep);

    originalSegmentation->Modified();
    mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  }
}
Exemplo n.º 25
0
void mitk::CorrectorAlgorithm::GenerateData()
{
  Image::Pointer inputImage = const_cast<Image*>(ImageToImageFilter::GetInput(0));

  if (inputImage.IsNull() || inputImage->GetDimension() != 2)
  {
    itkExceptionMacro("CorrectorAlgorithm needs a 2D image as input.");
  }

  if (m_Contour.IsNull())
  {
    itkExceptionMacro("CorrectorAlgorithm needs a Contour object as input.");
  }

   // copy the input (since m_WorkingImage will be changed later)
  m_WorkingImage = Image::New();
  m_WorkingImage->Initialize( inputImage );
  m_WorkingImage->SetVolume( inputImage.GetPointer()->GetData() );

  if (inputImage->GetTimeSlicedGeometry() )
  {
    AffineGeometryFrame3D::Pointer originalGeometryAGF = inputImage->GetTimeSlicedGeometry()->Clone();
    TimeSlicedGeometry::Pointer originalGeometry = dynamic_cast<TimeSlicedGeometry*>( originalGeometryAGF.GetPointer() );
    m_WorkingImage->SetGeometry( originalGeometry );
  }
  else
  {
    itkExceptionMacro("Original image does not have a 'Time sliced geometry'! Cannot copy.");
  }

 
  // Convert to ipMITKSegmentationTYPE (because TobiasHeimannCorrectionAlgorithm relys on that data type)
  itk::Image< ipMITKSegmentationTYPE, 2 >::Pointer correctPixelTypeImage;
  CastToItkImage( m_WorkingImage, correctPixelTypeImage );
  assert (correctPixelTypeImage.IsNotNull() );

  // possible bug in CastToItkImage ?
  // direction maxtrix is wrong/broken/not working after CastToItkImage, leading to a failed assertion in
  // mitk/Core/DataStructures/mitkSlicedGeometry3D.cpp, 479:
  // virtual void mitk::SlicedGeometry3D::SetSpacing(const mitk::Vector3D&): Assertion `aSpacing[0]>0 && aSpacing[1]>0 && aSpacing[2]>0' failed
  // solution here: we overwrite it with an unity matrix
  itk::Image< ipMITKSegmentationTYPE, 2 >::DirectionType imageDirection;
  imageDirection.SetIdentity();
  correctPixelTypeImage->SetDirection(imageDirection);

  Image::Pointer temporarySlice = this->GetOutput();
  //  temporarySlice = ImportItkImage( correctPixelTypeImage );
  CastToMitkImage( correctPixelTypeImage, temporarySlice );

  TobiasHeimannCorrectionAlgorithm( temporarySlice->GetSliceData()->GetPicDescriptor() );

  // temporarySlice is our return value (user  can get it by calling GetOutput() )

  CalculateDifferenceImage( temporarySlice, inputImage );
  if ( m_DifferenceImage.IsNotNull() && inputImage->GetTimeSlicedGeometry() )
  {
    AffineGeometryFrame3D::Pointer originalGeometryAGF = inputImage->GetTimeSlicedGeometry()->Clone();
    TimeSlicedGeometry::Pointer originalGeometry = dynamic_cast<TimeSlicedGeometry*>( originalGeometryAGF.GetPointer() );
    m_DifferenceImage->SetGeometry( originalGeometry );
  }
  else
  {
    itkExceptionMacro("Original image does not have a 'Time sliced geometry'! Cannot copy.");
  }
}
Exemplo n.º 26
0
  static void PixelvalueBasedTestByPlane(mitk::Image* imageInMitk, mitk::PlaneGeometry::PlaneOrientation orientation){

    typedef itk::Image<unsigned short, 3> ImageType;

    //set the seed of the rand function
    srand((unsigned)time(0));

    /* setup a random orthogonal plane */
    int sliceindex = 17;//rand() % 32;
    bool isFrontside = true;
    bool isRotated = false;


                if( orientation == mitk::PlaneGeometry::Axial)
    {
      /*isFrontside = false;
      isRotated = true;*/
    }



    mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New();


    plane->InitializeStandardPlane(imageInMitk->GetGeometry(), orientation, sliceindex, isFrontside, isRotated);

    mitk::Point3D origin = plane->GetOrigin();
    mitk::Vector3D normal;
    normal = plane->GetNormal();


    normal.Normalize();

    origin += normal * 0.5;//pixelspacing is 1, so half the spacing is 0.5

    plane->SetOrigin(origin);

    //we dont need this any more, because we are only testing orthogonal planes
    /*mitk::Vector3D rotationVector;
    rotationVector[0] = randFloat();
    rotationVector[1] = randFloat();
    rotationVector[2] = randFloat();


    float degree = randFloat() * 180.0;

    mitk::RotationOperation* op = new mitk::RotationOperation(mitk::OpROTATE, plane->GetCenter(), rotationVector, degree);
    plane->ExecuteOperation(op);
    delete op;*/

    /* end setup plane */


    /* define a point in the 3D volume.
     * add the two axis vectors of the plane (each multiplied with a
     * random number) to the origin. now the two random numbers
     * become our index coordinates in the 2D image, because the
     * length of the axis vectors is 1.
     */
    mitk::Point3D planeOrigin =  plane->GetOrigin();
    mitk::Vector3D axis0, axis1;
    axis0 = plane->GetAxisVector(0);
    axis1 = plane->GetAxisVector(1);
    axis0.Normalize();
    axis1.Normalize();


    unsigned char n1 = 7;// rand() % 32;
    unsigned char n2 = 13;// rand() % 32;


    mitk::Point3D testPoint3DInWorld;
    testPoint3DInWorld = planeOrigin + (axis0 * n1) + (axis1 * n2);

    //get the index of the point in the 3D volume
    ImageType::IndexType testPoint3DInIndex;
    imageInMitk->GetGeometry()->WorldToIndex(testPoint3DInWorld, testPoint3DInIndex);

    itk::Index<3> testPoint2DInIndex;

    /* end define a point in the 3D volume.*/


    //do reslicing at the plane
    mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New();
    slicer->SetInput(imageInMitk);
    slicer->SetWorldGeometry(plane);

    slicer->Update();

    mitk::Image::Pointer slice = slicer->GetOutput();

    // Get TestPoiont3D as Index in Slice
    slice->GetGeometry()->WorldToIndex(testPoint3DInWorld,testPoint2DInIndex);


    mitk::Point3D p, sliceIndexToWorld, imageIndexToWorld;
    p[0] = testPoint2DInIndex[0];
    p[1] = testPoint2DInIndex[1];
    p[2] = testPoint2DInIndex[2];
    slice->GetGeometry()->IndexToWorld(p, sliceIndexToWorld);

    p[0] = testPoint3DInIndex[0];
    p[1] = testPoint3DInIndex[1];
    p[2] = testPoint3DInIndex[2];
    imageInMitk->GetGeometry()->IndexToWorld(p, imageIndexToWorld);

    itk::Index<2> testPoint2DIn2DIndex;
    testPoint2DIn2DIndex[0] = testPoint2DInIndex[0];
    testPoint2DIn2DIndex[1] = testPoint2DInIndex[1];

    typedef mitk::ImagePixelReadAccessor< unsigned short, 3 > VolumeReadAccessorType;
    typedef mitk::ImagePixelReadAccessor< unsigned short, 2 > SliceReadAccessorType;
    VolumeReadAccessorType VolumeReadAccessor( imageInMitk );
    SliceReadAccessorType SliceReadAccessor( slice );

    //compare the pixelvalues of the defined point in the 3D volume with the value of the resliced image
    unsigned short valueAt3DVolume = VolumeReadAccessor.GetPixelByIndex( testPoint3DInIndex );
    unsigned short valueAtSlice = SliceReadAccessor.GetPixelByIndex( testPoint2DIn2DIndex );

    //valueAt3DVolume == valueAtSlice is not always working. because of rounding errors
    //indices are shifted
    MITK_TEST_CONDITION(valueAt3DVolume == valueAtSlice, "comparing pixelvalues for orthogonal plane");


    vtkSmartPointer<vtkImageData> imageInVtk = imageInMitk->GetVtkImageData();
    vtkSmartPointer<vtkImageData> sliceInVtk = slice->GetVtkImageData();

    double PixelvalueByMitkOutput = sliceInVtk->GetScalarComponentAsDouble(n1, n2, 0, 0);
    //double valueVTKinImage = imageInVtk->GetScalarComponentAsDouble(testPoint3DInIndex[0], testPoint3DInIndex[1], testPoint3DInIndex[2], 0);


    /* Test that everything is working equally if vtkoutput is used instead of the default output
     * from mitk ImageToImageFilter
     */
    mitk::ExtractSliceFilter::Pointer slicerWithVtkOutput = mitk::ExtractSliceFilter::New();
    slicerWithVtkOutput->SetInput(imageInMitk);
    slicerWithVtkOutput->SetWorldGeometry(plane);
    slicerWithVtkOutput->SetVtkOutputRequest(true);

    slicerWithVtkOutput->Update();
    vtkSmartPointer<vtkImageData> vtkImageByVtkOutput = slicerWithVtkOutput->GetVtkOutput();
    double PixelvalueByVtkOutput = vtkImageByVtkOutput->GetScalarComponentAsDouble(n1, n2, 0, 0);

    MITK_TEST_CONDITION(PixelvalueByMitkOutput == PixelvalueByVtkOutput, "testing convertion of image output vtk->mitk by reslicer");



/*================ mbilog outputs ===========================*/
#ifdef EXTRACTOR_DEBUG
    MITK_INFO << "\n" << "TESTINFO index: " << sliceindex << " orientation: " << orientation << " frontside: " << isFrontside << " rotated: " << isRotated;
    MITK_INFO << "\n" << "slice index to world: " << sliceIndexToWorld;
    MITK_INFO << "\n" << "image index to world: "  << imageIndexToWorld;

    MITK_INFO  << "\n" << "vtk: slice: " << PixelvalueByMitkOutput << ", image: "<< valueVTKinImage;

    MITK_INFO << "\n" << "testPoint3D InWorld" << testPoint3DInWorld << " is " << testPoint2DInIndex << " in 2D";
    MITK_INFO << "\n" << "randoms: " << ((int)n1) << ", " << ((int)n2);
    MITK_INFO << "\n" << "point is inside plane: " << plane->IsInside(testPoint3DInWorld) << " and volume: " << imageInMitk->GetGeometry()->IsInside(testPoint3DInWorld);

    MITK_INFO << "\n" << "volume idx: " << testPoint3DInIndex << " = " << valueAt3DVolume ;
    MITK_INFO << "\n" << "volume world: " << testPoint3DInWorld << " = " << valueAt3DVolumeByWorld ;
    MITK_INFO << "\n" << "slice idx: " << testPoint2DInIndex << " = " << valueAtSlice ;

    itk::Index<3> curr;
    curr[0] = curr[1] = curr[2] = 0;

    for( int i = 0; i < 32 ; ++i){
      for( int j = 0; j < 32; ++j){
        ++curr[1];
        if(SliceReadAccessor.GetPixelByIndex( curr ) == valueAt3DVolume){
          MITK_INFO << "\n" << valueAt3DVolume << " MATCHED mitk " << curr;
        }
      }
      curr[1] = 0;
      ++curr[0];
    }

    typedef itk::Image<unsigned short, 2> Image2DType;

    Image2DType::Pointer img  = Image2DType::New();
    CastToItkImage(slice, img);
    typedef itk::ImageRegionConstIterator< Image2DType > Iterator2D;

    Iterator2D iter(img, img->GetLargestPossibleRegion());
    iter.GoToBegin();
    while( !iter.IsAtEnd() ){

      if(img->GetPixel(iter.GetIndex()) == valueAt3DVolume) MITK_INFO << "\n" << valueAt3DVolume << " MATCHED itk " << iter.GetIndex();

      ++iter;
    }
#endif //EXTRACTOR_DEBUG
  }
Exemplo n.º 27
0
void mitk::RegistrationWrapper::ApplyTransformationToImage(mitk::Image::Pointer img, const mitk::RegistrationWrapper::RidgidTransformType &transformation,double* offset, mitk::Image* resampleReference,  bool binary)
{
  typedef mitk::DiffusionImage<short> DiffusionImageType;

  if (dynamic_cast<DiffusionImageType*> (img.GetPointer()) == NULL)
  {

    ItkImageType::Pointer itkImage = ItkImageType::New();


    MITK_ERROR << "imgCopy  0 " <<  "/" << img->GetReferenceCount();
    MITK_ERROR << "pixel type  " << img->GetPixelType().GetComponentTypeAsString();

    CastToItkImage(img, itkImage);



    typedef itk::Euler3DTransform< double > RigidTransformType;
    RigidTransformType::Pointer rtransform = RigidTransformType::New();
    RigidTransformType::ParametersType parameters(RigidTransformType::ParametersDimension);

    for (int i = 0; i<6;++i)
      parameters[i] = transformation[i];

    rtransform->SetParameters( parameters );

    mitk::Point3D origin = itkImage->GetOrigin();
    origin[0]-=offset[0];
    origin[1]-=offset[1];
    origin[2]-=offset[2];

    mitk::Point3D newOrigin = rtransform->GetInverseTransform()->TransformPoint(origin);

    itk::Matrix<double,3,3> dir = itkImage->GetDirection();
    itk::Matrix<double,3,3> transM  ( vnl_inverse(rtransform->GetMatrix().GetVnlMatrix()));
    itk::Matrix<double,3,3> newDirection = transM * dir;

    itkImage->SetOrigin(newOrigin);
    itkImage->SetDirection(newDirection);

    // Perform Resampling if reference image is provided
    if (resampleReference != NULL)
    {
      typedef itk::ResampleImageFilter<ItkImageType, ItkImageType>  ResampleFilterType;

      ItkImageType::Pointer itkReference = ItkImageType::New();
      CastToItkImage(resampleReference,itkReference);

      typedef itk::WindowedSincInterpolateImageFunction< ItkImageType, 3> WindowedSincInterpolatorType;
      WindowedSincInterpolatorType::Pointer sinc_interpolator = WindowedSincInterpolatorType::New();

      typedef itk::NearestNeighborInterpolateImageFunction< ItkImageType, double > NearestNeighborInterpolatorType;
      NearestNeighborInterpolatorType::Pointer nn_interpolator = NearestNeighborInterpolatorType::New();


      ResampleFilterType::Pointer resampler = ResampleFilterType::New();
      resampler->SetInput(itkImage);
      resampler->SetReferenceImage( itkReference );
      resampler->UseReferenceImageOn();
      if (binary)
        resampler->SetInterpolator(nn_interpolator);
      else
        resampler->SetInterpolator(sinc_interpolator);

      resampler->Update();

      GrabItkImageMemory(resampler->GetOutput(), img);
    }
    else
    {
      // !! CastToItk behaves very differently depending on the original data type
      // if the target type is the same as the original, only a pointer to the data is set
      // and an additional GrabItkImageMemory will cause a segfault when the image is destroyed
      // GrabItkImageMemory - is not necessary in this case since we worked on the original data
      // See Bug 17538.
      if (img->GetPixelType().GetComponentTypeAsString() != "double")
        img = GrabItkImageMemory(itkImage);
    }
  }
  else
  {
    DiffusionImageType::Pointer diffImages = dynamic_cast<DiffusionImageType*>(img.GetPointer());

    typedef itk::Euler3DTransform< double > RigidTransformType;
    RigidTransformType::Pointer rtransform = RigidTransformType::New();
    RigidTransformType::ParametersType parameters(RigidTransformType::ParametersDimension);

    for (int i = 0; i<6;++i)
    {
      parameters[i] = transformation[i];
    }

    rtransform->SetParameters( parameters );

    mitk::Point3D b0origin = diffImages->GetVectorImage()->GetOrigin();
    b0origin[0]-=offset[0];
    b0origin[1]-=offset[1];
    b0origin[2]-=offset[2];

    mitk::Point3D newOrigin = rtransform->GetInverseTransform()->TransformPoint(b0origin);

    itk::Matrix<double,3,3> dir = diffImages->GetVectorImage()->GetDirection();
    itk::Matrix<double,3,3> transM  ( vnl_inverse(rtransform->GetMatrix().GetVnlMatrix()));
    itk::Matrix<double,3,3> newDirection = transM * dir;

    diffImages->GetVectorImage()->SetOrigin(newOrigin);
    diffImages->GetVectorImage()->SetDirection(newDirection);
    diffImages->Modified();

    mitk::DiffusionImageCorrectionFilter<short>::Pointer correctionFilter = mitk::DiffusionImageCorrectionFilter<short>::New();

    // For Diff. Images: Need to rotate the gradients (works in-place)
    correctionFilter->SetImage(diffImages);
    correctionFilter->CorrectDirections(transM.GetVnlMatrix());
    img = diffImages;
  }
}
Exemplo n.º 28
0
void mitk::FastMarchingTool::BuildITKPipeline()
{
  m_ReferenceImageSliceAsITK = InternalImageType::New();

  m_ReferenceImageSlice = GetAffectedReferenceSlice( m_PositionEvent );
  CastToItkImage(m_ReferenceImageSlice, m_ReferenceImageSliceAsITK);

  m_ProgressCommand = mitk::ToolCommand::New();

  m_SmoothFilter = SmoothingFilterType::New();
  m_SmoothFilter->SetInput( m_ReferenceImageSliceAsITK );
  m_SmoothFilter->SetTimeStep( 0.05 );
  m_SmoothFilter->SetNumberOfIterations( 2 );
  m_SmoothFilter->SetConductanceParameter( 9.0 );

  m_GradientMagnitudeFilter = GradientFilterType::New();
  m_GradientMagnitudeFilter->SetSigma( m_Sigma );

  m_SigmoidFilter = SigmoidFilterType::New();
  m_SigmoidFilter->SetAlpha( m_Alpha );
  m_SigmoidFilter->SetBeta( m_Beta );
  m_SigmoidFilter->SetOutputMinimum( 0.0 );
  m_SigmoidFilter->SetOutputMaximum( 1.0 );

  m_FastMarchingFilter = FastMarchingFilterType::New();
  m_FastMarchingFilter->SetStoppingValue( m_StoppingValue );

  m_ThresholdFilter = ThresholdingFilterType::New();
  m_ThresholdFilter->SetLowerThreshold( m_LowerThreshold );
  m_ThresholdFilter->SetUpperThreshold( m_UpperThreshold );
  m_ThresholdFilter->SetOutsideValue( 0 );
  m_ThresholdFilter->SetInsideValue( 1.0 );

  m_SeedContainer = NodeContainer::New();
  m_SeedContainer->Initialize();
  m_FastMarchingFilter->SetTrialPoints( m_SeedContainer );

  if (this->m_SmoothFilter.IsNotNull())
      this->m_SmoothFilter->RemoveAllObservers();

  if (this->m_SigmoidFilter.IsNotNull())
      this->m_SigmoidFilter->RemoveAllObservers();

  if (this->m_GradientMagnitudeFilter.IsNotNull())
      this->m_GradientMagnitudeFilter->RemoveAllObservers();

  if (this->m_FastMarchingFilter.IsNotNull())
      this->m_FastMarchingFilter->RemoveAllObservers();

  m_SmoothFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand);
  m_GradientMagnitudeFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand);
  m_SigmoidFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand);
  m_FastMarchingFilter->AddObserver( itk::ProgressEvent(), m_ProgressCommand);

  m_SmoothFilter->SetInput( m_ReferenceImageSliceAsITK );
  m_GradientMagnitudeFilter->SetInput( m_SmoothFilter->GetOutput() );
  m_SigmoidFilter->SetInput( m_GradientMagnitudeFilter->GetOutput() );
  m_FastMarchingFilter->SetInput( m_SigmoidFilter->GetOutput() );
  m_ThresholdFilter->SetInput( m_FastMarchingFilter->GetOutput() );
  m_ReferenceImageSliceAsITK = InternalImageType::New();
}
Exemplo n.º 29
0
static mitk::Image::Pointer ResampleBySpacing(mitk::Image *input, float *spacing, bool useLinInt = true)
{
  InputImageType::Pointer itkImage = InputImageType::New();
  CastToItkImage(input,itkImage);

  /**
   * 1) Resampling
   *
   */
  // Identity transform.
  // We don't want any transform on our image except rescaling which is not
  // specified by a transform but by the input/output spacing as we will see
  // later.
  // So no transform will be specified.
  typedef itk::IdentityTransform<double, 3> T_Transform;

  // The resampler type itself.
  typedef itk::ResampleImageFilter<InputImageType, InputImageType>  T_ResampleFilter;

  // Prepare the resampler.
  // Instantiate the transform and specify it should be the id transform.
  T_Transform::Pointer _pTransform = T_Transform::New();
  _pTransform->SetIdentity();

  // Instantiate the resampler. Wire in the transform and the interpolator.
  T_ResampleFilter::Pointer _pResizeFilter = T_ResampleFilter::New();

  // Specify the input.
  _pResizeFilter->SetInput(itkImage);

  _pResizeFilter->SetTransform(_pTransform);

  // Set the output origin.
  _pResizeFilter->SetOutputOrigin(itkImage->GetOrigin());

  // Compute the size of the output.
  // The size (# of pixels) in the output is recomputed using
  // the ratio of the input and output sizes.
  InputImageType::SpacingType inputSpacing = itkImage->GetSpacing();
  InputImageType::SpacingType outputSpacing;
  const InputImageType::RegionType& inputSize = itkImage->GetLargestPossibleRegion();

  InputImageType::SizeType outputSize;
  typedef InputImageType::SizeType::SizeValueType SizeValueType;

  // Set the output spacing.
  outputSpacing[0] = spacing[0];
  outputSpacing[1] = spacing[1];
  outputSpacing[2] = spacing[2];

  outputSize[0] = static_cast<SizeValueType>(inputSize.GetSize()[0] * inputSpacing[0] / outputSpacing[0] + .5);
  outputSize[1] = static_cast<SizeValueType>(inputSize.GetSize()[1] * inputSpacing[1] / outputSpacing[1] + .5);
  outputSize[2] = static_cast<SizeValueType>(inputSize.GetSize()[2] * inputSpacing[2] / outputSpacing[2] + .5);

  _pResizeFilter->SetOutputSpacing(outputSpacing);
  _pResizeFilter->SetSize(outputSize);

  typedef itk::LinearInterpolateImageFunction< InputImageType > LinearInterpolatorType;
  LinearInterpolatorType::Pointer lin_interpolator = LinearInterpolatorType::New();

  typedef itk::WindowedSincInterpolateImageFunction< InputImageType, 4> WindowedSincInterpolatorType;
  WindowedSincInterpolatorType::Pointer sinc_interpolator = WindowedSincInterpolatorType::New();

  if (useLinInt)
    _pResizeFilter->SetInterpolator(lin_interpolator);
  else
    _pResizeFilter->SetInterpolator(sinc_interpolator);

  _pResizeFilter->Update();

  mitk::Image::Pointer image = mitk::Image::New();
  image->InitializeByItk(_pResizeFilter->GetOutput());
  mitk::GrabItkImageMemory( _pResizeFilter->GetOutput(), image);
  return image;
}