Exemple #1
0
static HalfHermetianImageType::Pointer GetLowpassOperator(FloatImageType::Pointer norm01_lowres,
                                                           FloatImageType::Pointer p_image, const PrecisionType scaler)
{
  /*
   * Make dirac-delta impulse response filter for convolving with the high-resolution image
  The operator A should represent the characteristics of the measurement device as it
  takes measurements at lower resolutions.  For example, in MRI as resolution is decreased,
  larger anatomical regions are included in each measurement, thus giving a
  smoother image as if the high resolution image were passed through a low-pass-filter.
  p_image below represents the smoothing convolution filter that is applied to a
  high-resolution image to best represent the low-resolution image sampling.
  In the case of no downsampling p_image is simply a perfect dirac-delta function.
  Convolution in the spatial-domain is multiplication in the frequency domain.

  In the case were some downsampling is present between the lowresolution and
  the highresolution images, we need the operator A to represent a low-pass filter
  that optimally models the lower sampling rate.  The low-pass filter is accomplished
  in the frequency domain by zeroing-out frequency components that are not representable
  in the frequency domain of the low-resolution image.
   */

  HalfHermetianImageType::Pointer testA_fhp = A_fhp(p_image,norm01_lowres.GetPointer());
  FloatImageType::Pointer testAtA = At_fhp(testA_fhp,norm01_lowres->GetLargestPossibleRegion().GetSize()[0]%2 == 1, p_image.GetPointer());
  HalfHermetianImageType::Pointer AtAhat = GetForwardFFT(testAtA);
  return opIC(AtAhat,AtAhat,'*',scaler); // A is the linear measurement operator
}
void QmitkDeformableRegistrationView::ApplyDeformationField()
{

  ImageReaderType::Pointer reader  = ImageReaderType::New();
  reader->SetFileName( m_Controls.m_QmitkBSplineRegistrationViewControls->m_Controls.m_DeformationField->text().toStdString() );
  reader->Update();

  DeformationFieldType::Pointer deformationField = reader->GetOutput();

  mitk::Image * mimage = dynamic_cast<mitk::Image*> (m_MovingNode->GetData());
  mitk::Image * fimage = dynamic_cast<mitk::Image*> (m_FixedNode->GetData());

  typedef itk::Image<float, 3> FloatImageType;

  FloatImageType::Pointer itkMovingImage = FloatImageType::New();
  FloatImageType::Pointer itkFixedImage = FloatImageType::New();
  mitk::CastToItkImage(mimage, itkMovingImage);
  mitk::CastToItkImage(fimage, itkFixedImage);

  typedef itk::WarpImageFilter<
                            FloatImageType,
                            FloatImageType,
                            DeformationFieldType  >     WarperType;

  typedef itk::LinearInterpolateImageFunction<
                                    FloatImageType,
                                    double          >  InterpolatorType;

  WarperType::Pointer warper = WarperType::New();
  InterpolatorType::Pointer interpolator = InterpolatorType::New();

  warper->SetInput( itkMovingImage );
  warper->SetInterpolator( interpolator );
  warper->SetOutputSpacing( itkFixedImage->GetSpacing() );
  warper->SetOutputOrigin( itkFixedImage->GetOrigin() );
  warper->SetOutputDirection (itkFixedImage->GetDirection() );
  warper->SetDisplacementField( deformationField );
  warper->Update();

  FloatImageType::Pointer outputImage = warper->GetOutput();
  mitk::Image::Pointer result = mitk::Image::New();

  mitk::CastToMitkImage(outputImage, result);

  // Create new DataNode
  mitk::DataNode::Pointer newNode = mitk::DataNode::New();
  newNode->SetData( result );
  newNode->SetProperty( "name", mitk::StringProperty::New("warped image") );

  // add the new datatree node to the datatree
  this->GetDefaultDataStorage()->Add(newNode);
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();

  //Image::Pointer outputImage = this->GetOutput();
  //mitk::CastToMitkImage( warper->GetOutput(), outputImage );


}
int main(int argc, char**argv)
{
	typedef itk::GradientAnisotropicDiffusionImageFilter<FloatImageType, FloatImageType> FilterType;

	if(!file_exists(argv[3]))
	{
		InputImageType::Pointer im = readImage<InputImageType>(argv[1]);

		typedef itk::CastImageFilter<InputImageType,FloatImageType> CastFilter;
		typedef itk::CastImageFilter<FloatImageType,InputImageType> ReverseCastFilter;
		FilterType::Pointer filter = FilterType::New();


		CastFilter::Pointer cfilter = CastFilter::New();
		cfilter->SetInput(im);
		filter->SetInput(cfilter->GetOutput());

		int num_i;
		float time_step;
		float conductance;
		sscanf(argv[2],"%d,%f,%f",&num_i,&time_step,&conductance);
		printf("time_step %f num_i %d conductance %f\n",time_step,num_i,conductance);
		filter->SetTimeStep(time_step);
		filter->SetNumberOfIterations(num_i);
		filter->SetConductanceParameter(conductance);
		filter->Update();

		FloatImageType::Pointer imf = filter->GetOutput();
		typedef itk::ImageRegionIterator<FloatImageType> IRI;
		IRI imageIterator(imf,imf->GetLargestPossibleRegion());
		for(imageIterator.GoToBegin();!imageIterator.IsAtEnd(); ++imageIterator)
		{
			float value = imageIterator.Get();
			value = ((value < 0)?0:((value>255)?255:value));
			imageIterator.Set(value);
		}

		ReverseCastFilter::Pointer rfilter = ReverseCastFilter::New();
		rfilter->SetInput(filter->GetOutput());
		rfilter->Update();
		writeImage<InputImageType>(rfilter->GetOutput(),argv[3]);
	}

	return 0;
}
Exemple #4
0
// (2*mu+gam)^{-1}
static CVImageType::Pointer ComputeInvTwoMuPlusGamma( FloatImageType::Pointer edgemask,  const PrecisionType gam)
{
  CVImageType::Pointer repMu = CreateEmptyImage<CVImageType>(edgemask);
  itk::ImageRegionIterator<CVImageType> cvIt(repMu,repMu->GetLargestPossibleRegion());
  itk::ImageRegionConstIterator<FloatImageType> muIt(edgemask,edgemask->GetLargestPossibleRegion());
  CVImageType::PixelType temp;
  while(!muIt.IsAtEnd())
  {
    cvIt.Set( 1.0 / ( 2.0*muIt.Value() + gam) );
    ++cvIt;
    ++muIt;
  }
  return repMu;
}
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();
}
  void TractAnalyzer::MakeRoi()
  {

    m_CostSum = 0.0;

    int n = 0;
    if(m_PointSetNode.IsNotNull())
    {
      n = m_PointSetNode->GetSize();
      if(n==0)
      {
        QMessageBox msgBox;
        msgBox.setText("No points have been set yet.");
        msgBox.exec();
      }
    }
    else{
      QMessageBox msgBox;
      msgBox.setText("No points have been set yet.");
      msgBox.exec();
    }

    std::string pathDescription = "";
    std::vector< itk::Index<3> > totalPath;

    if(n>0)
    {
      for(int i=0; i<n-1; ++i)
      {

        mitk::ProgressBar::GetInstance()->Progress();

        mitk::Point3D p = m_PointSetNode->GetPoint(i);
        mitk::Point3D p2 = m_PointSetNode->GetPoint(i+1);


        itk::Index<3> startPoint;
        itk::Index<3> endPoint;

        m_InputImage->GetGeometry()->WorldToIndex(p,startPoint);
        m_InputImage->GetGeometry()->WorldToIndex(p2,endPoint);

        MITK_INFO << "create roi";

        std::vector< itk::Index<3> > path = CreateSegment(startPoint, endPoint);

        for(std::vector< itk::Index<3> >::iterator it = path.begin();
            it != path.end(); it++)
        {
          itk::Index<3> ix = *it;

          if (!(ix==endPoint))
          {
            mitk::ProgressBar::GetInstance()->Progress();

            totalPath.push_back(ix);
            std::stringstream ss;
            ss << ix[0] << " " << ix[1] << " " << ix[2] << "\n";
            pathDescription += ss.str();
          }
          else
          {
            // Only when dealing with the last segment the last point should be added. This one will not occur
            // as the first point of the next roi segment.
            if(i == (n-2))
            {
              totalPath.push_back(endPoint);
              std::stringstream ss;
              ss << endPoint[0] << " " << endPoint[1] << " " << endPoint[2] << "\n";
              pathDescription += ss.str();
            }

          }

        }

      }


      // save pathDescription to m_PathDescription
      m_PathDescription = pathDescription;

      FloatImageType::Pointer itkImg = FloatImageType::New();
      mitk::CastToItkImage(m_InputImage, itkImg);

      CharImageType::Pointer roiImg = CharImageType::New();
      roiImg->SetRegions(itkImg->GetLargestPossibleRegion().GetSize());
      roiImg->SetOrigin(itkImg->GetOrigin());
      roiImg->SetSpacing(itkImg->GetSpacing());
      roiImg->SetDirection(itkImg->GetDirection());
      roiImg->Allocate();
      roiImg->FillBuffer(0);


      std::vector< itk::Index<3> > roi;

      std::vector< itk::Index<3> >::iterator it;
      for(it = totalPath.begin();
          it != totalPath.end();
          it++)
      {
        itk::Index<3> ix = *it;
        roiImg->SetPixel(ix, 1);
        roi.push_back(ix);
      }


      m_TbssRoi = mitk::TbssRoiImage::New();

      m_TbssRoi->SetRoi(roi);

      m_TbssRoi->SetImage(roiImg);

      m_TbssRoi->InitializeFromImage();



    }



  }
