void GenerateData_3DImage_CompareToReference()
  {
    int upperThr = 255;
    int lowerThr = 60;

    int outsideVal = 0;
    int insideVal = 100;

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

    try{

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

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

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

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

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

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

  }
Esempio n. 2
0
void mitk::RegionGrow3DTool::ConfirmSegmentation( std::string name, mitk::Color color)
{
    mitk::DataNode::Pointer new_node = mitk::DataNode::New();
    new_node->SetColor(color);
    new_node->SetName(name);
    new_node->SetProperty("binary", mitk::BoolProperty::New("true"));

    mitk::Image* image = dynamic_cast<mitk::Image*> (m_FeedbackNode->GetData());

    mitk::LevelWindow tempLevelWindow;
    m_FeedbackNode->GetLevelWindow( tempLevelWindow, NULL, "levelWindow");
    int upperThresholdLabeledImage = (short int) tempLevelWindow.GetRangeMax();
    int lowerThresholdLabeledImage = (short int) tempLevelWindow.GetLowerWindowBound() + 1;

    typedef itk::Image<int, 3> InputImageType;
    typedef itk::Image<unsigned char, 3> SegmentationType;
    typedef itk::BinaryThresholdImageFilter<InputImageType, SegmentationType> ThresholdFilterType;

    ThresholdFilterType::Pointer filter = ThresholdFilterType::New();
    InputImageType::Pointer itkImage;
    mitk::CastToItkImage(image, itkImage);
    filter->SetInput(itkImage);
    filter->SetInsideValue(1);
    filter->SetOutsideValue(0);
    filter->SetUpperThreshold(upperThresholdLabeledImage);
    filter->SetLowerThreshold(lowerThresholdLabeledImage);
    filter->Update();
    mitk::Image::Pointer new_image = mitk::Image::New();
    mitk::CastToMitkImage(filter->GetOutput(), new_image);


    //pad to original size
    if (m_OriginalImageNode.GetPointer() != m_NodeToProceed.GetPointer())
    {
        mitk::PadImageFilter::Pointer padFilter = mitk::PadImageFilter::New();

        padFilter->SetInput(0, new_image);
        padFilter->SetInput(1, dynamic_cast<mitk::Image*> (m_OriginalImageNode->GetData()));
        padFilter->SetBinaryFilter(true);
        padFilter->SetUpperThreshold(1);
        padFilter->SetLowerThreshold(1);
        padFilter->Update();

        new_image = padFilter->GetOutput();
    }

    new_node->SetData(new_image);
    m_ToolManager->GetDataStorage()->Add(new_node);

    mitk::RenderingManager::GetInstance()->RequestUpdateAll();

    m_ToolManager->ActivateTool(-1);
}
Esempio n. 3
0
BinaryImageType::Pointer readBinaryImage(const std::string& filename) {
    ImageReaderType::Pointer reader = ImageReaderType::New();
    reader->SetFileName(filename.c_str());
    reader->Update();

    // we make sure that the image really has value 0 and 1
    typedef itk::BinaryThresholdImageFilter<BinaryImageType, BinaryImageType> ThresholdFilterType;
    ThresholdFilterType::Pointer thresholdFilter = ThresholdFilterType::New();
    thresholdFilter->SetInsideValue(1);
    thresholdFilter->SetOutsideValue(0);
    thresholdFilter->SetLowerThreshold(1);
    thresholdFilter->SetUpperThreshold(255);
    thresholdFilter->SetInput(reader->GetOutput());
    thresholdFilter->Update();
    BinaryImageType::Pointer img = thresholdFilter->GetOutput();
    img->DisconnectPipeline();
    return img;
}
Esempio n. 4
0
void mitk::BinaryThresholdULTool::UpdatePreview()
{
  typedef itk::Image<int, 3> ImageType;
  typedef itk::Image<unsigned char, 3> SegmentationType;
  typedef itk::BinaryThresholdImageFilter<ImageType, SegmentationType> ThresholdFilterType;
  mitk::Image::Pointer thresholdimage = dynamic_cast<mitk::Image*> (m_NodeForThresholding->GetData());
  if(thresholdimage)
  {
    ImageType::Pointer itkImage = ImageType::New();
    CastToItkImage(thresholdimage, itkImage);
    ThresholdFilterType::Pointer filter = ThresholdFilterType::New();
    filter->SetInput(itkImage);
    filter->SetLowerThreshold(m_CurrentLowerThresholdValue);
    filter->SetUpperThreshold(m_CurrentUpperThresholdValue);
    filter->SetInsideValue(1);
    filter->SetOutsideValue(0);
    filter->Update();

    mitk::Image::Pointer new_image = mitk::Image::New();
    CastToMitkImage(filter->GetOutput(), new_image);
    m_ThresholdFeedbackNode->SetData(new_image);
  }
  RenderingManager::GetInstance()->RequestUpdateAll();
}
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();
}
Esempio n. 6
0
int mitkToFCompositeFilterTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("ToFCompositeFilter");

  //initialize composite filter
  mitk::ToFCompositeFilter::Pointer compositeFilter = mitk::ToFCompositeFilter::New();

  //Initialize threshold filter
  ThresholdFilterType::Pointer thresholdFilter = ThresholdFilterType::New();
  int threshold_min = 5;
  int threshold_max = 100;
  thresholdFilter->SetOutsideValue(0.0);
  thresholdFilter->SetLower(threshold_min);
  thresholdFilter->SetUpper(threshold_max);
  compositeFilter->SetThresholdFilterParameter(threshold_min, threshold_max);

  //Initialize spatial median filter
  MedianFilterType::Pointer medianFilter = MedianFilterType::New();

  //Initialize bilateral filter
  BilateralImageFilterType::Pointer bilateralFilter = BilateralImageFilterType::New();
  float domainSigma = 4;
  float rangeSigma = 50;
  float kernelRadius = 3;
  bilateralFilter->SetDomainSigma(domainSigma);
  bilateralFilter->SetRangeSigma(rangeSigma);
  bilateralFilter->SetRadius(kernelRadius);
  compositeFilter->SetBilateralFilterParameter(domainSigma,rangeSigma,kernelRadius);

  //Initialize pipeline
  ItkImageType_2D::Pointer itkInputImage = ItkImageType_2D::New();
  mitk::Image::Pointer mitkInputImage = mitk::Image::New();
  CreateRandomDistanceImage(100,100,itkInputImage,mitkInputImage);
  ItkImageType_2D::Pointer itkOutputImage;
  compositeFilter->SetInput(mitkInputImage);
  mitk::Image::Pointer mitkOutputImage = compositeFilter->GetOutput();


  //-------------------------------------------------------------------------------------------------------

  //Apply first filter only (threshold)

  //standard variant
  thresholdFilter->SetInput(itkInputImage);
  itkOutputImage = thresholdFilter->GetOutput();
  itkOutputImage->Update();

  //variant with composite filter
  compositeFilter->SetApplyThresholdFilter(true);
  compositeFilter->SetApplyMedianFilter(false);
  compositeFilter->SetApplyTemporalMedianFilter(false);
  compositeFilter->SetApplyBilateralFilter(false);
  mitkOutputImage->Update();

  //compare output
  mitk::Image::Pointer itkOutputImageConverted;
  mitk::CastToMitkImage(itkOutputImage,itkOutputImageConverted);

  MITK_TEST_CONDITION_REQUIRED( mitk::Equal(*itkOutputImageConverted, *mitkOutputImage, mitk::eps, true),
                                "Test threshold filter in pipeline");

  //-------------------------------------------------------------------------------------------------------

  //Apply first and second filter

  //standard variant
  medianFilter->SetInput(thresholdFilter->GetOutput());
  itkOutputImage = medianFilter->GetOutput();
  itkOutputImage->Update();

  //variant with composite filter
  compositeFilter->SetApplyMedianFilter(true);
  mitkOutputImage->Update();

  //compare output
  mitk::CastToMitkImage(itkOutputImage,itkOutputImageConverted);

  MITK_TEST_CONDITION_REQUIRED( mitk::Equal(*itkOutputImageConverted, *mitkOutputImage, mitk::eps, true),
                               "Test threshold and median filter in pipeline");


  //-------------------------------------------------------------------------------------------------------

  //Apply first three filters

  //standard variant
  bilateralFilter->SetInput(medianFilter->GetOutput());
  itkOutputImage = bilateralFilter->GetOutput();
  itkOutputImage->Update();

  //variant with composite filter
  compositeFilter->SetApplyBilateralFilter(true);
  mitkOutputImage->Update();

  //compare output
  mitk::CastToMitkImage(itkOutputImage,itkOutputImageConverted);

  MITK_TEST_CONDITION_REQUIRED( mitk::Equal(*itkOutputImageConverted, *mitkOutputImage, mitk::eps, true),
                               "Test threshold filter, bilateral filter and temporal median filter in pipeline");


  //-------------------------------------------------------------------------------------------------------
  // TODO: Rewrite this. This don't make sense. the itk reference applies a median filter
  // and threshold filter afterwards. The composite filter does it in the other directtion.
  // also the input of random image stacks is never set into the composite filter

  //Apply all filters

  //generate image stack
