Пример #1
0
TransformMatrixType GetVoxelSpaceToRASPhysicalSpaceMatrix(typename ImageType::Pointer image)
  {
  // Generate intermediate terms
  vnl_matrix<double> m_dir, m_ras_matrix;
  vnl_diag_matrix<double> m_scale, m_lps_to_ras;
  vnl_vector<double> v_origin, v_ras_offset;

  // Compute the matrix
  m_dir = image->GetDirection().GetVnlMatrix();
  m_scale.set(image->GetSpacing().GetVnlVector());
  m_lps_to_ras.set(vnl_vector<double>(ImageType::ImageDimension, 1.0));
  m_lps_to_ras[0] = -1;
  m_lps_to_ras[1] = -1;
  m_ras_matrix = m_lps_to_ras * m_dir * m_scale;

  // Compute the vector
  v_origin = image->GetOrigin().GetVnlVector();
  v_ras_offset = m_lps_to_ras * v_origin;

  // Create the larger matrix
  TransformMatrixType mat;
  vnl_vector<double> vcol(ImageType::ImageDimension+1, 1.0);
  vcol.update(v_ras_offset);
  mat.SetIdentity();
  mat.GetVnlMatrix().update(m_ras_matrix);
  mat.GetVnlMatrix().set_column(ImageType::ImageDimension, vcol);

  return mat;
  }
Пример #2
0
void StrokeMask::
Write(const std::string& filename,
      const TPixel& strokeValue)
{
  typedef itk::Image<TPixel, 2> ImageType;
  typename ImageType::Pointer image = ImageType::New();

  image->SetRegions(this->GetLargestPossibleRegion());
  image->Allocate();

  itk::ImageRegionConstIteratorWithIndex<StrokeMask>
      maskIterator(this,
                   this->GetLargestPossibleRegion());
  while(!maskIterator.IsAtEnd())
  {
    if(maskIterator.Get() == StrokeMaskPixelTypeEnum::STROKE)
    {
      image->SetPixel(maskIterator.GetIndex(),
                      strokeValue);
    }
    else
    {
      image->SetPixel(maskIterator.GetIndex(), itk::NumericTraits<TPixel>::Zero);
    }

    ++maskIterator;
  }

  typedef  itk::ImageFileWriter<ImageType> WriterType;
  typename WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(filename);
  writer->SetInput(image);
  writer->Update();

}
Пример #3
0
int testBackCasting(mitk::Image* imgMem, typename ImageType::Pointer & itkImage, bool disconnectAfterImport)
{
  int result;

  if(itkImage.IsNull())
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  int *p = (int*)itkImage->GetBufferPointer();
  if(p==NULL)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Testing mitk::CastToMitkImage: " << std::flush;
  mitk::Image::Pointer mitkImage = mitk::Image::New();
  mitk::CastToMitkImage( itkImage, mitkImage );
  std::cout<<"[PASSED]"<<std::endl;

  result = compareGeometries(imgMem->GetGeometry(), mitkImage->GetGeometry());
  if(result != EXIT_SUCCESS)
    return result;

  std::cout << "Testing whether data after mitk::CastToMitkImage is available: " << std::flush;
  if(mitkImage->IsChannelSet()==false)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  std::cout << "Testing mitk::ImportItkImage: " << std::flush;
  mitkImage = mitk::ImportItkImage(itkImage);
  std::cout<<"[PASSED]"<<std::endl;

  if(disconnectAfterImport)
  {
    std::cout << "Testing DisconnectPipeline() on mitk::Image into which was imported : " << std::flush;
    mitkImage->DisconnectPipeline();
    std::cout<<"[PASSED]"<<std::endl;
  }

  result = compareGeometries(imgMem->GetGeometry(), mitkImage->GetGeometry());
  if(result != EXIT_SUCCESS)
    return result;

  std::cout << "Testing whether data after mitk::ImportItkImage is available: " << std::flush;
  if(mitkImage->IsChannelSet()==false)
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  return EXIT_SUCCESS;
}
Пример #4
0
    void operator()(Parameters& params)
    {
        typedef typename ::itk::Image< PIXELTYPE, 3 > ImageType;
        const typename ImageType::Pointer itkImage = ::fwItkIO::itkImageFactory< ImageType >(params.i_image);

        typename ::itk::ResampleImageFilter<ImageType, ImageType>::Pointer resampler =
            ::itk::ResampleImageFilter<ImageType, ImageType>::New();

        typename ::itk::MinimumMaximumImageCalculator< ImageType >::Pointer minCalculator =
            ::itk::MinimumMaximumImageCalculator< ImageType >::New();

        minCalculator->SetImage(itkImage);
        minCalculator->ComputeMinimum();
        resampler->SetDefaultPixelValue(minCalculator->GetMinimum());

        resampler->SetTransform(params.i_trf.GetPointer());
        resampler->SetInput(itkImage);

        typename ImageType::SizeType size           = itkImage->GetLargestPossibleRegion().GetSize();
        typename ImageType::PointType origin        = itkImage->GetOrigin();
        typename ImageType::SpacingType spacing     = itkImage->GetSpacing();
        typename ImageType::DirectionType direction = itkImage->GetDirection();

        SLM_ASSERT("Input spacing can't be null along any axis", spacing[0] > 0 && spacing[1] > 0 && spacing[2] > 0);

        if(params.i_targetImage)
        {
            for(std::uint8_t i = 0; i < 3; ++i)
            {
                // ITK uses unsigned long to store sizes.
                size[i] = static_cast<typename ImageType::SizeType::SizeValueType>(params.i_targetImage->getSize()[i]);

                origin[i]  = params.i_targetImage->getOrigin()[i];
                spacing[i] = params.i_targetImage->getSpacing()[i];

                SLM_ASSERT("Output spacing can't be null along any axis.", spacing[i] > 0);
            }
        }

        resampler->SetSize(size);
        resampler->SetOutputOrigin(origin);
        resampler->SetOutputDirection(direction);
        resampler->SetOutputSpacing(spacing);

        resampler->Update();

        typename ImageType::Pointer outputImage = resampler->GetOutput();

        ::fwItkIO::itkImageToFwDataImage(outputImage, params.o_image);
    }
Пример #5
0
typename ImageType::Pointer convolveImageHelper(
  typename ImageType::Pointer image,
  typename ImageType::Pointer kernel )
{
  enum { Dimension = ImageType::ImageDimension };
  if( image.IsNotNull() & kernel.IsNotNull() )
    {
    typedef itk::ConvolutionImageFilter<ImageType> FilterType;
    typename FilterType::Pointer convolutionFilter = FilterType::New();
    convolutionFilter->SetInput( image );
    convolutionFilter->SetKernelImage( kernel );
    convolutionFilter->Update();
    return convolutionFilter->GetOutput();
    }
  return NULL;
}
Пример #6
0
void WorkbenchUtils::addPaddingItk(itk::Image <PixelType, ImageDimension> *itkImage, Axis axis, bool append,
                                   int numberOfSlices, float pixelValue, Image::Pointer outImage) {
    // pixel type is templated. The input field for the value is set to float, so the user might enter some invalid values for the image type at hand.
    // since all primitive built-in types have well defined casting behaviour between each other, we'll just do a typecast. we will clip the entered
    // value at PixelTypes min/max to prevent an overflow. The possible loss of precision is ignored.
    float lower = itk::NumericTraits<PixelType>::min();
    float upper = itk::NumericTraits<PixelType>::max();
    float clippedPixelValue = std::max(lower, std::min(pixelValue, upper));

    PixelType paddingPixelValue = (PixelType) clippedPixelValue;

    typedef itk::Image <PixelType, ImageDimension> ImageType;

    // gather all data
    typename ImageType::SizeType lowerBound;
    typename ImageType::SizeType upperBound;
    lowerBound.Fill(0);
    upperBound.Fill(0);

    unsigned int itkAxis = convertToItkAxis(axis);
    if (append) {
        upperBound[itkAxis] = numberOfSlices;
    } else {
        lowerBound[itkAxis] = numberOfSlices;
    }

    // setup the filter
    typedef itk::ConstantPadImageFilter <ImageType, ImageType> PadFilterType;
    typename PadFilterType::Pointer padFilter = PadFilterType::New();
    padFilter->SetInput(itkImage);
    padFilter->SetConstant(paddingPixelValue);
    padFilter->SetPadLowerBound(lowerBound);
    padFilter->SetPadUpperBound(upperBound);
    padFilter->UpdateLargestPossibleRegion();

    // Update the origin, since padding creates negative index that is lost when returned to MITK
    typename ImageType::Pointer paddedImage = padFilter->GetOutput();
    typename ImageType::RegionType paddedImageRegion = paddedImage->GetLargestPossibleRegion();
    typename ImageType::PointType origin;
    paddedImage->TransformIndexToPhysicalPoint(paddedImageRegion.GetIndex(), origin);
    paddedImage->SetOrigin(origin);

    // get the results and cast them back to mitk. return via out parameter.
    outImage->InitializeByItk(paddedImage.GetPointer());
    CastToMitkImage(paddedImage, outImage);
}
    template <class ImagePixelType, class MaskPixelType> int update()
    {
        typedef itk::Image<ImagePixelType, 3> ImageType;
        typedef itk::Image<MaskPixelType,  3> MaskType;

        if ( !input ||!input->data() || !mask ||!mask->data())
            return EXIT_FAILURE;

        typedef itk::MaskImageFilter< ImageType,  MaskType> MaskFilterType;
        typename MaskFilterType::Pointer maskFilter = MaskFilterType::New();

        typename ImageType::Pointer imgInput = dynamic_cast<ImageType *> ( ( itk::Object* ) ( input->data() )) ;
        typename MaskType::Pointer maskInput = dynamic_cast<MaskType *>  ( ( itk::Object* ) ( mask->data() )) ;

        try
        {
            maskInput->SetOrigin(imgInput->GetOrigin());
            maskInput->SetSpacing(imgInput->GetSpacing());
            maskFilter->SetInput(imgInput);
            maskFilter->SetMaskingValue(maskBackgroundValue);
            maskFilter->SetMaskImage(maskInput);

            //Outside values set to the lowest reachable value

            typedef itk::MinimumMaximumImageCalculator <ImageType> ImageCalculatorFilterType;
 
            typename ImageCalculatorFilterType::Pointer imageCalculatorFilter
                    = ImageCalculatorFilterType::New ();
            imageCalculatorFilter->SetImage(imgInput);
            imageCalculatorFilter->ComputeMinimum();
            maskFilter->SetOutsideValue(std::min(double(imageCalculatorFilter->GetMinimum()), 0.0));
            maskFilter->Update();
            output->setData(maskFilter->GetOutput());
        }
        catch( itk::ExceptionObject & err )
        {
            std::cerr << "ExceptionObject caught in medMaskApplication!" << std::endl;
            std::cerr << err << std::endl;
            return EXIT_FAILURE;
        }

        medUtilities::setDerivedMetaData(output, input, "masked");

        return EXIT_SUCCESS;
    }