Exemple #7
0
void TubeDetection::calcMedialness()
{
    unsigned x,y,z;
    HessianFilter::OutputImageType::IndexType index;
    unsigned int x_size;
    unsigned int y_size;
    unsigned int z_size;



    float V[3][3];
    float d[3];

    FloatImageType::Pointer medialnessimage;

    std::cout << "Starting calculating medialness for level: ";


    for(unsigned i = 0; i < this->imagePyramid.size(); i++)
    {
        std::cout << i << " " << std::endl;

        //medialnessimage = imagePyramid.at(i)->Clone();
        DuplicatorType::Pointer duplicator = DuplicatorType::New();
        duplicator->SetInputImage(imagePyramid.at(i));
        duplicator->Update();

        medialnessimage = duplicator->GetOutput();

        x_size = imagePyramid.at(i)->GetLargestPossibleRegion().GetSize(0);
        y_size = imagePyramid.at(i)->GetLargestPossibleRegion().GetSize(1);
        z_size = imagePyramid.at(i)->GetLargestPossibleRegion().GetSize(2);

        for(x = 0; x < x_size ; x++)
        {
            index[0] = x;

            if(x % 10 == 0)
              std::cout << "x = " << x << std::endl;

            for(y = 0; y < y_size; y++)
            {
                index[1] = y;

                for(z = 0; z < z_size; z++)
                {
                    //Indices for gradient, forward differences
                    index[2] = z;


                    eigenValueDecomposition(i, index, V, d);

                    float medialness = calcMedialness(i, x, y, z, d, V);

                    medialnessimage->SetPixel(index, medialness);
                }
            }
        }

        medialnessImages.push_back(medialnessimage);
    }

    std::cout << std::endl << "Finished calculation of medialness" << std::endl;
}
void 
rich_cell::
update_texture( ImageType::Pointer image )
{
  // Compute the gradient magnitude
  GradMagFilterType::Pointer gmFilter = GradMagFilterType::New();
  gmFilter->SetInput( image );
  try {
    gmFilter->Update();
  }
  catch (itk::ExceptionObject & e) {
      std::cerr << "Exception in SubFilter: " << e << std::endl;
      exit(0);
  }
  FloatImageType::Pointer gmImage = gmFilter->GetOutput();

  // Compute the texture as the average gradient of the first portion
  // of the sorted gradient magnitudes.

  std::cout<<"class = "<<class_type_<<std::endl;
  double interior_grad = 0;
  std::vector< float > grad_magnitudes;
  grad_magnitudes.reserve(interior_points_.size());
  FloatImageType::IndexType ind;
  for (unsigned int i = 0; i<interior_points_.size(); i++) {
    ind[0] = interior_points_[i][0];
    ind[1] = interior_points_[i][1];
    ind[2] = interior_points_[i][2];
    //interior_grad += gmImage->GetPixel( ind );
    //std::cout<<interior_points_[i]<<", grad_mag = "<<gmImage->GetPixel( ind )<<std::endl;
    grad_magnitudes.push_back(gmImage->GetPixel( ind ));
  }
  
  /*
  std::vector<float>::iterator loc = grad_magnitudes.begin()+interior_points_.size()/2;
  std::nth_element(grad_magnitudes.begin(), loc, grad_magnitudes.end());
  //texture_ = interior_grad/(double)interior_points_.size();
  */
  std::vector<float>::iterator loc = grad_magnitudes.begin()+grad_magnitudes.size()/2;
  std::partial_sort(grad_magnitudes.begin(), loc, grad_magnitudes.end());
  for (std::vector<float>::iterator itr=grad_magnitudes.begin(); itr<loc; itr++) {
    interior_grad += *itr;
  }
  texture_ = interior_grad/grad_magnitudes.size()*2;
  //std::cout<<"texture = "<<texture_<<std::endl;

  /*
  image->SetRequestedRegion( bounding_box_ );
  
  int radius = 1; //for both median filtering and structuring element

  //set neighborhood
  ImageType::SizeType miIndexRadius;
  
  miIndexRadius[0] = radius; // radius along x
  miIndexRadius[1] = radius; // radius along y
  miIndexRadius[2] = 0;	// radius along z
  MedianFilterType::Pointer f_med = MedianFilterType::New();
  
  //set radius and input
  f_med->SetRadius( miIndexRadius );
  f_med->SetInput( image );
  
  OpenFilterType::Pointer f_open = OpenFilterType::New();
  ErodeFilterType::Pointer  f_erode  = ErodeFilterType::New();
  DilateFilterType::Pointer f_dilate = DilateFilterType::New();
  SubFilterType::Pointer f_sub = SubFilterType::New();
  
  StructuringElementType  structuringElement;
  structuringElement.SetRadius( radius );
  structuringElement.CreateStructuringElement();
  
  f_open->SetKernel( structuringElement );
  f_erode->SetKernel(  structuringElement );
  f_dilate->SetKernel( structuringElement );

  //connect open to medium filter
  f_open->SetInput( f_med->GetOutput() );
  f_erode->SetInput(  f_open->GetOutput() );
  f_dilate->SetInput( f_open->GetOutput() ); 

  //set inputs of substract filter for morphological gradient
  //(dilation-erosion=morphological gradient)
  f_sub->SetInput1( f_dilate->GetOutput() );
  f_sub->SetInput2( f_erode->GetOutput() );

  try
    {
      f_sub->Update();
    }
  catch (itk::ExceptionObject & e)
    {
      std::cerr << "Exception in SubFilter: " << e << std::endl;
      exit(0);
    }

  // Now we can compute the gradient values!
  ImageType::Pointer morph_image = f_sub->GetOutput();
  double interior_grad = 0;
  ImageType::IndexType ind;
  for (unsigned int i = 0; i<interior_points_.size(); i++) {
    ind[0] = interior_points_[i][0];
    ind[1] = interior_points_[i][1];
    ind[2] = interior_points_[i][2];
    interior_grad += morph_image->GetPixel( ind );
  }
  texture_ = interior_grad/(double)interior_points_.size();
  */

  /*
  double bdry_grad = 0;
  for (unsigned int i = 0; i<cell->boundary_points_.size(); i++) {
    ind[0] = cell->interior_points_[i][0];
    ind[1] = cell->interior_points_[i][1];
    ind[2] = cell->interior_points_[i][2];
    bdry_grad += morph_image->GetPixel( ind );
  }
  cell->ave_bound_gradient_ = vol_grad/(double)cell->boundary_points_.size();
  */
}
Exemple #9
0
/*
OPWEIGHTEDL2: Solves weighted L2 regularized inverse problems.
Minimizes the cost function
X* = argmin_X ||A(X)-b_FC||_2^2 + lambda ||W |D(X)| ||_2^2
where     X* = recovered image
          A  = linear measurement operator
          b_FC  = (noisy) measurements
                 %           W  = diagonal weight matrix built from the edge mask
          |D(X)| = gradient magnitude at each pixel

Inputs:  A = function handle representing the forward
              model/measurement operator
         At = function handle representing the backwards model/
              the transpose of the measurment operator.
              (e.g. if A is a downsampling, At is a upsampling)
         b_FC =  a vector of measurements; should match the
              dimensions of A(X)
         lambda = regularization parameter that balances data fidelity
              and smoothness. set lambda high for more smoothing.
         siz = output image size, e.g. siz = [512,512]
         Niter = is the number of iterations; should be ~100-500

Output:  X = high-resolution output image
         cost = array of cost function value vs. iteration
Define AtA fourier mask
PrecisionType lambda, uvec ind_samples, frowvec res, int Niter, double tol, PrecisionType gam, FloatImageType::Pointer& X, frowvec& cost, frowvec& resvec)
 */