//  ItkImageType_3D::Pointer itkInputImage3D = ItkImageType_3D::New();
//  mitk::Image::Pointer mitkImage3D = mitk::Image::New();
//  CreateRandomDistanceImageStack(100,100,12,itkInputImage3D,mitkImage3D);
//
//  //standard variant
//  ItkImageType_2D::Pointer medianFilteredImage = ItkImageType_2D::New();
//  ApplyTemporalMedianFilter(mitkImage3D,medianFilteredImage);
//  thresholdFilter->SetInput(medianFilteredImage);
//  itkOutputImage->Update();
//
//  //variant with composite filter
//  compositeFilter->SetApplyTemporalMedianFilter(true);
//  mitkOutputImage->Update();
//
//  //compare output
//  mitk::CastToMitkImage(itkOutputImage,itkOutputImageConverted);
//  pipelineSuccess = CompareImages(itkOutputImageConverted,mitkOutputImage);
//  MITK_TEST_CONDITION_REQUIRED(pipelineSuccess,"Test all filters in pipeline");


//-------------------------------------------------------------------------------------------------------

  //Check set/get functions
  mitk::Image::Pointer newImage = mitk::Image::New();
  mitk::Image::Pointer returnedImage;
  compositeFilter->SetInput(newImage);
  returnedImage = compositeFilter->GetInput();
  MITK_TEST_CONDITION_REQUIRED(newImage == returnedImage,"Get/Set empty image");

  compositeFilter->SetApplyTemporalMedianFilter(false);
  MITK_TEST_CONDITION_REQUIRED(compositeFilter->GetApplyTemporalMedianFilter()==false,"Get/Set ApplyTemporalMedianFilter");

  compositeFilter->SetApplyMedianFilter(false);
  MITK_TEST_CONDITION_REQUIRED(compositeFilter->GetApplyMedianFilter()==false,"Get/Set ApplyMedianFilter");

  compositeFilter->SetApplyThresholdFilter(false);
  MITK_TEST_CONDITION_REQUIRED(compositeFilter->GetApplyThresholdFilter()==false,"Get/Set ApplyThresholdFilter");

  compositeFilter->SetApplyBilateralFilter(false);
  MITK_TEST_CONDITION_REQUIRED(compositeFilter->GetApplyBilateralFilter()==false,"Get/Set ApplyBilateralFilter");