Пример #8
0
medAbstractJob::medJobExitStatus medItkErodeImageProcess::_run()
{
    typedef itk::Image<inputType, 3> ImageType;

    typename ImageType::Pointer in = dynamic_cast<ImageType *>((itk::Object*)(this->input()->data()));

    if(in.IsNotNull())
    {
        typedef itk::BinaryBallStructuringElement<inputType, 3> KernelType;
        typedef itk::GrayscaleErodeImageFilter<ImageType, ImageType, KernelType> FilterType;
        typename FilterType::Pointer filter = FilterType::New();
        m_filter = filter;

        KernelType kernel;
        kernel.SetRadius(this->kernelRadius()->value());
        kernel.CreateStructuringElement();

        filter->SetKernel(kernel);
        filter->SetInput(in);

        itk::CStyleCommand::Pointer callback = itk::CStyleCommand::New();
        callback->SetClientData((void*)this);
        callback->SetCallback(medItkErodeImageProcess::eventCallback);
        filter->AddObserver(itk::ProgressEvent(), callback);

        try
        {
            filter->Update();
        }
        catch(itk::ProcessAborted &e)
        {
            return medAbstractJob::MED_JOB_EXIT_CANCELLED;
        }

        medAbstractImageData *out= dynamic_cast<medAbstractImageData *>(medAbstractDataFactory::instance()->create(this->input()->identifier()));
        out->setData(filter->GetOutput());
        this->setOutput(out);
        return medAbstractJob::MED_JOB_EXIT_SUCCESS;
    }
    return medAbstractJob::MED_JOB_EXIT_FAILURE;
}
  Image::Pointer mitk::OpenCVToMitkImageFilter::ConvertIplToMitkImage( const IplImage * input )
  {
    typedef itk::Image< TPixel, VImageDimension > ImageType;

    typename ImageType::Pointer output = ImageType::New();
    typename ImageType::RegionType region;
    typename ImageType::RegionType::SizeType size;
    typename ImageType::RegionType::IndexType index;
    typename ImageType::SpacingType spacing;
    size.Fill( 1 );
    size[0] = input->width;
    size[1] = input->height;
    index.Fill(0);
    spacing.Fill(1);
    region.SetSize(size);
    region.SetIndex(index);
    output->SetRegions(region);
    output->SetSpacing(spacing);
    output->Allocate();

    // CAVE: The itk openCV bridge seem to NOT correctly copy the image data, hence the call to
    // itk::OpenCVImageBridge::IplImageToITKImage<ImageType>() is simply used to initialize the itk image
    // and in the next step the image data are copied by hand!

    if(input->nChannels == 3) // these are RGB images and need to be set to BGR before conversion!
    {
      output = itk::OpenCVImageBridge::IplImageToITKImage<ImageType>(input);
    }
    else
    {
      memcpy((void*) output->GetBufferPointer(), (void*) input->imageDataOrigin,
        input->width*input->height*sizeof(TPixel));
    }

    Image::Pointer mitkImage = Image::New();
    mitkImage = GrabItkImageMemory(output);

    return mitkImage;
  }