FloatImageType::Pointer OpWeightedL2(FloatImageType::Pointer norm01_lowres, FloatImageType::Pointer edgemask)
{
  const PrecisionType lambda = 1e-3F ;
  constexpr int Niter = 100;
  const PrecisionType tol = 1e-8F ;

  const PrecisionType gam = 1.0F ;

  //typedef itk::VectorMagnitudeImageFilter<CVImageType, FloatImageType> GMType;

  //The optimal filter for modeling the measurement operator is low pass filter in this case
  // NOTE: That the A operator is a projection operator, so A^{T}A = A, That is to say that applying
  //       the A^{T} to A results in A.
  FloatImageType::Pointer p_image = GetDiracDeltaImage(edgemask);
  // Precompute

  //Make high-res coefficients
  const HalfHermetianImageType::Pointer b_FC = GetAFP_of_b(norm01_lowres, edgemask);
  //TODO: too many copies of Atb here.
  FloatImageType::Pointer Atb = At_fhp(b_FC,
                                       edgemask->GetLargestPossibleRegion().GetSize()[0]%2 == 1,
                                       edgemask.GetPointer());
  FloatImageType::Pointer TwoAtb = MakeTwoAtb(Atb);
  FloatImageType::Pointer X = DeepImageCopy<FloatImageType>(Atb);
  Atb = nullptr; //Save memory here

  CVImageType::Pointer DX = GetGradient(X);
  CVImageType::Pointer L = CreateEmptyImage<CVImageType>(DX);
  CVImageType::Pointer Y = CreateEmptyImage<CVImageType>(DX);
  //CVImageType::Pointer WDX = CreateEmptyImage<CVImageType>(DX);
  CVImageType::Pointer residue = CreateEmptyImage<CVImageType>(DX);
  CVImageType::Pointer YminusL = CreateEmptyImage<CVImageType>(DX);
  FloatImageType::Pointer tempValue=CreateEmptyImage<FloatImageType>(DX);

  std::vector<PrecisionType> resvec(Niter,0);
  std::vector<PrecisionType> cost(Niter,0);

#ifdef USE_WRITE_DEGUBBING
  itk::ComplexToModulusImageFilter<HalfHermetianImageType,FloatImageType>::Pointer cpx2abs =
  itk::ComplexToModulusImageFilter<HalfHermetianImageType,FloatImageType>::New();
#endif

  CVImageType::Pointer gradIm = GetGradient(p_image);
  FloatImageType::Pointer divIm = GetDivergence(gradIm);
  HalfHermetianImageType::Pointer DtDhat = GetForwardFFT(divIm);
  // TODO:  ALL SAME TO HERE!
  typedef HalfHermetianImageType::PixelType FCType;
  HalfHermetianImageType::Pointer TwoTimesAtAhatPlusLamGamDtDhat = CreateEmptyImage<HalfHermetianImageType>(DtDhat);
  {
    HalfHermetianImageType::Pointer TwoTimesAtAhat = GetLowpassOperator(norm01_lowres,p_image, 2.0F);
    TwoTimesAtAhatPlusLamGamDtDhat = opIC(TwoTimesAtAhatPlusLamGamDtDhat,FCType(lambda*gam),'*',DtDhat);
    //TODO:  Make This an inverse!
    TwoTimesAtAhatPlusLamGamDtDhat = opII(TwoTimesAtAhatPlusLamGamDtDhat,TwoTimesAtAhat,'+',TwoTimesAtAhatPlusLamGamDtDhat);
  }
  p_image = nullptr; //Save memory

  const bool edgemask_ActualXDimensionIsOdd = edgemask->GetLargestPossibleRegion().GetSize()[0] % 2 == 1;

  CVImageType::Pointer InvTwoMuPlusGamma = ComputeInvTwoMuPlusGamma(edgemask,gam);
  //FloatImageType::Pointer SqrtMu = ComputeSqrtMu(edgemask);

#define USE_BLAS_WRAPPERS
#ifdef USE_BLAS_WRAPPERS
#else
  typedef itk::AddImageFilter<CVImageType,CVImageType> CVImageAdder;
  CVImageAdder::Pointer dxPlusL = CVImageAdder::New();
#endif

  itk::TimeProbe tp;
  tp.Start();

  HalfHermetianImageType::Pointer tempRatioFC = CreateEmptyImage<HalfHermetianImageType>(DtDhat);

  for (size_t i=0; i < Niter; ++i)
  {
    std::cout << "Iteration : " << i << std::endl;

#ifdef USE_BLAS_WRAPPERS
    //Z = 1.0*L+DX
    AddAllElements(DX,1.0F,L,DX,gam);//DX destroyed
    CVImageType::Pointer & Z = DX;
#else
    //Z = opII(Z,DX,'+',L);
    dxPlusL->SetInput1(DX);
    dxPlusL->SetInput2(L);
    dxPlusL->SetInPlace(true);
    dxPlusL->Update();
    CVImageType::Pointer Z=dxPlusL->GetOutput();
    MultiplyCVByScalar(Z,gam);
#endif
#ifdef USE_BLAS_WRAPPERS
    //Y=InvTwoMuPlusGamm.*Z
    MultiplyVectors(Y,InvTwoMuPlusGamma,Z);
#else
    Y = opII(Y,Z,'*',InvTwoMuPlusGamma);
#endif

    // X Subprob
    // Numerator = 2*Atb+lambda*gam*SRdiv(Y-L))
#ifdef USE_BLAS_WRAPPERS
    //YminusL = 1.0F* SRdiv( -1.0F*L + Y)
    Duplicate(Y,YminusL);
    AddAllElements(YminusL,-1.0F,L,YminusL,1.0F);
#else
    YminusL=opII(YminusL,Y,'-',L);
#endif
    FloatImageType::Pointer tempNumerator=GetDivergence(YminusL);
#ifdef USE_BLAS_WRAPPERS
    //lambd*gam*tempNumerator+TwoAtb
    Duplicate(TwoAtb,tempValue);
    AddAllElements(tempValue,lambda*gam,tempNumerator,tempValue,1.0F);
    HalfHermetianImageType::Pointer tempNumeratorFC = GetForwardFFT(tempValue);
#else
    tempNumerator=opIC(tempNumerator,lambda*gam,'*',tempNumerator);
    tempNumerator=opII(tempNumerator,TwoAtb,'+',tempNumerator);
    HalfHermetianImageType::Pointer tempNumeratorFC = GetForwardFFT(tempNumerator);
#endif

    //KEEP
    tempRatioFC = opII_scalar(tempRatioFC,tempNumeratorFC,'/',TwoTimesAtAhatPlusLamGamDtDhat);

    X = GetInverseFFT(tempRatioFC,edgemask_ActualXDimensionIsOdd,1.0); //TODO: Determine scale factor here. X

    // should be on same dynamic range as b
    DX = GetGradient(X);
    residue = opII(residue, DX, '-', Y); //TODO:  Implement math graph output here
    L = opII(L,L,'+',residue);

    //
    resvec[i] = 0; //TODO: Figure out the math for here
    if ( i > 900000 )
    {
      tp.Stop();
      std::cout << " Only iterations " << tp.GetTotal() << tp.GetUnit() << std::endl;
      return X;
    }
    if( i > 99 ) //HACK: Cutting this function short
    {
      return X;
    }
    //WDX = opII_CVmult(WDX,SqrtMu,'*',DX);
    //diff = opII(diff,A_fhp(X,norm01_lowres.GetPointer()),'-',b_FC);
    //
    //cost[i] = 0; //TODO: Need to figure out math for here
  }
  return X;
}
Exemple #10
0
static HalfHermetianImageType::Pointer GetAFP_of_b(FloatImageType::Pointer norm01_lowres, FloatImageType::Pointer edgemask)
{
  FloatImageType::Pointer upsampledB = IdentityResampleByFFT(norm01_lowres, edgemask.GetPointer());
  HalfHermetianImageType::Pointer b_FC = A_fhp(upsampledB, norm01_lowres.GetPointer());
  return b_FC;
}
  bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source, float& computedEnergy) const override
  {
    itk::Index<2> targetPixel = ITKHelpers::CreateIndex(target);
    itk::ImageRegion<2> targetRegion = ITKHelpers::GetRegionInRadiusAroundPixel(targetPixel, HalfWidth);

    itk::Index<2> sourcePixel = ITKHelpers::CreateIndex(source);
    itk::ImageRegion<2> sourceRegion = ITKHelpers::GetRegionInRadiusAroundPixel(sourcePixel, HalfWidth);

    typedef itk::Image<float, 2> FloatImageType;
    
    typedef itk::VectorMagnitudeImageFilter<TImage, FloatImageType> VectorMagnitudeFilterType;
    typename VectorMagnitudeFilterType::Pointer magnitudeFilter = VectorMagnitudeFilterType::New();
    magnitudeFilter->SetInput(Image);
    magnitudeFilter->Update();

    std::vector<itk::Offset<2> > validOffsets = MaskImage->GetValidOffsetsInRegion(targetRegion);

    FloatImageType::Pointer sourceImage = FloatImageType::New();
//     sourceImage->SetRegions(ITKHelpers::CornerRegion(sourceRegion.GetSize()));
//     sourceImage->Allocate();
    ITKHelpers::ExtractRegion(magnitudeFilter->GetOutput(), sourceRegion, sourceImage.GetPointer());

    FloatImageType::Pointer targetImage = FloatImageType::New();
//     sourceImage->SetRegions(ITKHelpers::CornerRegion(targetRegion.GetSize()));
//     sourceImage->Allocate();
    ITKHelpers::ExtractRegion(magnitudeFilter->GetOutput(), targetRegion, targetImage.GetPointer());

    std::vector<itk::Index<2> > validIndices = ITKHelpers::OffsetsToIndices(validOffsets);

    VarianceFunctor varianceFunctor;
    AverageFunctor averageFunctor;
    /////////// Target region //////////
    std::vector<FloatImageType::PixelType> validPixelsTargetRegion = ITKHelpers::GetPixelValues(targetImage.GetPointer(), validIndices);
    typename TypeTraits<FloatImageType::PixelType>::LargerType targetMean = averageFunctor(validPixelsTargetRegion);
    typename TypeTraits<FloatImageType::PixelType>::LargerType targetStandardDeviation = sqrt(varianceFunctor(validPixelsTargetRegion));

    typedef itk::AddImageFilter <FloatImageType, FloatImageType, FloatImageType> AddImageFilterType;
    AddImageFilterType::Pointer targetAddImageFilter = AddImageFilterType::New();
    targetAddImageFilter->SetInput(targetImage);
    targetAddImageFilter->SetConstant2(-1.0f * targetMean);
    targetAddImageFilter->Update();

    typedef itk::MultiplyImageFilter<FloatImageType, FloatImageType, FloatImageType> MultiplyImageFilterType;
    MultiplyImageFilterType::Pointer targetMultiplyImageFilter = MultiplyImageFilterType::New();
    targetMultiplyImageFilter->SetInput(targetImage);
    targetMultiplyImageFilter->SetConstant(1.0f/targetStandardDeviation);
    targetMultiplyImageFilter->Update();

    /////////// Source region //////////
    std::vector<FloatImageType::PixelType> validPixelsSourceRegion = ITKHelpers::GetPixelValues(sourceImage.GetPointer(), validIndices);
    typename TypeTraits<FloatImageType::PixelType>::LargerType sourceMean = averageFunctor(validPixelsSourceRegion);
    typename TypeTraits<FloatImageType::PixelType>::LargerType sourceStandardDeviation = sqrt(varianceFunctor(validPixelsSourceRegion));

    AddImageFilterType::Pointer sourceAddImageFilter = AddImageFilterType::New();
    sourceAddImageFilter->SetInput(sourceImage);
    sourceAddImageFilter->SetConstant2(-1.0f * sourceMean);
    sourceAddImageFilter->Update();

    MultiplyImageFilterType::Pointer sourceMultiplyImageFilter = MultiplyImageFilterType::New();
    sourceMultiplyImageFilter->SetInput(sourceImage);
    sourceMultiplyImageFilter->SetConstant(1.0f/sourceStandardDeviation);
    sourceMultiplyImageFilter->Update();

    // Initialize
    computedEnergy = 0.0f;
    
    for(std::vector<itk::Index<2> >::const_iterator iter = validIndices.begin(); iter != validIndices.end(); ++iter)
    {
      computedEnergy += (sourceMultiplyImageFilter->GetOutput()->GetPixel(*iter) * targetMultiplyImageFilter->GetOutput()->GetPixel(*iter));
    }

    computedEnergy /= static_cast<float>(validIndices.size());

    if(computedEnergy < Threshold)
      {
      std::cout << this->VisitorName << ": Match accepted (" << computedEnergy << " is less than " << Threshold << ")" << std::endl << std::endl;
      return true;
      }
    else
      {
      std::cout << this->VisitorName << ": Match rejected (" << computedEnergy << " is greater than " << Threshold << ")" << std::endl << std::endl;
      return false;
      }
  };