//-------------------------------------------------------------------------------------------------------

  MITK_TEST_END();

}
Esempio n. 7
0
/**
  This function is testing the class mitk::OclContextManager.
  */
int mitkOclBinaryThresholdImageFilterTest( int /*argc*/, char**/* argv[]*/ )
{
    MITK_TEST_BEGIN("mitkOclBinaryThresholdImageFilterTest");

    ServiceReference ref = GetModuleContext()->GetServiceReference<OclResourceService>();
    MITK_TEST_CONDITION_REQUIRED( ref != 0, "Got valid ServiceReference" );

    OclResourceService* resources = GetModuleContext()->GetService<OclResourceService>(ref);
    MITK_TEST_CONDITION_REQUIRED( resources != NULL, "OpenCL Resource service available." );

    cl_context gpuContext = resources->GetContext();
    MITK_TEST_CONDITION_REQUIRED( gpuContext != NULL, "Got not-null OpenCL context.");

    cl_device_id gpuDevice = resources->GetCurrentDevice();
    MITK_TEST_CONDITION_REQUIRED( gpuDevice != NULL, "Got not-null OpenCL device.");

    //Create a random reference image
    mitk::Image::Pointer inputImage = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(119, 204, 52, 1, // dimension
                                      1.0f, 1.0f, 1.0f, // spacing
                                      255, 0); // max, min
    MITK_TEST_CONDITION_REQUIRED( inputImage.IsNotNull(), "Input (random) mitk::Image object instantiated.");

    // FIXME: could also be random values
    int upperThr = 255;
    int lowerThr = 60;

    int outsideVal = 0;
    int insideVal = 100;

    mitk::OclBinaryThresholdImageFilter* oclFilter = new mitk::OclBinaryThresholdImageFilter;
    MITK_TEST_CONDITION_REQUIRED( oclFilter != NULL, "Filter was created. ");

    oclFilter->SetInput( inputImage );
    oclFilter->SetUpperThreshold( upperThr );
    oclFilter->SetLowerThreshold( lowerThr );
    oclFilter->SetOutsideValue( outsideVal );
    oclFilter->SetInsideValue( insideVal );

    oclFilter->Update();

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

    MITK_TEST_CONDITION_REQUIRED( outputImage.IsNotNull(), "Filter returned an not-NULL image. ");

    // reference computation
    typedef itk::Image< unsigned char, 3> ImageType;
    typedef itk::BinaryThresholdImageFilter< ImageType, ImageType > ThresholdFilterType;

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

    ThresholdFilterType::Pointer refThrFilter = ThresholdFilterType::New();
    refThrFilter->SetInput( itkInputImage );
    refThrFilter->SetLowerThreshold( lowerThr );
    refThrFilter->SetUpperThreshold( upperThr );
    refThrFilter->SetOutsideValue( outsideVal );
    refThrFilter->SetInsideValue( insideVal );

    typedef itk::SubtractImageFilter< ImageType, ImageType > SubtractFilterType;
    SubtractFilterType::Pointer subFilt = SubtractFilterType::New();

    ImageType::Pointer gpuReferenceImage = ImageType::New();
    CastToItkImage( oclFilter->GetOutput() ,gpuReferenceImage );

    subFilt->SetInput1( refThrFilter->GetOutput() );
    subFilt->SetInput2( gpuReferenceImage );

    typedef itk::StatisticsImageFilter< ImageType > StatFilterType;
    StatFilterType::Pointer stats = StatFilterType::New();
    stats->SetInput( subFilt->GetOutput() );
    stats->Update();

    MITK_TEST_CONDITION( stats->GetMaximum() == 0, "Maximal value in the difference image is 0.");
    MITK_TEST_CONDITION( stats->GetMinimum() == 0, "Minimal value in the difference image is 0.")

    MITK_TEST_END();
}
void QmitkTbssSkeletonizationView::Project()
{

  typedef itk::SkeletonizationFilter<FloatImageType, FloatImageType> SkeletonisationFilterType;
  typedef itk::ProjectionFilter ProjectionFilterType;
  typedef itk::DistanceMapFilter<FloatImageType, FloatImageType> DistanceMapFilterType;

  SkeletonisationFilterType::Pointer skeletonizer = SkeletonisationFilterType::New();



  std::vector<mitk::DataNode*> nodes = this->GetDataManagerSelection();


  mitk::Image::Pointer meanImage = mitk::Image::New();
  mitk::Image::Pointer subjects = mitk::Image::New();
  mitk::Image::Pointer tubular = mitk::Image::New();

  for ( int i=0; i<nodes.size(); i++ )
  {
    // process only on valid nodes
    mitk::BaseData* nodeData = nodes[i]->GetData();

    if(nodeData)
    {
      if(QString("Image").compare(nodeData->GetNameOfClass())==0)
      {
        mitk::Image* img = static_cast<mitk::Image*>(nodeData);
        if(img->GetDimension() == 3)
        {

          bool isBinary(false);
          nodes[i]->GetBoolProperty("binary", isBinary);


          if(isBinary)
          {
            tubular = img;
          }
          else
          {
            meanImage = img;
          }
        }

        else if(img->GetDimension() == 4)
        {
          subjects = img;
        }
      }
    }

  }

  Float4DImageType::Pointer allFA = ConvertToItk(subjects);

    // Calculate skeleton
  FloatImageType::Pointer itkImg = FloatImageType::New();
  mitk::CastToItkImage(meanImage, itkImg);
  skeletonizer->SetInput(itkImg);
  skeletonizer->Update();


  FloatImageType::Pointer output = skeletonizer->GetOutput();
  mitk::Image::Pointer mitkOutput = mitk::Image::New();
  mitk::CastToMitkImage(output, mitkOutput);
  AddToDataStorage(mitkOutput, "mean_FA_skeletonised");



  // Retrieve direction image needed later by the projection filter
  DirectionImageType::Pointer directionImg = skeletonizer->GetVectorImage();


  // Calculate distance image
  DistanceMapFilterType::Pointer distanceMapFilter = DistanceMapFilterType::New();
  distanceMapFilter->SetInput(output);
  distanceMapFilter->Update();
  FloatImageType::Pointer distanceMap = distanceMapFilter->GetOutput();

  if(m_Controls->m_OutputDistanceMap->isChecked())
  {
    mitk::Image::Pointer mitkDistance = mitk::Image::New();
    mitk::CastToMitkImage(distanceMap, mitkDistance);
    AddToDataStorage(mitkDistance, "distance map");
  }

  // Do projection

  // Ask a threshold to create a skeleton mask
  double threshold = -1.0;
  while(threshold == -1.0)
  {
    threshold = QInputDialog::getDouble(m_Controls->m_Skeletonize, tr("Specify the FA threshold"),
                                        tr("Threshold:"), QLineEdit::Normal,
                                        0.2);

    if(threshold < 0.0 || threshold > 1.0)
    {
      QMessageBox msgBox;
      msgBox.setText("Please choose a value between 0 and 1");
      msgBox.exec();
      threshold = -1.0;
    }
  }

  typedef itk::BinaryThresholdImageFilter<FloatImageType, CharImageType> ThresholdFilterType;
  ThresholdFilterType::Pointer thresholder = ThresholdFilterType::New();
  thresholder->SetInput(output);
  thresholder->SetLowerThreshold(threshold);
  thresholder->SetUpperThreshold(std::numeric_limits<float>::max());
  thresholder->SetOutsideValue(0);
  thresholder->SetInsideValue(1);
  thresholder->Update();


  CharImageType::Pointer thresholdedImg = thresholder->GetOutput();


  if(m_Controls->m_OutputMask->isChecked())
  {
    mitk::Image::Pointer mitkThresholded = mitk::Image::New();
    mitk::CastToMitkImage(thresholdedImg, mitkThresholded);
    std::string maskName = "skeleton_mask_at_" + boost::lexical_cast<std::string>(threshold);
    AddToDataStorage(mitkThresholded, maskName);
  }




  CharImageType::Pointer itkTubular = CharImageType::New();
  mitk::CastToItkImage(tubular, itkTubular);


  ProjectionFilterType::Pointer projectionFilter = ProjectionFilterType::New();
  projectionFilter->SetDistanceMap(distanceMap);
  projectionFilter->SetDirections(directionImg);
  projectionFilter->SetAllFA(allFA);
  projectionFilter->SetTube(itkTubular);
  projectionFilter->SetSkeleton(thresholdedImg);
  projectionFilter->Project();

  Float4DImageType::Pointer projected = projectionFilter->GetProjections();

  mitk::Image::Pointer mitkProjections = mitk::Image::New();
  mitk::CastToMitkImage(projected, mitkProjections);

  AddToDataStorage(mitkProjections, "all_FA_projected");



}
Esempio n. 9
0
void WholeCellSeg::BinarizationForRealBounds(){
	if( !nuc_im_set || !cyt_im_set ){
		std::cerr<<"Complete segmenting nuclei and set input imge before starting segmentation\n";
		return;
	}

	itk::SizeValueType size1=cyt_im_inp->GetLargestPossibleRegion().GetSize()[0];
	itk::SizeValueType size2=cyt_im_inp->GetLargestPossibleRegion().GetSize()[1];

	if( ( size1 != nuclab_inp->GetLargestPossibleRegion().GetSize()[0] ) ||
      	    ( size2 != nuclab_inp->GetLargestPossibleRegion().GetSize()[1] ) )
	{
		std::cerr<<"The input images must be of the same size\n";
		return;
	}

	typedef unsigned short int UShortPixelType;

	typedef itk::ImageRegionIteratorWithIndex< UShortImageType > IteratorType;
	typedef itk::ImageRegionConstIterator< UShortImageType > ConstIteratorType;

	typedef itk::Statistics::ScalarImageToHistogramGenerator< IntImageType > ScalarImageToHistogramGeneratorType;
	typedef ScalarImageToHistogramGeneratorType::HistogramType HistogramType;
	typedef itk::OtsuMultipleThresholdsCalculator< HistogramType > CalculatorType;
	typedef itk::RescaleIntensityImageFilter< UShortImageType, IntImageType > RescaleUsIntType;
	typedef itk::RescaleIntensityImageFilter< UShortImageType, UShortImageType > RescaleUsUsType;
	typedef itk::BinaryThresholdImageFilter< IntImageType, UShortImageType >  ThreshFilterType;
	typedef itk::BinaryThresholdImageFilter< UShortImageType, UShortImageType >  ThresholdFilterType;
	typedef itk::OrImageFilter< UShortImageType, UShortImageType, UShortImageType > OrFilterType;
 	typedef itk::BinaryBallStructuringElement< UShortPixelType, 2 > StructuringElementType;
	typedef itk::BinaryErodeImageFilter< UShortImageType, UShortImageType, StructuringElementType > ErodeFilterType;
	typedef itk::BinaryDilateImageFilter< UShortImageType, UShortImageType, StructuringElementType > DilateFilterType;

	unsigned char *in_Image;
	itk::SizeValueType ind=0;

//Call Yousef's binarization method if the number of bin levels is < 2
	if( num_levels < 2 ){
		bin_Image = (unsigned short *) malloc (size1*size2*sizeof(unsigned short));
		for(itk::SizeValueType j=0; j<size2; ++j)
			for(itk::SizeValueType i=0; i<size1; ++i)
				BIN_Image(i,j)=255;
		in_Image = (unsigned char *) malloc (size1*size2);
		if( ( in_Image == NULL ) || ( bin_Image == NULL ) ){
			std::cerr << "Memory allocation for binarization of image failed\n";
			return;
		}

		RescaleUsUsType::Pointer rescaleususfilter = RescaleUsUsType::New();
		rescaleususfilter->SetInput( cyt_im_inp );
		rescaleususfilter->SetOutputMaximum( itk::NumericTraits<unsigned char>::max() );
		rescaleususfilter->SetOutputMinimum( 0 );
		rescaleususfilter->Update();
		UShortImageType::Pointer resc_cyt_im = UShortImageType::New();
		resc_cyt_im = rescaleususfilter->GetOutput();
		ConstIteratorType pix_buf1( resc_cyt_im, resc_cyt_im->GetRequestedRegion() );
		for ( pix_buf1.GoToBegin(); !pix_buf1.IsAtEnd(); ++pix_buf1, ++ind )
		in_Image[ind]=(unsigned char)(pix_buf1.Get());

		int ok = 0;
		ok = Cell_Binarization_2D(in_Image,bin_Image, size1, size2, shift_bin);
		free( in_Image );

		if( !ok ){
			std::cerr<<"Binarization Failed\n";
			return;
		}

//copy the output binary image into the ITK image
		intermediate_bin_im_out = UShortImageType::New();
		UShortImageType::PointType origin;
		origin[0] = 0;
		origin[1] = 0;
		intermediate_bin_im_out->SetOrigin( origin );

		UShortImageType::IndexType start;
		start[0] = 0;  // first index on X
		start[1] = 0;  // first index on Y
		UShortImageType::SizeType  size;
		size[0] = size1;  // size along X
		size[1] = size2;  // size along Y

		UShortImageType::RegionType region;
		region.SetSize( size );
		region.SetIndex( start );

		intermediate_bin_im_out->SetRegions( region );
		intermediate_bin_im_out->Allocate();
		intermediate_bin_im_out->FillBuffer(0);
		intermediate_bin_im_out->Update();

		itk::SizeValueType dum,dum1;
		dum = 0;
		dum1 = USHRT_MAX;

		//unsigned int asd,asd1; asd=0; asd1=0;
		IteratorType iterator ( intermediate_bin_im_out, intermediate_bin_im_out->GetRequestedRegion() );
		for(itk::SizeValueType i=0; i < (size1*size2); ++i){
			if( bin_Image[i] )
			iterator.Set( dum1 );
			else
			iterator.Set( dum );
			++iterator;
		}
	}
//Call multi level binarization method if the number of bin levels is >= 2
	else{
		RescaleUsIntType::Pointer rescaleusintfilter = RescaleUsIntType::New();
		ScalarImageToHistogramGeneratorType::Pointer scalarImageToHistogramGenerator = ScalarImageToHistogramGeneratorType::New();
		rescaleusintfilter->SetInput( cyt_im_inp );
		rescaleusintfilter->SetOutputMaximum( itk::NumericTraits<unsigned short>::max() );
		rescaleusintfilter->SetOutputMinimum( 0 );
		rescaleusintfilter->Update();

		ThreshFilterType::Pointer threshfilter = ThreshFilterType::New();
		CalculatorType::Pointer calculator = CalculatorType::New();
		scalarImageToHistogramGenerator->SetNumberOfBins( 255 );
		calculator->SetNumberOfThresholds( num_levels );
		threshfilter->SetOutsideValue( (int)0 );
		threshfilter->SetInsideValue( (int)USHRT_MAX );
		scalarImageToHistogramGenerator->SetInput( rescaleusintfilter->GetOutput() );
		scalarImageToHistogramGenerator->Compute();
		calculator->SetInputHistogram( scalarImageToHistogramGenerator->GetOutput() );
		threshfilter->SetInput( rescaleusintfilter->GetOutput() );
		calculator->Update();
		const CalculatorType::OutputType &thresholdVector = calculator->GetOutput();
		CalculatorType::OutputType::const_iterator itNum = thresholdVector.begin();
		int lowerThreshold,upperThreshold;

		for( int i=0; i<(num_levels-num_levels_incl); ++i ) ++itNum;
		lowerThreshold = static_cast<unsigned short>(*itNum);
		upperThreshold = itk::NumericTraits<unsigned short>::max();

		threshfilter->SetLowerThreshold( lowerThreshold );
		threshfilter->SetUpperThreshold( upperThreshold );
		threshfilter->Update();

		intermediate_bin_im_out = UShortImageType::New();
		intermediate_bin_im_out = threshfilter->GetOutput();
	}

//Fill holes left by the nuclei
	ThresholdFilterType::Pointer binarythreshfilter = ThresholdFilterType::New();
	binarythreshfilter->SetInsideValue( USHRT_MAX );
	binarythreshfilter->SetOutsideValue( 0 );
	binarythreshfilter->SetLowerThreshold( 1 );
	binarythreshfilter->SetUpperThreshold( USHRT_MAX );
	binarythreshfilter->SetInput( nuclab_inp );
	OrFilterType::Pointer orfilter = OrFilterType::New();
	orfilter->SetInput1( binarythreshfilter->GetOutput() );
	orfilter->SetInput2( intermediate_bin_im_out );
//dialate and erode
	ErodeFilterType::Pointer  binaryErode  = ErodeFilterType::New();
	DilateFilterType::Pointer binaryDilate = DilateFilterType::New();
	StructuringElementType  structuringElement;
	structuringElement.SetRadius( 3 );  // 3x3 structuring element
	structuringElement.CreateStructuringElement();
	binaryErode->SetKernel( structuringElement );
	binaryErode->SetErodeValue( USHRT_MAX );
	binaryDilate->SetDilateValue( USHRT_MAX );
	binaryDilate->SetKernel( structuringElement );
	binaryErode->SetInput( binaryDilate->GetOutput() );
	binaryDilate->SetInput( orfilter->GetOutput() );
//erode and dialate
	ErodeFilterType::Pointer  binaryErode1  = ErodeFilterType::New();
	DilateFilterType::Pointer binaryDilate1 = DilateFilterType::New();
	binaryErode1->SetKernel(  structuringElement );
	binaryErode1->SetErodeValue( USHRT_MAX );
	binaryDilate1->SetDilateValue( USHRT_MAX );
	binaryDilate1->SetKernel( structuringElement );
	binaryErode1->SetInput( binaryErode->GetOutput() );
	binaryDilate1->SetInput( binaryErode1->GetOutput() );
	binaryDilate1->Update();
//Get pointer to the final binary image and return it to calling function
	UShortImageType::Pointer image_bin = UShortImageType::New();
	image_bin = binaryDilate1->GetOutput();
	bin_im_out = image_bin;
	bin_done = 1;

//Update bin array
	ind=0;
	if( draw_real_bounds ){
		ConstIteratorType pix_buf3( bin_im_out, bin_im_out->GetRequestedRegion() );
		for ( pix_buf3.GoToBegin(); !pix_buf3.IsAtEnd(); ++pix_buf3, ++ind )
		bin_Image[ind]=(pix_buf3.Get());
	}else
		free( bin_Image );
/*
	typedef itk::ImageFileWriter< UShortImageType > WriterType;
	WriterType::Pointer writer = WriterType::New();
	writer->SetFileName( "bin_info.tif" );
	writer->SetInput( bin_im_out );//RescaleIntIO1--finalO/P
	writer->Update();
*/
	return;
}
Esempio n. 10
0
//腐蚀操作
void segmentation::erosionOperation()//未用到
{
    const unsigned int Dimension = 3;
    typedef unsigned char   InputPixelType;
    typedef unsigned char   OutputPixelType;
    typedef itk::Image< InputPixelType,  Dimension >   InputImageType;
    typedef itk::Image< OutputPixelType, Dimension >   OutputImageType;
    typedef itk::ImageFileReader< InputImageType  >  ReaderType;
    typedef itk::ImageFileWriter< OutputImageType >  WriterType;
    typedef itk::BinaryThresholdImageFilter< InputImageType, InputImageType >  ThresholdFilterType;
    typedef itk::BinaryBallStructuringElement< 
        InputPixelType,
        Dimension  >             StructuringElementType;
    typedef itk::BinaryErodeImageFilter<
        InputImageType, 
        OutputImageType,
        StructuringElementType >  ErodeFilterType;
    ReaderType::Pointer reader = ReaderType::New();
    WriterType::Pointer writerErosion  = WriterType::New();
    ThresholdFilterType::Pointer thresholder = ThresholdFilterType::New();
    ErodeFilterType::Pointer  binaryErode  = ErodeFilterType::New();
    StructuringElementType  structuringElementErosion;
    reader->SetFileName( initFileName );//读入二值图
    reader->Update();
    InputImageType::Pointer inputImage = InputImageType::New();
    InputImageType::IndexType voxelIndex;
    inputImage = reader->GetOutput();
    InputImageType::SizeType imgSize = inputImage->GetLargestPossibleRegion().GetSize();
    long vol = 0;
    unsigned char temp;
    float r;
    for(int z = 0; z < imgSize[2]; z++)
        for(int y = 0; y < imgSize[1]; y++)
            for(int x = 0; x < imgSize[0]; x++)
            {
                voxelIndex[0] = x;
                voxelIndex[1] = y;
                voxelIndex[2] = z;
                temp = inputImage->GetPixel(voxelIndex);
                if(temp == 255)// 255 for PED
                    vol += 1;
            }
            r = pow((3 * vol) / (4 * PI), (1.0 / 3)) ;
            r = r / 20;//experiment data
            structuringElementErosion.SetRadius( r );  // 3x3 structuring element
            structuringElementErosion.CreateStructuringElement();
            binaryErode->SetKernel(  structuringElementErosion );
            //文件前缀名
            filePrefix = inputFileName;//char* to string
            filePrefix = filePrefix.substr(0, filePrefix.length() - 4);
            string erosionFileName;
            erosionFileName = filePrefix + "_erosionResult.mhd";
            strcpy(outputFileName, erosionFileName.c_str());//string to char*
            writerErosion->SetFileName(outputFileName);
            const InputPixelType lowerThreshold = 255;
            const InputPixelType upperThreshold = 255;
            thresholder->SetInput( reader->GetOutput() );
            InputPixelType background =   0;
            InputPixelType foreground = 255;
            thresholder->SetOutsideValue( background );
            thresholder->SetInsideValue(  foreground );
            thresholder->SetLowerThreshold( lowerThreshold );
            thresholder->SetUpperThreshold( upperThreshold );
            binaryErode->SetInput( thresholder->GetOutput() );
            binaryErode->SetErodeValue( foreground );
            writerErosion->SetInput( binaryErode->GetOutput() );
            writerErosion->Update();
            //binaryErode->GetOutput()->GetPixel(index);//获取像素值失败

            //腐蚀结果叠加到原图
            typedef itk::Image< unsigned short,  Dimension >   OriginalImageType;
            typedef itk::ImageFileReader<OriginalImageType>OriginalReaderType;
            OriginalReaderType::Pointer orignalImgreader = OriginalReaderType::New();
            OriginalImageType::Pointer originalImage = OriginalImageType::New();
            OriginalReaderType::IndexType originalImgVoxelIndex;
            reader->SetFileName(outputFileName);//读入腐蚀结果图像
            reader->Update();
            inputImage = reader->GetOutput();
            orignalImgreader->SetFileName(inputFileName);//读入原图像
            orignalImgreader->Update();
            originalImage = orignalImgreader->GetOutput();
            for(int z = 0; z < imgSize[2]; z++)
                for(int y = 0; y < imgSize[1]; y++)
                    for(int x = 0; x < imgSize[0]; x++)
                    {
                        voxelIndex[0] = x;
                        voxelIndex[1] = y;
                        voxelIndex[2] = z;
                        originalImgVoxelIndex[0] = x;
                        originalImgVoxelIndex[1] = y;
                        originalImgVoxelIndex[2] = z;
                        temp = inputImage->GetPixel(voxelIndex);
                        if(temp == 255)
                            originalImage->SetPixel(originalImgVoxelIndex, 65535);
                    }
                    //输出结果
                    typedef itk::ImageFileWriter<OriginalImageType>NewWriterType;
                    NewWriterType::Pointer writer = NewWriterType::New();
                    //文件前缀名
                    filePrefix = inputFileName;//char* to string
                    filePrefix = filePrefix.substr(0, filePrefix.length() - 4);
                    filePrefix = filePrefix + "_refinedResult.mhd";
                    strcpy(outputFileName, filePrefix.c_str());//string to char*
                    writer->SetFileName(outputFileName);
                    writer->SetInput(originalImage);
                    writer->Update();

                    emit returnInternalFileName(initResultFileName);//更新原视图
                    emit returnOutputFileName(outputFileName);//显示结果图
}
void unmix_threshold(InputImageType::Pointer im[],InputImageType::Pointer om[],int n,int GFP_channel,int AF_channel, int thresh)
{
	printf("Unnmixing %d channels ...\n",n);
	InputImageType::SizeType size = im[0]->GetLargestPossibleRegion().GetSize();

	printf("I'm here\n");
	MedianFilterType::Pointer filt[15];
	IteratorType iterator[15];
	//IteratorType assigniter[15];

	InputImageType::SizeType radius;
	radius[0]=1;
	radius[1]=1;
	radius[2]=1;

	InputImageType::SizeType imagesize = im[0]->GetLargestPossibleRegion().GetSize();
	InputImageType::IndexType imageindex;
	imageindex.Fill(0);
	InputImageType::RegionType region;
	region.SetSize(imagesize);
	region.SetIndex(imageindex);

	double max_values[15];
	for(int counter=0; counter<n; counter++)
	{
		printf("\tPerforming median filtering on channel %d ...",counter+1);
		filt[counter]=MedianFilterType::New();
		filt[counter]->SetRadius(radius);
		filt[counter]->SetInput(im[counter]);
		filt[counter]->Update();
		om[counter]=filt[counter]->GetOutput();
		iterator[counter]=IteratorType(om[counter],om[counter]->GetLargestPossibleRegion());
		iterator[counter].GoToBegin();
		max_values[counter]=-1;
		printf(" Done %d.\n",counter+1);
		for(;!iterator[counter].IsAtEnd();++iterator[counter])
		{
			if(max_values[counter]<iterator[counter].Value())
				max_values[counter] = iterator[counter].Value();

		}
		//	printf("Max%d = %lf\n",counter,max_values[counter]);
		iterator[counter].GoToBegin();
	}
	
	printf("Binarizing the Autofluoroscence Channel\n");
	ThresholdFilterType::Pointer tfilter = ThresholdFilterType::New();
	tfilter->SetInput(om[AF_channel]);
	tfilter->SetLowerThreshold(thresh);
	tfilter->SetUpperThreshold(255);
	tfilter->SetInsideValue(255);
	tfilter->SetOutsideValue(0);
	om[AF_channel] = tfilter->GetOutput();
	tfilter->Update();
	
	//int total_voxels = size[0]*size[1]*size[2];
	int num_processed = 0;
	
	//Removing Small components
	om[AF_channel] = getLargeComponents(om[AF_channel],thresh);

	printf("\tComputing foreground in AF channel ... ");
	for(;!iterator[0].IsAtEnd();)
	{
		num_processed++;
		unsigned char temp = iterator[2].Value();///max_values[co];
		if(temp > 0)
			{
				iterator[GFP_channel].Set(0);
				//iterator[0].Set(0);
			}
		
		for(int co = 0; co<n; co++)
		{
			++iterator[co];

		}
	}
	printf(" Done.\n");
}