Пример #10
0
SEXP addNeighborhoodToImageHelper(
  SEXP r_antsimage,
  SEXP r_center,
  SEXP r_rad,
  SEXP r_vec)
{
  typedef typename ImageType::Pointer  ImagePointerType;
  const unsigned int ImageDimension = ImageType::ImageDimension;
  typedef float                        PixelType;
  typename ImageType::Pointer image =
    Rcpp::as< ImagePointerType >( r_antsimage );
  Rcpp::NumericVector center( r_center );
  Rcpp::NumericVector rad( r_rad );
  Rcpp::NumericVector intvec( r_vec );
  if ( center.size() != ImageDimension )
    Rcpp::stop("addNeighborhoodToImageHelper dim error.");
  typename itk::NeighborhoodIterator<ImageType>::SizeType nSize;
  typename ImageType::IndexType ind;
  ind.Fill( 0 );
  for ( unsigned int i=0; i<ImageDimension; i++ )
    {
    nSize[i] = rad[i];
    ind[i] = center[i]; // R coords to ITK
    }
  itk::NeighborhoodIterator<ImageType> nit( nSize, image,
    image->GetLargestPossibleRegion() ) ;
// for each location in nitSearch, compute the correlation
// of the intvec with the nit neighborhood
  nit.SetLocation( ind );
  for( unsigned int i = 0; i < nit.Size(); i++ )
    {
    typename ImageType::IndexType ind2 = nit.GetIndex(i);
    PixelType lval = image->GetPixel( ind2 );
    image->SetPixel( ind2, lval + intvec[i] );
    }
  return 0;
}
void ForegroundBackgroundSegmentMask::
Write(const std::string& filename,
      const ForegroundPixelValueWrapper<TPixel>& foregroundValue,
      const BackgroundPixelValueWrapper<TPixel>& backgroundValue)
{
  typedef itk::Image<TPixel, 2> ImageType;
  typename ImageType::Pointer image = ImageType::New();

  image->SetRegions(this->GetLargestPossibleRegion());
  image->Allocate();

  itk::ImageRegionConstIteratorWithIndex<ForegroundBackgroundSegmentMask>
      maskIterator(this,
                   this->GetLargestPossibleRegion());
  while(!maskIterator.IsAtEnd())
  {
    if(maskIterator.Get() == ForegroundBackgroundSegmentMaskPixelTypeEnum::FOREGROUND)
    {
      image->SetPixel(maskIterator.GetIndex(),
                      foregroundValue.Value);
    }
    else if(maskIterator.Get() == ForegroundBackgroundSegmentMaskPixelTypeEnum::BACKGROUND)
    {
      image->SetPixel(maskIterator.GetIndex(), backgroundValue.Value);
    }

    ++maskIterator;
  }

  typedef  itk::ImageFileWriter<ImageType> WriterType;
  typename WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(filename);
  writer->SetInput(image);
  writer->Update();

}
Пример #12
0
typename PatchExtractor<PValue>::ImageType::Pointer 
PatchExtractor<PValue>::ExtractPatch()
{
	ContIndexType startIndex;
	for(unsigned int i = 0; i < 2; i++)
	{
		startIndex[i] = m_Center[i] - (m_Size[i] / 2.0);
	}
	startIndex[2] = 0;

	PointType newOrigin;
	m_Image->TransformContinuousIndexToPhysicalPoint(startIndex, newOrigin);


	typename ImageType::Pointer patch = ImageType::New();
	patch->SetDirection(m_Image->GetDirection());
	patch->SetOrigin(newOrigin);
	patch->SetSpacing(m_Image->GetSpacing());
	
	typename ImageType::RegionType region;
	m_Size[2] = 1;
	region.SetSize(m_Size);
	
	patch->SetRegions(region);
	patch->Allocate();

	
	typedef itk::NearestNeighborInterpolateImageFunction<ImageType, double> InterpolatorType;
	typename InterpolatorType::Pointer interpolator = InterpolatorType::New();
	interpolator->SetInputImage(m_Image);


	itk::ImageRegionIterator<ImageType> imageIt(patch, region);
	while(!imageIt.IsAtEnd())
	{
		typename ImageType::IndexType index = imageIt.GetIndex();
		PointType point;
		patch->TransformIndexToPhysicalPoint(index, point);

		if(interpolator->IsInsideBuffer(point))
			imageIt.Set(interpolator->Evaluate(point));
		else
			imageIt.Set(0);
		++imageIt;
	}

	return patch;
	
}
Пример #13
0
SEXP jointLabelFusionNeighborhoodSearchHelper(
  SEXP r_intvec,
  SEXP r_center,
  unsigned int rad,
  unsigned int radSearch,
  SEXP r_antsimage,
  SEXP r_antsimageseg)
{
  unsigned int segval = 0;
  typedef typename ImageType::Pointer  ImagePointerType;
  const unsigned int ImageDimension = ImageType::ImageDimension;
  typedef float                        PixelType;
  typename ImageType::Pointer image =
    Rcpp::as< ImagePointerType >( r_antsimage );
  typename ImageType::Pointer imageseg =
      Rcpp::as< ImagePointerType >( r_antsimageseg );
  Rcpp::NumericVector intvec( r_intvec );
  Rcpp::NumericVector outvec =
    Rcpp::NumericVector( intvec.size(), Rcpp::NumericVector::get_na() );
  Rcpp::NumericVector bestvec =
    Rcpp::NumericVector( intvec.size(), Rcpp::NumericVector::get_na() );
  Rcpp::NumericVector outsegvec =
    Rcpp::NumericVector( intvec.size(), Rcpp::NumericVector::get_na() );
  Rcpp::NumericVector bestsegvec =
    Rcpp::NumericVector( intvec.size(), Rcpp::NumericVector::get_na() );
  Rcpp::NumericVector center( r_center );
  if ( center.size() != ImageDimension )
    Rcpp::stop("jointLabelFusionNeighborhoodSearchHelper dim error.");
  typename itk::NeighborhoodIterator<ImageType>::SizeType nSize;
  typename itk::NeighborhoodIterator<ImageType>::SizeType nSizeSearch;
  typename ImageType::IndexType ind;
  ind.Fill( 0 );
  for ( unsigned int i=0; i<ImageDimension; i++ )
    {
    nSize[i] = rad;
    nSizeSearch[i] = radSearch;
    ind[i] = center[i]; // R coords to ITK
    }
  itk::NeighborhoodIterator<ImageType> nit( nSize, image,
    image->GetLargestPossibleRegion() ) ;
  itk::NeighborhoodIterator<ImageType> nitSearch( nSizeSearch, image,
    image->GetLargestPossibleRegion() ) ;
// for each location in nitSearch, compute the correlation
// of the intvec with the nit neighborhood
  nitSearch.SetLocation( ind );
  PixelType bestcor = 1.e11;
  PixelType bestsd = 0;
  PixelType bestmean = 0;
  for( unsigned int i = 0; i < nitSearch.Size(); i++ )
    {
    typename ImageType::IndexType ind2 = nitSearch.GetIndex(i);
    nit.SetLocation( ind2 );
    PixelType outmean = 0;
    PixelType outsd = 0;
    PixelType inmean = 0;
    PixelType insd = 0;
    for ( unsigned int i=0; i < intvec.size(); i++ ) {
      PixelType pix = image->GetPixel( nit.GetIndex(i) );
      outvec[i] = pix;
      outsegvec[i] = imageseg->GetPixel( nit.GetIndex(i) );
      outmean += pix;
      inmean += intvec[i];
      }
    outmean /= ( static_cast<PixelType>(intvec.size()) );
    inmean /= ( static_cast<PixelType>(intvec.size()) );
    for ( unsigned int i=0; i < intvec.size(); i++ ) {
      // should use recursive formula in above loop
      outsd += ( outvec[i] - outmean ) * ( outvec[i] - outmean );
      insd += ( intvec[i] - inmean ) * ( intvec[i] - inmean );
      }
    outsd = sqrt(  outsd  );
    insd = sqrt(  insd  );
    PixelType sum_uv = 0;
    PixelType sum_psearch = 0;
    PixelType ssq_psearch = 0;
    unsigned int n = intvec.size();
    for(unsigned int i = 0; i < n; i++)
      {
      PixelType v = intvec[i];
      PixelType u = outvec[i];
      sum_psearch += u;
      ssq_psearch += u * u;
      sum_uv += u * v;
      }
    PixelType var_u_unnorm = ssq_psearch - sum_psearch * sum_psearch / n;
    if(var_u_unnorm < 1.0e-6)
      var_u_unnorm = 1.0e-6;
    PixelType locor = 0;
    if ( sum_uv > 0 )
      locor = ( -1.0 * (sum_uv * sum_uv) / var_u_unnorm );
    else
      locor = ( sum_uv * sum_uv ) / var_u_unnorm;
//  - (\Sum u_i v_i)^2 / z,   where z = sigma_v^2 * (n-1)
//      locor = locor / ( insd * outsd );
      if ( locor < bestcor )
        {
        segval = imageseg->GetPixel( ind2 );
        for ( unsigned int i=0; i < intvec.size(); i++ ) {
          bestvec[i] = outvec[i];
          bestsegvec[i] = outsegvec[i];
          }
        bestcor = locor;
        bestsd = outsd;
        bestmean = outmean;
        }
    }
  return Rcpp::List::create( Rcpp::Named("segval") = segval,
    Rcpp::Named("values") = bestvec,
    Rcpp::Named("bestmean") = bestmean,
    Rcpp::Named("bestsd") = bestsd,
    Rcpp::Named("bestcor") = bestcor,
    Rcpp::Named("bestsegvec") = bestsegvec  );
}
Пример #14
0
void mitk::SurfaceStampImageFilter::SurfaceStampProcessing(itk::Image<TPixel, 3> *input, MeshType *mesh)
{
  typedef itk::Image<TPixel, 3> ImageType;
  typedef itk::Image<unsigned char, 3> BinaryImageType;

  typedef itk::TriangleMeshToBinaryImageFilter<mitk::SurfaceStampImageFilter::MeshType, BinaryImageType> FilterType;

  BinaryImageType::Pointer binaryInput = BinaryImageType::New();
  binaryInput->SetSpacing(input->GetSpacing());
  binaryInput->SetOrigin(input->GetOrigin());
  binaryInput->SetDirection(input->GetDirection());
  binaryInput->SetRegions(input->GetLargestPossibleRegion());
  binaryInput->Allocate();
  binaryInput->FillBuffer(0);

  FilterType::Pointer filter = FilterType::New();
  filter->SetInput(mesh);
  filter->SetInfoImage(binaryInput);
  filter->SetInsideValue(1);
  filter->SetOutsideValue(0);
  filter->Update();

  BinaryImageType::Pointer resultImage = filter->GetOutput();
  resultImage->DisconnectPipeline();

  mitk::Image::Pointer outputImage = this->GetOutput();
  typename ImageType::Pointer itkOutputImage;
  mitk::CastToItkImage(outputImage, itkOutputImage);

  typedef itk::ImageRegionConstIterator<BinaryImageType> BinaryIteratorType;
  typedef itk::ImageRegionConstIterator<ImageType> InputIteratorType;
  typedef itk::ImageRegionIterator<ImageType> OutputIteratorType;

  BinaryIteratorType sourceIter(resultImage, resultImage->GetLargestPossibleRegion());
  sourceIter.GoToBegin();

  InputIteratorType inputIter(input, input->GetLargestPossibleRegion());
  inputIter.GoToBegin();

  OutputIteratorType outputIter(itkOutputImage, itkOutputImage->GetLargestPossibleRegion());
  outputIter.GoToBegin();

  typename ImageType::PixelType inputValue;
  unsigned char sourceValue;

  auto fgValue = static_cast<typename ImageType::PixelType>(m_ForegroundValue);
  auto bgValue = static_cast<typename ImageType::PixelType>(m_BackgroundValue);

  while (!sourceIter.IsAtEnd())
  {
    sourceValue = static_cast<unsigned char>(sourceIter.Get());
    inputValue = static_cast<typename ImageType::PixelType>(inputIter.Get());

    if (sourceValue != 0)
      outputIter.Set(fgValue);
    else if (m_OverwriteBackground)
      outputIter.Set(bgValue);
    else
      outputIter.Set(inputValue);

    ++sourceIter;
    ++inputIter;
    ++outputIter;
  }
}
Пример #15
0
SEXP sccanCppHelper(
  NumericMatrix X,
  NumericMatrix Y,
  SEXP r_maskx,
  SEXP r_masky,
  RealType sparsenessx,
  RealType sparsenessy,
  IntType nvecs,
  IntType its,
  IntType cthreshx,
  IntType cthreshy,
  RealType z,
  RealType smooth,
  Rcpp::List initializationListx,
  Rcpp::List initializationListy,
  IntType covering,
  RealType ell1,
  IntType verbose,
  RealType priorWeight )
{
  enum { Dimension = ImageType::ImageDimension };
  typename ImageType::RegionType region;
  typedef typename ImageType::PixelType PixelType;
  typedef typename ImageType::Pointer ImagePointerType;
  typedef double                                        Scalar;
  typedef itk::ants::antsSCCANObject<ImageType, Scalar> SCCANType;
  typedef typename SCCANType::MatrixType                vMatrix;
  typename SCCANType::Pointer sccanobj = SCCANType::New();

  typename ImageType::Pointer maskx = Rcpp::as<ImagePointerType>( r_maskx );
  typename ImageType::Pointer masky = Rcpp::as<ImagePointerType>( r_masky );

  bool maskxisnull = maskx.IsNull();
  bool maskyisnull = masky.IsNull();
// deal with the initializationList, if any
  unsigned int nImagesx = initializationListx.size();
  if ( ( nImagesx > 0 ) && ( !maskxisnull ) )
    {
    itk::ImageRegionIteratorWithIndex<ImageType> it( maskx,
      maskx->GetLargestPossibleRegion() );
    vMatrix priorROIMatx( nImagesx , X.cols() );
    priorROIMatx.fill( 0 );
    for ( unsigned int i = 0; i < nImagesx; i++ )
      {
      typename ImageType::Pointer init =
        Rcpp::as<ImagePointerType>( initializationListx[i] );
      unsigned long ct = 0;
      it.GoToBegin();
      while ( !it.IsAtEnd() )
        {
        PixelType pix = it.Get();
        if ( pix >= 0.5 )
          {
          pix = init->GetPixel( it.GetIndex() );
          priorROIMatx( i, ct ) = pix;
          ct++;
          }
        ++it;
        }
      }
    sccanobj->SetMatrixPriorROI( priorROIMatx );
    nvecs = nImagesx;
    }
  unsigned int nImagesy = initializationListy.size();
  if ( ( nImagesy > 0 ) && ( !maskyisnull ) )
    {
    itk::ImageRegionIteratorWithIndex<ImageType> it( masky,
      masky->GetLargestPossibleRegion() );
    vMatrix priorROIMaty( nImagesy , Y.cols() );
    priorROIMaty.fill( 0 );
    for ( unsigned int i = 0; i < nImagesy; i++ )
      {
      typename ImageType::Pointer init =
        Rcpp::as<ImagePointerType>( initializationListy[i] );
      unsigned long ct = 0;
      it.GoToBegin();
      while ( !it.IsAtEnd() )
        {
        PixelType pix = it.Get();
        if ( pix >= 0.5 )
          {
          pix = init->GetPixel( it.GetIndex() );
          priorROIMaty( i, ct ) = pix;
          ct++;
          }
        ++it;
        }
      }
    sccanobj->SetMatrixPriorROI2( priorROIMaty );
    nvecs = nImagesy;
    }

  sccanobj->SetPriorWeight( priorWeight );
  sccanobj->SetLambda( priorWeight );
// cast hack from Rcpp type to sccan type
  std::vector<double> xdat =
      Rcpp::as< std::vector<double> >( X );
  const double* _xdata = &xdat[0];
  vMatrix vnlX( _xdata , X.cols(), X.rows()  );
  vnlX = vnlX.transpose();
  std::vector<double> ydat =
      Rcpp::as< std::vector<double> >( Y );
  const double* _ydata = &ydat[0];
  vMatrix vnlY( _ydata , Y.cols(), Y.rows()  );
  vnlY = vnlY.transpose();
// cast hack done
  sccanobj->SetGetSmall( false  );
  sccanobj->SetCovering( covering );
  sccanobj->SetSilent(  ! verbose  );
  if( ell1 > 0 )
    {
    sccanobj->SetUseL1( true );
    }
  else
    {
    sccanobj->SetUseL1( false );
    }
  sccanobj->SetGradStep( vnl_math_abs( ell1 ) );
  sccanobj->SetMaximumNumberOfIterations( its );
  sccanobj->SetRowSparseness( z );
  sccanobj->SetSmoother( smooth );
  if ( sparsenessx < 0 ) sccanobj->SetKeepPositiveP(false);
  if ( sparsenessy < 0 ) sccanobj->SetKeepPositiveQ(false);
  sccanobj->SetSCCANFormulation(  SCCANType::PQ );
  sccanobj->SetFractionNonZeroP( fabs( sparsenessx ) );
  sccanobj->SetFractionNonZeroQ( fabs( sparsenessy ) );
  sccanobj->SetMinClusterSizeP( cthreshx );
  sccanobj->SetMinClusterSizeQ( cthreshy );
  sccanobj->SetMatrixP( vnlX );
  sccanobj->SetMatrixQ( vnlY );
//  sccanobj->SetMatrixR( r ); // FIXME
  sccanobj->SetMaskImageP( maskx );
  sccanobj->SetMaskImageQ( masky );
  sccanobj->SparsePartialArnoldiCCA( nvecs );

  // FIXME - should not copy, should map memory
  vMatrix solP = sccanobj->GetVariatesP();
  NumericMatrix eanatMatp( solP.cols(), solP.rows() );
  unsigned long rows = solP.rows();
  for( unsigned long c = 0; c < solP.cols(); c++ )
    {
    for( unsigned int r = 0; r < rows; r++ )
      {
      eanatMatp( c, r ) = solP( r, c );
      }
    }

  vMatrix solQ = sccanobj->GetVariatesQ();
  NumericMatrix eanatMatq( solQ.cols(), solQ.rows() );
  rows = solQ.rows();
  for( unsigned long c = 0; c < solQ.cols(); c++ )
    {
    for( unsigned int r = 0; r < rows; r++ )
      {
      eanatMatq( c, r ) = solQ( r, c );
      }
    }

  return(
      Rcpp::List::create(
        Rcpp::Named("eig1") = eanatMatp,
        Rcpp::Named("eig2") = eanatMatq )
      );
}
void invcondemonsforces(int nlhs,
                 mxArray *plhs[],
                 int nrhs,
                 const mxArray *prhs[])
{
   typedef float PixelType;
   typedef itk::Image< PixelType, Dimension >           ImageType;
   
   typedef float                                        VectorComponentType;
   typedef itk::Vector<VectorComponentType, Dimension>  VectorPixelType;
   typedef itk::Image<VectorPixelType, Dimension>       DeformationFieldType;

   typedef itk::ESMInvConDemonsRegistrationFunction
      <ImageType,ImageType,DeformationFieldType>        DemonsRegistrationFunctionType;

   
   //boost::timer timer;


   // Allocate images and deformation field
   typename ImageType::Pointer fixedimage
      = ImageType::New();
   typename ImageType::Pointer movingimage
      = ImageType::New();
   typename ImageType::Pointer fw_weightimage
      = ImageType::New();  
   typename DeformationFieldType::Pointer field
      = DeformationFieldType::New();
   
   typename ImageType::Pointer jacobianimage
      = ImageType::New();  
      
      
   typename DeformationFieldType::Pointer inv_field
      = DeformationFieldType::New();
      
   typename DeformationFieldType::Pointer update
      = DeformationFieldType::New();
   
   typename DeformationFieldType::SpacingType spacing;
   spacing.Fill( 1.0 );
   
   typename DeformationFieldType::PointType origin;
   origin.Fill( 0.0 );
   
   typename DeformationFieldType::RegionType     region;
   typename DeformationFieldType::SizeType       size;
   typename DeformationFieldType::IndexType      start;

   unsigned int numPix(1u);
   const MatlabPixelType * fixinptr =  static_cast<const MatlabPixelType *>(mxGetData(prhs[0]));
   const MatlabPixelType * movinptr =  static_cast<const MatlabPixelType *>(mxGetData(prhs[1]));
   const MatlabPixelType * fieldinptrs[Dimension];
   const MatlabPixelType * inv_fieldinptrs[Dimension];
   
   
   mwSize matlabdims[Dimension];
   for (unsigned int d=0; d<Dimension; d++)
   {
      matlabdims[d]= mxGetDimensions(prhs[0])[d];
      size[d] = matlabdims[d];
      start[d] = 0;
      numPix *= size[d];

      fieldinptrs[d] = static_cast<const MatlabPixelType *>(mxGetData(prhs[2+d]));
      inv_fieldinptrs[d] = static_cast<const MatlabPixelType *>(mxGetData(prhs[2+Dimension+d]));
   }
   
   const MatlabPixelType * jacobianptr = static_cast<const MatlabPixelType *> (mxGetData(prhs[2*Dimension + 2]));
   const MatlabPixelType * fw_weightptr = static_cast<const MatlabPixelType *> (mxGetData(prhs[2*Dimension + 3]));
   
   const double RegWeight = static_cast<double>( mxGetPr(prhs[2*Dimension+4])[0] );
   
   const unsigned int UseJacFlag = 1;
   
   //std::cout << "RegWeight : " << RegWeight << std::endl;
   
   region.SetSize( size );
   region.SetIndex( start );

   fixedimage->SetOrigin( origin );
   fixedimage->SetSpacing( spacing );
   fixedimage->SetRegions( region );
   fixedimage->Allocate();

   movingimage->SetOrigin( origin );
   movingimage->SetSpacing( spacing );
   movingimage->SetRegions( region );
   movingimage->Allocate();
   
   fw_weightimage->SetOrigin( origin );
   fw_weightimage->SetSpacing( spacing );
   fw_weightimage->SetRegions( region );
   fw_weightimage->Allocate();
   
   
   field->SetOrigin( origin );
   field->SetSpacing( spacing );
   field->SetRegions( region );
   field->Allocate();
   
   inv_field->SetOrigin( origin );
   inv_field->SetSpacing( spacing );
   inv_field->SetRegions( region );
   inv_field->Allocate();

   update->SetOrigin( origin );
   update->SetSpacing( spacing );
   update->SetRegions( region );
   update->Allocate();
   if (UseJacFlag > 0)
   {
        jacobianimage->SetOrigin( origin );
        jacobianimage->SetSpacing( spacing );
        jacobianimage->SetRegions( region );
        jacobianimage->Allocate();
   }
   

   //mexPrintf("done Allocate(); %f sec\n", timer.elapsed());
   //timer.restart();

   
   PixelType * fixptr = fixedimage->GetBufferPointer();
   const PixelType * const fixbuff_end = fixptr + numPix;
   PixelType * movptr = movingimage->GetBufferPointer();
   PixelType * fwweightptr = NULL;
   PixelType * jacptr = NULL;
   if (UseJacFlag > 0)
   {
       jacptr = jacobianimage->GetBufferPointer();
   }
   
   
   
   fwweightptr = fw_weightimage->GetBufferPointer();
   
   VectorPixelType * fieldptr = field->GetBufferPointer();
   VectorPixelType * inv_fieldptr = inv_field->GetBufferPointer();
   
   while ( fixptr != fixbuff_end )
   {
      *fixptr++ = *fixinptr++;
      *movptr++ = *movinptr++;
      *fwweightptr++ = *fw_weightptr++; 
      
      for (unsigned int d=0; d<Dimension; d++)
      {
         (*fieldptr)[d] = *(fieldinptrs[d])++;
      }
      if (UseJacFlag > 0)
      {
        *jacptr++ = *jacobianptr++; 
      }
      
      ++fieldptr;
      
      for (unsigned int d=0; d<Dimension; d++)
      {
         (*inv_fieldptr)[d] = *(inv_fieldinptrs[d])++;
      }
      ++inv_fieldptr;
   }

   // Create demons function
   typename DemonsRegistrationFunctionType::Pointer drfp
      = DemonsRegistrationFunctionType::New();

   //mexPrintf("step size: %f\n",mxGetPr(prhs[2*Dimension+2])[0]);
   //drfp->SetMaximumUpdateStepLength( mxGetPr(prhs[2*Dimension+2])[0] );

   typename DemonsRegistrationFunctionType::GradientType gtype = DemonsRegistrationFunctionType::Symmetric;
   drfp->SetUseGradientType( gtype );

   drfp->SetDeformationField( field );
   drfp->SetInvDeformationField( inv_field);
   drfp->SetFixedImage( fixedimage );
   drfp->SetMovingImage( movingimage );
   
   drfp->SetRegWeight(RegWeight);
   
   drfp->SetUseFwWeight(true);
   drfp->SetFwWeightImage(fw_weightimage);
   
   if (UseJacFlag > 0)
   {
       drfp->SetUseJacobian(true);
       drfp->SetJacobianDetImage(jacobianimage);
   }
   else
   {
       drfp->SetUseJacobian(false);
   }
   
   drfp->InitializeIteration();

   //mexPrintf("done demons function init %f sec\n", timer.elapsed());
   //timer.restart();

   const itk::Size<Dimension> radius = drfp->GetRadius();

   // Break the input into a series of regions.  The first region is free
   // of boundary conditions, the rest with boundary conditions.  We operate
   // on the output region because input has been copied to output.
   typedef itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator
      <DeformationFieldType> FaceCalculatorType;
   typedef typename FaceCalculatorType::FaceListType FaceListType;
   typedef typename DemonsRegistrationFunctionType::NeighborhoodType
      NeighborhoodIteratorType;
   typedef itk::ImageRegionIterator<DeformationFieldType> UpdateIteratorType;

   FaceCalculatorType faceCalculator;
   
   FaceListType faceList = faceCalculator(field, region, radius);
   typename FaceListType::iterator fIt = faceList.begin();
   
   // Ask the function object for a pointer to a data structure it
   // will use to manage any global values it needs.  We'll pass this
   // back to the function object at each calculation and then
   // again so that the function object can use it to determine a
   // time step for this iteration.
   void * globalData = drfp->GetGlobalDataPointer();
   
   // Process the non-boundary region.
   NeighborhoodIteratorType nD(radius, field, *fIt);
   UpdateIteratorType       nU(update,  *fIt);
   nD.GoToBegin();
   while( !nD.IsAtEnd() )
   {
      nU.Value() = drfp->ComputeUpdate(nD, globalData);
      ++nD;
      ++nU;
   }

   // Process each of the boundary faces.
   
   NeighborhoodIteratorType bD;
   UpdateIteratorType   bU;
   for (++fIt; fIt != faceList.end(); ++fIt)
   {
      bD = NeighborhoodIteratorType(radius, field, *fIt);
      bU = UpdateIteratorType(update, *fIt);
      
      bD.GoToBegin();
      bU.GoToBegin();
      while ( !bD.IsAtEnd() )
      {
         bU.Value() = drfp->ComputeUpdate(bD, globalData);
         ++bD;
         ++bU;
      }
   }

   // Ask the finite difference function to compute the time step for
   // this iteration.  We give it the global data pointer to use, then
   // ask it to free the global data memory.
   //timeStep = df->ComputeGlobalTimeStep(globalData);
   drfp->ReleaseGlobalDataPointer(globalData);


   //mexPrintf("done actual computations %f sec\n", timer.elapsed());
   //timer.restart();


   // Allocate outputs
   const mxClassID classID = mxGetClassID(prhs[0]);
   MatlabPixelType * outptrs[Dimension];
   for (unsigned int d=0; d<Dimension; d++)
   {
      plhs[d] = mxCreateNumericArray(
         Dimension, matlabdims, classID, mxREAL);

      outptrs[d] = static_cast<MatlabPixelType *>(mxGetData(plhs[d]));
   }

   
   //mexPrintf("done allocate outputs %f sec\n", timer.elapsed());
   //timer.restart();
   

   // put result into outputs
   const VectorPixelType * upptr = update->GetBufferPointer();
   const VectorPixelType * const upbuff_end = upptr + numPix;
   
   while ( upptr != upbuff_end )
   {
      for (unsigned int d=0; d<Dimension; d++)
      {
         *(outptrs[d])++ = (*upptr)[d];
      }
      ++upptr;
   }

   //mexPrintf("done outputs copy %f sec\n", timer.elapsed());
}
void mitk::MRNormLinearStatisticBasedFilter::InternalComputeMask(itk::Image<TPixel, VImageDimension>* itkImage)
{
  // Define all necessary Types
  typedef itk::Image<TPixel, VImageDimension> ImageType;
  typedef itk::Image<int, VImageDimension> MaskType;
  typedef itk::LabelStatisticsImageFilter<ImageType, MaskType> FilterType;
  typedef itk::MinimumMaximumImageCalculator<ImageType> MinMaxComputerType;

  typename MaskType::Pointer itkMask0 = MaskType::New();
  mitk::CastToItkImage(this->GetMask(), itkMask0);

  typename ImageType::Pointer outImage = ImageType::New();
  mitk::CastToItkImage(this->GetOutput(0), outImage);

  typename MinMaxComputerType::Pointer minMaxComputer = MinMaxComputerType::New();
  minMaxComputer->SetImage(itkImage);
  minMaxComputer->Compute();

  typename FilterType::Pointer labelStatisticsImageFilter = FilterType::New();
  labelStatisticsImageFilter->SetUseHistograms(true);
  labelStatisticsImageFilter->SetHistogramParameters(256, minMaxComputer->GetMinimum(),minMaxComputer->GetMaximum());
  labelStatisticsImageFilter->SetInput( itkImage );

  labelStatisticsImageFilter->SetLabelInput(itkMask0);
  labelStatisticsImageFilter->Update();
  double median0 = labelStatisticsImageFilter->GetMedian(1);
  double mean0 = labelStatisticsImageFilter->GetMean(1);
  double stddev = labelStatisticsImageFilter->GetSigma(1);
  double modulo0=0;
  {
    auto histo = labelStatisticsImageFilter->GetHistogram(1);
    double maxFrequency=0;
    for (auto hIter=histo->Begin();hIter!=histo->End();++hIter)
    {
      if (maxFrequency < hIter.GetFrequency())
      {
        maxFrequency = hIter.GetFrequency();
        modulo0 = (histo->GetBinMin(0,hIter.GetInstanceIdentifier()) + histo->GetBinMax(0,hIter.GetInstanceIdentifier())) / 2.0;
      }
    }
  }

  double value0=0;
  switch (m_CenterMode)
  {
  case MRNormLinearStatisticBasedFilter::MEAN:
    value0=mean0; break;
  case MRNormLinearStatisticBasedFilter::MEDIAN:
    value0=median0; break;
  case MRNormLinearStatisticBasedFilter::MODE:
    value0=modulo0; break;
  }

  double offset = value0;
  double scaling = stddev;
  if (scaling < 0.0001)
    return;

  itk::ImageRegionIterator<ImageType> inIter(itkImage, itkImage->GetLargestPossibleRegion());
  itk::ImageRegionIterator<ImageType> outIter(outImage, outImage->GetLargestPossibleRegion());
  while (! inIter.IsAtEnd())
  {
    TPixel value = inIter.Value();
    outIter.Set((value - offset) / scaling);
    ++inIter;
    ++outIter;
  }
}
Пример #18
0
static mitk::Image::Pointer GenerateMaskImage(unsigned int dimX,
                                              unsigned int dimY,
                                              unsigned int dimZ,
                                              float spacingX = 1,
                                              float spacingY = 1,
                                              float spacingZ = 1)
{
  typedef itk::Image< TPixelType, 3 > ImageType;
  typename ImageType::RegionType imageRegion;
  imageRegion.SetSize(0, dimX);
  imageRegion.SetSize(1, dimY);
  imageRegion.SetSize(2, dimZ);
  typename ImageType::SpacingType spacing;
  spacing[0] = spacingX;
  spacing[1] = spacingY;
  spacing[2] = spacingZ;

  mitk::Point3D                       origin; origin.Fill(0.0);
  itk::Matrix<double, 3, 3>           directionMatrix; directionMatrix.SetIdentity();

  typename ImageType::Pointer image = ImageType::New();
  image->SetSpacing( spacing );
  image->SetOrigin( origin );
  image->SetDirection( directionMatrix );
  image->SetLargestPossibleRegion( imageRegion );
  image->SetBufferedRegion( imageRegion );
  image->SetRequestedRegion( imageRegion );
  image->Allocate();
  image->FillBuffer(1);

  mitk::Image::Pointer mitkImage = mitk::Image::New();
  mitkImage->InitializeByItk( image.GetPointer() );
  mitkImage->SetVolume( image->GetBufferPointer() );
  return mitkImage;
}
Пример #19
0
static mitk::Image::Pointer GenerateGradientWithDimXImage(unsigned int dimX,
                                                          unsigned int dimY,
                                                          unsigned int dimZ,
                                                          float spacingX = 1,
                                                          float spacingY = 1,
                                                          float spacingZ = 1)
{
  typedef itk::Image< TPixelType, 3 > ImageType;
  typename ImageType::RegionType imageRegion;
  imageRegion.SetSize(0, dimX);
  imageRegion.SetSize(1, dimY);
  imageRegion.SetSize(2, dimZ);
  typename ImageType::SpacingType spacing;
  spacing[0] = spacingX;
  spacing[1] = spacingY;
  spacing[2] = spacingZ;

  mitk::Point3D                       origin; origin.Fill(0.0);
  itk::Matrix<double, 3, 3>           directionMatrix; directionMatrix.SetIdentity();

  typename ImageType::Pointer image = ImageType::New();
  image->SetSpacing( spacing );
  image->SetOrigin( origin );
  image->SetDirection( directionMatrix );
  image->SetLargestPossibleRegion( imageRegion );
  image->SetBufferedRegion( imageRegion );
  image->SetRequestedRegion( imageRegion );
  image->Allocate();
  image->FillBuffer(0.0);

  typedef itk::ImageRegionIterator<ImageType>      IteratorOutputType;
  IteratorOutputType it(image, imageRegion);
  it.GoToBegin();

  TPixelType val = 0;
  while(!it.IsAtEnd())
  {
    it.Set(val % dimX);
    val++;
    ++it;
  }

  mitk::Image::Pointer mitkImage = mitk::Image::New();
  mitkImage->InitializeByItk( image.GetPointer() );
  mitkImage->SetVolume( image->GetBufferPointer() );
  return mitkImage;
}
Пример #20
0
SEXP eigenanatomyCppHelper(
  NumericMatrix X,
  SEXP r_mask,
  RealType sparseness,
  IntType nvecs,
  IntType its,
  IntType cthresh,
  RealType z,
  RealType smooth,
//  NumericMatrix initializationMatrix,
  Rcpp::List initializationList,
  IntType covering,
  RealType ell1,
  IntType verbose,
  IntType powerit,
  RealType priorWeight )
{
  enum { Dimension = ImageType::ImageDimension };
  typename ImageType::RegionType region;
  typedef typename ImageType::PixelType PixelType;
  typedef typename ImageType::Pointer ImagePointerType;
  typedef double                                        Scalar;
  typedef itk::ants::antsSCCANObject<ImageType, Scalar> SCCANType;
  typedef typename SCCANType::MatrixType                vMatrix;
  typename SCCANType::Pointer sccanobj = SCCANType::New();

  typename ImageType::Pointer mask = Rcpp::as<ImagePointerType>( r_mask );
  bool maskisnull = mask.IsNull();
// deal with the initializationList, if any
  unsigned int nImages = initializationList.size();
  if ( ( nImages > 0 ) && ( !maskisnull ) )
    {
    itk::ImageRegionIteratorWithIndex<ImageType> it( mask,
      mask->GetLargestPossibleRegion() );
    vMatrix priorROIMat( nImages , X.cols() );
    priorROIMat.fill( 0 );
    for ( unsigned int i = 0; i < nImages; i++ )
      {
      typename ImageType::Pointer init =
        Rcpp::as<ImagePointerType>( initializationList[i] );
      unsigned long ct = 0;
      it.GoToBegin();
      while ( !it.IsAtEnd() )
        {
        PixelType pix = it.Get();
        if ( pix >= 0.5 )
          {
          pix = init->GetPixel( it.GetIndex() );
          priorROIMat( i, ct ) = pix;
          ct++;
          }
        ++it;
        }
      }
    sccanobj->SetMatrixPriorROI( priorROIMat );
    nvecs = nImages;
    }
  sccanobj->SetPriorWeight( priorWeight );
  sccanobj->SetLambda( priorWeight );
// cast hack from Rcpp type to sccan type
  std::vector<double> xdat =
      Rcpp::as< std::vector<double> >( X );
  const double* _xdata = &xdat[0];
  vMatrix vnlX( _xdata , X.cols(), X.rows()  );
  vnlX = vnlX.transpose();

  sccanobj->SetGetSmall( false  );
  vMatrix priorROIMat;

//    sccanobj->SetMatrixPriorROI( priorROIMat);
//    sccanobj->SetMatrixPriorROI2( priorROIMat );
  sccanobj->SetCovering( covering );
  sccanobj->SetSilent(  ! verbose  );
  if( ell1 > 0 )
    {
    sccanobj->SetUseL1( true );
    }
  else
    {
    sccanobj->SetUseL1( false );
    }
  sccanobj->SetGradStep( vnl_math_abs( ell1 ) );
  sccanobj->SetMaximumNumberOfIterations( its );
  sccanobj->SetRowSparseness( z );
  sccanobj->SetSmoother( smooth );
  if ( sparseness < 0 ) sccanobj->SetKeepPositiveP(false);
  sccanobj->SetSCCANFormulation(  SCCANType::PQ );
  sccanobj->SetFractionNonZeroP( fabs( sparseness ) );
  sccanobj->SetMinClusterSizeP( cthresh );
  sccanobj->SetMatrixP( vnlX );
//  sccanobj->SetMatrixR( r ); // FIXME
  sccanobj->SetMaskImageP( mask );
  RealType truecorr = 0;
  if( powerit == 1 )
    {
    truecorr = sccanobj->SparseReconHome( nvecs );
    }
  else if ( priorWeight > 1.e-12 )
    truecorr = sccanobj->SparseReconPrior( nvecs, true );
  else truecorr = sccanobj->SparseRecon(nvecs);
  /*
  else if( powerit != 0 )
    {
    truecorr = sccanobj->SparseArnoldiSVD(nvecs);
    }
  else if( svd_option == 4  )
    {
    truecorr = sccanobj->NetworkDecomposition( nvecs );
    }
  else if( svd_option == 5  )
    {
    truecorr = sccanobj->LASSO( nvecs );
    }
  else if( svd_option == 2 )
    {
    truecorr = sccanobj->CGSPCA(nvecs);                         // cgspca
    }
  else if( svd_option == 6 )
    {
    truecorr = sccanobj->SparseRecon(nvecs);  // sparse (default)
    }
  else if( svd_option == 7 )
    {
    // sccanobj->SetPriorScaleMat( priorScaleMat);
    sccanobj->SetMatrixPriorROI( priorROIMat);
    sccanobj->SetFlagForSort();
    sccanobj->SetLambda(sccanparser->Convert<double>( option->GetFunction( 0 )->GetParameter( 3 ) ) );
    truecorr = sccanobj->SparseReconPrior(nvecs, true); // Prior
  }
  else
    {
    truecorr = sccanobj->SparseArnoldiSVDGreedy( nvecs );  // sparse (default)
    }
  */

  // solutions should be much smaller so may not be a big deal to copy
  // FIXME - should not copy, should map memory
  vMatrix solV = sccanobj->GetVariatesP();
  NumericMatrix eanatMat( solV.cols(), solV.rows() );
  unsigned long rows = solV.rows();
  for( unsigned long c = 0; c < solV.cols(); c++ )
    {
    for( unsigned int r = 0; r < rows; r++ )
      {
      eanatMat( c, r ) = solV( r, c );
      }
    }
  vMatrix solU = sccanobj->GetMatrixU();
  NumericMatrix eanatMatU( solU.rows(), solU.cols() );
  rows = solU.rows();
  for( unsigned long c = 0; c < solU.cols(); c++ )
    {
    for( unsigned int r = 0; r < rows; r++ )
      {
      eanatMatU( r, c) = solU( r, c);
      }
    }
  return(
      Rcpp::List::create(
        Rcpp::Named("eigenanatomyimages") = eanatMat,
        Rcpp::Named("umatrix") = eanatMatU,
        Rcpp::Named("varex") = truecorr )
      );
}
template <class inputType, unsigned int Dimension> medAbstractJob::medJobExitStatus medItkBiasCorrectionProcess::N4BiasCorrectionCore()
{
    medJobExitStatus eRes = medAbstractJob::MED_JOB_EXIT_SUCCESS;

    typedef itk::Image<inputType, Dimension > ImageType;
    typedef itk::Image <float, Dimension> OutputImageType;
    typedef itk::Image<unsigned char, Dimension> MaskImageType;
    typedef itk::N4BiasFieldCorrectionImageFilter<OutputImageType, MaskImageType, OutputImageType> BiasFilter;
    typedef itk::ConstantPadImageFilter<OutputImageType, OutputImageType> PadderType;
    typedef itk::ConstantPadImageFilter<MaskImageType, MaskImageType> MaskPadderType;
    typedef itk::ShrinkImageFilter<OutputImageType, OutputImageType> ShrinkerType;
    typedef itk::ShrinkImageFilter<MaskImageType, MaskImageType> MaskShrinkerType;
    typedef itk::BSplineControlPointImageFilter<typename BiasFilter::BiasFieldControlPointLatticeType, typename BiasFilter::ScalarImageType> BSplinerType;
    typedef itk::ExpImageFilter<OutputImageType, OutputImageType> ExpFilterType;
    typedef itk::DivideImageFilter<OutputImageType, OutputImageType, OutputImageType> DividerType;
    typedef itk::ExtractImageFilter<OutputImageType, OutputImageType> CropperType;

    unsigned int uiThreadNb = static_cast<unsigned int>(m_poUIThreadNb->value());
    unsigned int uiShrinkFactors = static_cast<unsigned int>(m_poUIShrinkFactors->value());
    unsigned int uiSplineOrder = static_cast<unsigned int>(m_poUISplineOrder->value());
    float fWienerFilterNoise = static_cast<float>(m_poFWienerFilterNoise->value());
    float fbfFWHM = static_cast<float>(m_poFbfFWHM->value());
    float fConvergenceThreshold = static_cast<float>(m_poFConvergenceThreshold->value());
    float fSplineDistance = static_cast<float>(m_poFSplineDistance->value());

    float fProgression = 0;

    QStringList oListValue = m_poSMaxIterations->value().split("x");

    std::vector<unsigned int> oMaxNumbersIterationsVector(oListValue.size());
    std::vector<float> oInitialMeshResolutionVect(Dimension);
    for (int i=0; i<oMaxNumbersIterationsVector.size(); ++i)
    {
       oMaxNumbersIterationsVector[i] = (unsigned int)oListValue[i].toInt();
    }
    oInitialMeshResolutionVect[0] = static_cast<float>(m_poFInitialMeshResolutionVect1->value());
    oInitialMeshResolutionVect[1] = static_cast<float>(m_poFInitialMeshResolutionVect2->value());
    oInitialMeshResolutionVect[2] = static_cast<float>(m_poFInitialMeshResolutionVect3->value());

    typename ImageType::Pointer image = dynamic_cast<ImageType *>((itk::Object*)(this->input()->data()));
    typedef itk::CastImageFilter <ImageType, OutputImageType> CastFilterType;
    typename CastFilterType::Pointer castFilter = CastFilterType::New();
    castFilter->SetInput(image);

    /********************************************************************************/
    /***************************** PREPARING STARTING *******************************/
    /********************************************************************************/

    /*** 0 ******************* Create filter and accessories ******************/
    ABORT_CHECKING(m_bAborting);
    typename BiasFilter::Pointer filter = BiasFilter::New();
    typename BiasFilter::ArrayType oNumberOfControlPointsArray;
    m_filter = filter;

    /*** 1 ******************* Read input image *******************************/
    ABORT_CHECKING(m_bAborting);
    fProgression = 1;
    updateProgression(fProgression);

    /*** 2 ******************* Creating Otsu mask *****************************/
    ABORT_CHECKING(m_bAborting);
    itk::TimeProbe timer;
    timer.Start();
    typename MaskImageType::Pointer maskImage = ITK_NULLPTR;
    typedef itk::OtsuThresholdImageFilter<OutputImageType, MaskImageType> ThresholderType;
    typename ThresholderType::Pointer otsu = ThresholderType::New();
    m_filter = otsu;
    otsu->SetInput(castFilter->GetOutput());
    otsu->SetNumberOfHistogramBins(200);
    otsu->SetInsideValue(0);
    otsu->SetOutsideValue(1);

    otsu->SetNumberOfThreads(uiThreadNb);
    otsu->Update();
    updateProgression(fProgression);
    maskImage = otsu->GetOutput();


    /*** 3A *************** Set Maximum number of Iterations for the filter ***/
    ABORT_CHECKING(m_bAborting);
    typename BiasFilter::VariableSizeArrayType itkTabMaximumIterations;
    itkTabMaximumIterations.SetSize(oMaxNumbersIterationsVector.size());
    for (int i = 0; i < oMaxNumbersIterationsVector.size(); ++i)
    {
        itkTabMaximumIterations[i] = oMaxNumbersIterationsVector[i];
    }
    filter->SetMaximumNumberOfIterations(itkTabMaximumIterations);

    /*** 3B *************** Set Fitting Levels for the filter *****************/
    typename BiasFilter::ArrayType oFittingLevelsTab;
    oFittingLevelsTab.Fill(oMaxNumbersIterationsVector.size());
    filter->SetNumberOfFittingLevels(oFittingLevelsTab);

    updateProgression(fProgression);

    /*** 4 ******************* Save image's index, size, origine **************/
    ABORT_CHECKING(m_bAborting);
    typename ImageType::IndexType oImageIndex = image->GetLargestPossibleRegion().GetIndex();
    typename ImageType::SizeType oImageSize = image->GetLargestPossibleRegion().GetSize();
    typename ImageType::PointType newOrigin = image->GetOrigin();

    typename OutputImageType::Pointer outImage = castFilter->GetOutput();

    if (fSplineDistance > 0)
    {
        /*** 5 ******************* Compute number of control points  **************/
        ABORT_CHECKING(m_bAborting);
        itk::SizeValueType lowerBound[3];
        itk::SizeValueType upperBound[3];

        for (unsigned int i = 0; i < 3; i++)
        {
            float domain = static_cast<float>(image->GetLargestPossibleRegion().GetSize()[i] - 1) * image->GetSpacing()[i];
            unsigned int numberOfSpans = static_cast<unsigned int>(std::ceil(domain / fSplineDistance));
            unsigned long extraPadding = static_cast<unsigned long>((numberOfSpans * fSplineDistance - domain) / image->GetSpacing()[i] + 0.5);
            lowerBound[i] = static_cast<unsigned long>(0.5 * extraPadding);
            upperBound[i] = extraPadding - lowerBound[i];
            newOrigin[i] -= (static_cast<float>(lowerBound[i]) * image->GetSpacing()[i]);
            oNumberOfControlPointsArray[i] = numberOfSpans + filter->GetSplineOrder();
        }
        updateProgression(fProgression);

        /*** 6 ******************* Padder  ****************************************/
        ABORT_CHECKING(m_bAborting);
        typename PadderType::Pointer imagePadder = PadderType::New();
        m_filter = imagePadder;
        imagePadder->SetInput(castFilter->GetOutput());
        imagePadder->SetPadLowerBound(lowerBound);
        imagePadder->SetPadUpperBound(upperBound);
        imagePadder->SetConstant(0);
        imagePadder->SetNumberOfThreads(uiThreadNb);
        imagePadder->Update();
        updateProgression(fProgression);

        outImage = imagePadder->GetOutput();

        /*** 7 ******************** Handle the mask image *************************/
        ABORT_CHECKING(m_bAborting);
        typename MaskPadderType::Pointer maskPadder = MaskPadderType::New();
        m_filter = maskPadder;
        maskPadder->SetInput(maskImage);
        maskPadder->SetPadLowerBound(lowerBound);
        maskPadder->SetPadUpperBound(upperBound);
        maskPadder->SetConstant(0);
        maskPadder->SetNumberOfThreads(uiThreadNb);
        maskPadder->Update();
        updateProgression(fProgression);

        maskImage = maskPadder->GetOutput();

        /*** 8 ******************** SetNumber Of Control Points *******************/
        ABORT_CHECKING(m_bAborting);
        filter->SetNumberOfControlPoints(oNumberOfControlPointsArray);
    }
    else if (oInitialMeshResolutionVect.size() == 3)
    {
        /*** 9 ******************** SetNumber Of Control Points alternative *******/
        ABORT_CHECKING(m_bAborting);
        for (unsigned i = 0; i < 3; i++)
        {
            oNumberOfControlPointsArray[i] = static_cast<unsigned int>(oInitialMeshResolutionVect[i]) + filter->GetSplineOrder();
        }
        filter->SetNumberOfControlPoints(oNumberOfControlPointsArray);

        updateProgression(fProgression, 3);
    }
    else
    {
        fProgression = 0;
        updateProgression(fProgression);
        std::cout << "No BSpline distance and Mesh Resolution is ignored because not 3 dimensions" << std::endl;
    }

    /*** 10 ******************* Shrinker image ********************************/
    ABORT_CHECKING(m_bAborting);
    typename ShrinkerType::Pointer imageShrinker = ShrinkerType::New();
    m_filter = imageShrinker;
    imageShrinker->SetInput(outImage);

    /*** 11 ******************* Shrinker mask *********************************/
    ABORT_CHECKING(m_bAborting);
    typename MaskShrinkerType::Pointer maskShrinker = MaskShrinkerType::New();
    m_filter = maskShrinker;
    maskShrinker->SetInput(maskImage);

    /*** 12 ******************* Shrink mask and image *************************/
    ABORT_CHECKING(m_bAborting);
    imageShrinker->SetShrinkFactors(uiShrinkFactors);
    maskShrinker->SetShrinkFactors(uiShrinkFactors);
    imageShrinker->SetNumberOfThreads(uiThreadNb);
    maskShrinker->SetNumberOfThreads(uiThreadNb);
    imageShrinker->Update();
    updateProgression(fProgression);
    maskShrinker->Update();
    updateProgression(fProgression);

    /*** 13 ******************* Filter setings ********************************/
    ABORT_CHECKING(m_bAborting);
    filter->SetSplineOrder(uiSplineOrder);
    filter->SetWienerFilterNoise(fWienerFilterNoise);
    filter->SetBiasFieldFullWidthAtHalfMaximum(fbfFWHM);
    filter->SetConvergenceThreshold(fConvergenceThreshold);
    filter->SetInput(imageShrinker->GetOutput());
    filter->SetMaskImage(maskShrinker->GetOutput());

    /*** 14 ******************* Apply filter **********************************/
    ABORT_CHECKING(m_bAborting);
    try
    {
        filter->SetNumberOfThreads(uiThreadNb);
        filter->Update();
        updateProgression(fProgression, 5);
    }
    catch (itk::ExceptionObject & err)
    {
        std::cerr << "ExceptionObject caught !" << std::endl;
        std::cerr << err << std::endl;
        eRes = medAbstractJob::MED_JOB_EXIT_FAILURE;
        return eRes;
    }


    /**
    * Reconstruct the bias field at full image resolution.  Divide
    * the original input image by the bias field to get the final
    * corrected image.
    */
    ABORT_CHECKING(m_bAborting);
    typename BSplinerType::Pointer bspliner = BSplinerType::New();
    m_filter = bspliner;
    bspliner->SetInput(filter->GetLogBiasFieldControlPointLattice());
    bspliner->SetSplineOrder(filter->GetSplineOrder());
    bspliner->SetSize(image->GetLargestPossibleRegion().GetSize());
    bspliner->SetOrigin(newOrigin);
    bspliner->SetDirection(image->GetDirection());
    bspliner->SetSpacing(image->GetSpacing());
    bspliner->SetNumberOfThreads(uiThreadNb);
    bspliner->Update();
    updateProgression(fProgression);


    /*********************** Logarithm phase ***************************/
    ABORT_CHECKING(m_bAborting);
    typename OutputImageType::Pointer logField = OutputImageType::New();
    logField->SetOrigin(image->GetOrigin());
    logField->SetSpacing(image->GetSpacing());
    logField->SetRegions(image->GetLargestPossibleRegion());
    logField->SetDirection(image->GetDirection());
    logField->Allocate();

    itk::ImageRegionIterator<typename BiasFilter::ScalarImageType> IB(bspliner->GetOutput(), bspliner->GetOutput()->GetLargestPossibleRegion());

    itk::ImageRegionIterator<OutputImageType> IF(logField, logField->GetLargestPossibleRegion());

    for (IB.GoToBegin(), IF.GoToBegin(); !IB.IsAtEnd(); ++IB, ++IF)
    {
        IF.Set(IB.Get()[0]);
    }


    /*********************** Exponential phase *************************/
    ABORT_CHECKING(m_bAborting);
    typename ExpFilterType::Pointer expFilter = ExpFilterType::New();
    m_filter = expFilter;
    expFilter->SetInput(logField);
    expFilter->SetNumberOfThreads(uiThreadNb);
    expFilter->Update();
    updateProgression(fProgression);

    /************************ Dividing phase ***************************/
    ABORT_CHECKING(m_bAborting);
    typename DividerType::Pointer divider = DividerType::New();
    m_filter = divider;
    divider->SetInput1(castFilter->GetOutput());
    divider->SetInput2(expFilter->GetOutput());
    divider->SetNumberOfThreads(uiThreadNb);
    divider->Update();
    updateProgression(fProgression);


    /******************** Prepare cropping phase ***********************/
    ABORT_CHECKING(m_bAborting);
    typename ImageType::RegionType inputRegion;
    inputRegion.SetIndex(oImageIndex);
    inputRegion.SetSize(oImageSize);

    /************************ Cropping phase ***************************/
    ABORT_CHECKING(m_bAborting);
    typename CropperType::Pointer cropper = CropperType::New();
    m_filter = cropper;
    cropper->SetInput(divider->GetOutput());
    cropper->SetExtractionRegion(inputRegion);
    cropper->SetDirectionCollapseToSubmatrix();
    cropper->SetNumberOfThreads(uiThreadNb);
    cropper->Update();
    updateProgression(fProgression);

    /********************** Write output image *************************/
    ABORT_CHECKING(m_bAborting);
    medAbstractImageData *out = qobject_cast<medAbstractImageData *>(medAbstractDataFactory::instance()->create("itkDataImageFloat3"));
    out->setData(cropper->GetOutput());
    this->setOutput(out);

    m_filter = 0;
    
    return eRes;
}