Exemple #12
0
static void
ExtractSlicesFromImages(mitk::Image::Pointer image, mitk::Image::Pointer mask,
                        mitk::Image::Pointer maskNoNaN, mitk::Image::Pointer morphMask,
                        int direction,
                        std::vector<mitk::Image::Pointer> &imageVector,
                        std::vector<mitk::Image::Pointer> &maskVector,
                        std::vector<mitk::Image::Pointer> &maskNoNaNVector,
                        std::vector<mitk::Image::Pointer> &morphMaskVector)
{
  typedef itk::Image< double, 2 >                 FloatImage2DType;
  typedef itk::Image< unsigned short, 2 >          MaskImage2DType;

  FloatImageType::Pointer itkFloat = FloatImageType::New();
  MaskImageType::Pointer itkMask = MaskImageType::New();
  MaskImageType::Pointer itkMaskNoNaN = MaskImageType::New();
  MaskImageType::Pointer itkMorphMask = MaskImageType::New();
  mitk::CastToItkImage(mask, itkMask);
  mitk::CastToItkImage(maskNoNaN, itkMaskNoNaN);
  mitk::CastToItkImage(image, itkFloat);
  mitk::CastToItkImage(morphMask, itkMorphMask);

  int idxA, idxB, idxC;
  switch (direction)
  {
  case 0:
    idxA = 1; idxB = 2; idxC = 0;
    break;
  case 1:
    idxA = 0; idxB = 2; idxC = 1;
    break;
  case 2:
    idxA = 0; idxB = 1; idxC = 2;
    break;
  default:
    idxA = 1; idxB = 2; idxC = 0;
    break;
  }

  auto imageSize = image->GetLargestPossibleRegion().GetSize();
  FloatImageType::IndexType index3D;
  FloatImage2DType::IndexType index2D;
  FloatImage2DType::SpacingType spacing2D;
  spacing2D[0] = itkFloat->GetSpacing()[idxA];
  spacing2D[1] = itkFloat->GetSpacing()[idxB];

  for (unsigned int i = 0; i < imageSize[idxC]; ++i)
  {
    FloatImage2DType::RegionType region;
    FloatImage2DType::IndexType start;
    FloatImage2DType::SizeType size;
    start[0] = 0; start[1] = 0;
    size[0] = imageSize[idxA];
    size[1] = imageSize[idxB];
    region.SetIndex(start);
    region.SetSize(size);

    FloatImage2DType::Pointer image2D = FloatImage2DType::New();
    image2D->SetRegions(region);
    image2D->Allocate();

    MaskImage2DType::Pointer mask2D = MaskImage2DType::New();
    mask2D->SetRegions(region);
    mask2D->Allocate();

    MaskImage2DType::Pointer masnNoNaN2D = MaskImage2DType::New();
    masnNoNaN2D->SetRegions(region);
    masnNoNaN2D->Allocate();

    MaskImage2DType::Pointer morph2D = MaskImage2DType::New();
    morph2D->SetRegions(region);
    morph2D->Allocate();


    unsigned long voxelsInMask = 0;

    for (unsigned int a = 0; a < imageSize[idxA]; ++a)
    {
      for (unsigned int b = 0; b < imageSize[idxB]; ++b)
      {
        index3D[idxA] = a;
        index3D[idxB] = b;
        index3D[idxC] = i;
        index2D[0] = a;
        index2D[1] = b;
        image2D->SetPixel(index2D, itkFloat->GetPixel(index3D));
        mask2D->SetPixel(index2D, itkMask->GetPixel(index3D));
        masnNoNaN2D->SetPixel(index2D, itkMaskNoNaN->GetPixel(index3D));
        morph2D->SetPixel(index2D, itkMorphMask->GetPixel(index3D));
        voxelsInMask += (itkMask->GetPixel(index3D) > 0) ? 1 : 0;

      }
    }

    image2D->SetSpacing(spacing2D);
    mask2D->SetSpacing(spacing2D);
    masnNoNaN2D->SetSpacing(spacing2D);
    morph2D->SetSpacing(spacing2D);

    mitk::Image::Pointer tmpFloatImage = mitk::Image::New();
    tmpFloatImage->InitializeByItk(image2D.GetPointer());
    mitk::GrabItkImageMemory(image2D, tmpFloatImage);

    mitk::Image::Pointer tmpMaskImage = mitk::Image::New();
    tmpMaskImage->InitializeByItk(mask2D.GetPointer());
    mitk::GrabItkImageMemory(mask2D, tmpMaskImage);

    mitk::Image::Pointer tmpMaskNoNaNImage = mitk::Image::New();
    tmpMaskNoNaNImage->InitializeByItk(masnNoNaN2D.GetPointer());
    mitk::GrabItkImageMemory(masnNoNaN2D, tmpMaskNoNaNImage);

    mitk::Image::Pointer tmpMorphMaskImage = mitk::Image::New();
    tmpMorphMaskImage->InitializeByItk(morph2D.GetPointer());
    mitk::GrabItkImageMemory(morph2D, tmpMorphMaskImage);

    if (voxelsInMask > 0)
    {
      imageVector.push_back(tmpFloatImage);
      maskVector.push_back(tmpMaskImage);
      maskNoNaNVector.push_back(tmpMaskNoNaNImage);
      morphMaskVector.push_back(tmpMorphMaskImage);
    }
  }
}
InputImageType::Pointer Curvelet::RunOnInputImage(InputImageType::Pointer InputImage)
{
	//InputImage = NewInputImage;
	slices = InputImage->GetLargestPossibleRegion().GetSize()[2];
	InputImageType::Pointer outputim = InputImageType::New();
	outputim->SetRegions(InputImage->GetLargestPossibleRegion());
	outputim->Allocate();
	FloatImageType::Pointer cosim = FloatImageType::New();
	cosim->SetRegions(InputImage->GetLargestPossibleRegion());
	cosim->Allocate();
	FloatImageType::Pointer sinim = FloatImageType::New();
	sinim->SetRegions(InputImage->GetLargestPossibleRegion());
	sinim->Allocate();

	if(outputim->GetBufferPointer() == NULL || cosim->GetBufferPointer() == NULL || sinim->GetBufferPointer() == NULL)
	{
		printf("Couldnt' allocate memory - 3.. going to crash now\n");
	}
	int max_dim = tile_size;


	int xsize = InputImage->GetLargestPossibleRegion().GetSize()[0];
	int ysize = InputImage->GetLargestPossibleRegion().GetSize()[1];

	int kx = 0;int ky = 0;


	kx = xsize /(max_dim-this->border);
	ky = ysize /(max_dim-this->border);

	int remx = xsize % (max_dim-this->border);
	int remy = ysize % (max_dim-this->border);

	if ( remx > 0 )
		kx ++;
	if ( remy > 0 )
		ky ++;

	for(int xco = 0; xco < kx; xco++)
	{
		for(int yco = 0; yco < ky; yco++)
		{

			InputImageType::SizeType imsize = InputImage->GetLargestPossibleRegion().GetSize();
			InputImageType::IndexType index;
			InputImageType::SizeType size;
			InputImageType::RegionType region;

			index.Fill(0);
			size[0] =  MIN((xco)*(max_dim-this->border)+max_dim-1,imsize[0]-1) -  xco * (max_dim-this->border) +1;
			size[1] =  MIN((yco)*(max_dim-this->border)+max_dim-1,imsize[1]-1) -  yco * (max_dim-this->border) +1;
			size[2] = imsize[2];

			InputImageType::Pointer imtile = InputImageType::New();
			region.SetIndex(index);
			region.SetSize(size);
			imtile->SetRegions(region);
			imtile->Allocate();
			if(imtile->GetBufferPointer()==NULL)
				printf("Couldn't allocate memory - 4 .. going to crash now\n");
			InputImageType::RegionType region1;
			index[0] = xco *(max_dim-this->border);
			index[1] = yco *(max_dim-this->border);
			index[2] = 0;
			region1.SetIndex(index);
			region1.SetSize(size);

			typedef itk::ImageRegionIterator<InputImageType> IteratorType;
			IteratorType iter1(InputImage,region1);
			IteratorType iter2(imtile,region);


			//printf("xco = %d yco = %d :\n",xco,yco);
			region1.Print(std::cout);
			region.Print(std::cout);

			iter1.GoToBegin();
			iter2.GoToBegin();
			for(;!iter1.IsAtEnd();++iter1,++iter2)
			{
				iter2.Set(iter1.Get());
			}


			InputImageType::Pointer outputtile = InputImageType::New();
			outputtile->SetRegions(imtile->GetLargestPossibleRegion());
			outputtile->Allocate();
			FloatImageType::Pointer cosimtile = FloatImageType::New();
			cosimtile->SetRegions(imtile->GetLargestPossibleRegion());
			cosimtile->Allocate();
			FloatImageType::Pointer sinimtile = FloatImageType::New();
			sinimtile->SetRegions(imtile->GetLargestPossibleRegion());
			sinimtile->Allocate();
			if(outputtile->GetBufferPointer() == NULL || cosimtile->GetBufferPointer()==NULL || sinimtile->GetBufferPointer() == NULL )
			{
				printf("Couldn't allocate memory - 5 .. going to crash now ..\n");
			}

			{
#pragma omp parallel for shared(cosimtile,imtile,sinimtile,outputtile)  num_threads(numt)
				for(int counter = 0; counter < slices; counter++)
				{
					//printf("Counter = %d\n",counter);
					Input2DImageType::Pointer im2d = getSlice(imtile,counter);
					Input2DImageType::Pointer om2d;
					Float2DImageType::Pointer cosim2d,sinim2d;
					//call single slice 2-d curvelets function
					getCurveletsForOneSlice(im2d,om2d,cosim2d,sinim2d);
					copyslice<InputPixelType>(om2d,outputtile,counter);
					copyslice<float>(cosim2d,cosimtile,counter);
					copyslice<float>(sinim2d,sinimtile,counter);
				}
			}
			
			//printf("copying the tile\n");
			if(xco != 0)
			{
				size[0] = size[0] - border/2;
				index[0] = border/2;
			}
			if(xco != kx-1)
			{
				size[0] = size[0] - border/2;
			}

			if(yco != 0)
			{
				size[1] = size[1] - border/2;
				index[1] = border/2;
			}
			if(yco != ky-1)
			{
				size[1] = size[1] - border/2;
			}
			size[2] = slices;
			index[2] = 0;


			region.SetIndex(index);
			region.SetSize(size);
			
			if(xco!=0)
			{
				index[0] = xco *(max_dim-border)+border/2;
			}
			if(yco!=0)
			{
				index[1] = yco *(max_dim-border)+border/2;
			}
			
			
			index[2] = 0;
			region1.SetSize(size);
			region1.SetIndex(index);

			iter1 = IteratorType(outputim,region1);
			iter2 = IteratorType(outputtile,region);
			typedef itk::ImageRegionIterator<FloatImageType> FIteratorType;
			FIteratorType iter3(cosim,region1);
			FIteratorType iter4(cosimtile,region);
			FIteratorType iter5(sinim,region1);
			FIteratorType iter6(sinimtile, region);

			iter1.GoToBegin();iter2.GoToBegin();
			iter3.GoToBegin();iter4.GoToBegin();
			iter5.GoToBegin();iter6.GoToBegin();

			for(;!iter1.IsAtEnd();++iter1,++iter2,++iter3,++iter4,++iter5,++iter6)
			{
				iter1.Set(iter2.Get());
				iter3.Set(iter4.Get());
				iter5.Set(iter6.Get());
			}
			//printf("Done with copying the tile to full image\n");
		}
	}
	return outputim;
}