Exemplo n.º 1
0
void mitk::PickingTool::OnPointAdded()
{
  if (m_WorkingData != this->GetWorkingData())
  {
    DataStorage *dataStorage = this->GetDataStorage();

    if (dataStorage->Exists(m_PointSetNode))
    {
      dataStorage->Remove(m_PointSetNode);
      dataStorage->Add(m_PointSetNode, this->GetWorkingData());
    }

    if (dataStorage->Exists(m_ResultNode))
    {
      dataStorage->Remove(m_ResultNode);
      dataStorage->Add(m_ResultNode, this->GetWorkingData());
    }

    m_WorkingData = this->GetWorkingData();
  }

  // Perform region growing/picking

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

  mitk::PointSet::PointType seedPoint = m_PointSet->GetPointSet(timeStep)->GetPoints()->Begin().Value();

  // as we want to pick a region from our segmentation image use the working data from ToolManager
  mitk::Image::Pointer orgImage = dynamic_cast<mitk::Image *>(m_ToolManager->GetWorkingData(0)->GetData());

  if (orgImage.IsNotNull())
  {
    if (orgImage->GetDimension() == 4)
    { // there may be 4D segmentation data even though we currently don't support that
      mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
      timeSelector->SetInput(orgImage);
      timeSelector->SetTimeNr(timeStep);
      timeSelector->UpdateLargestPossibleRegion();
      mitk::Image *timedImage = timeSelector->GetOutput();

      AccessByItk_2(timedImage, StartRegionGrowing, timedImage->GetGeometry(), seedPoint);
    }
    else if (orgImage->GetDimension() == 3)
    {
      AccessByItk_2(orgImage, StartRegionGrowing, orgImage->GetGeometry(), seedPoint);
    }
    this->m_PointSet->Clear();
  }
}
Exemplo n.º 2
0
void mitk::GeometryClipImageFilter::GenerateData()
{
  Image::ConstPointer input = this->GetInput();
  Image::Pointer output = this->GetOutput();

  if((output->IsInitialized()==false) || (m_ClippingGeometry.IsNull()))
    return;

  const Geometry2D * clippingGeometryOfCurrentTimeStep = NULL;

  if(m_TimeSlicedClippingGeometry.IsNull())
  {
    clippingGeometryOfCurrentTimeStep = dynamic_cast<const Geometry2D*>(m_ClippingGeometry.GetPointer());
  }
  else
  {
    clippingGeometryOfCurrentTimeStep = dynamic_cast<const Geometry2D*>(m_TimeSlicedClippingGeometry->GetGeometry3D(0));
  }

  if(clippingGeometryOfCurrentTimeStep == NULL)
    return;

  m_InputTimeSelector->SetInput(input);
  m_OutputTimeSelector->SetInput(this->GetOutput());

  mitk::Image::RegionType outputRegion = output->GetRequestedRegion();
  const mitk::TimeSlicedGeometry *outputTimeGeometry = output->GetTimeSlicedGeometry();
  const mitk::TimeSlicedGeometry *inputTimeGeometry = input->GetTimeSlicedGeometry();
  ScalarType timeInMS;

  int timestep=0;
  int tstart=outputRegion.GetIndex(3);
  int tmax=tstart+outputRegion.GetSize(3);

  int t;
  for(t=tstart;t<tmax;++t)
  {
    timeInMS = outputTimeGeometry->TimeStepToMS( t );

    timestep = inputTimeGeometry->MSToTimeStep( timeInMS );

    m_InputTimeSelector->SetTimeNr(timestep);
    m_InputTimeSelector->UpdateLargestPossibleRegion();
    m_OutputTimeSelector->SetTimeNr(t);
    m_OutputTimeSelector->UpdateLargestPossibleRegion();

    if(m_TimeSlicedClippingGeometry.IsNotNull())
    {
      timestep = m_TimeSlicedClippingGeometry->MSToTimeStep( timeInMS );
      if(m_TimeSlicedClippingGeometry->IsValidTime(timestep) == false)
        continue;

      clippingGeometryOfCurrentTimeStep = dynamic_cast<const Geometry2D*>(m_TimeSlicedClippingGeometry->GetGeometry3D(timestep));
    }

    AccessByItk_2(m_InputTimeSelector->GetOutput(),_InternalComputeClippedImage,this,clippingGeometryOfCurrentTimeStep);
  }

  m_TimeOfHeaderInitialization.Modified();
}
mitk::GIFFirstOrderStatistics::FeatureListType mitk::GIFFirstOrderStatistics::CalculateFeatures(const Image::Pointer & image, const Image::Pointer &mask)
{
  FeatureListType featureList;

  AccessByItk_2(image, CalculateFirstOrderStatistics, mask, featureList);

  return featureList;
}
Exemplo n.º 4
0
mitk::Image::Pointer mitk::LabelSetImageConverter::ConvertLabelSetImageToImage(const mitk::LabelSetImage::ConstPointer input)
{
  unsigned int numberOfLayers = input->GetNumberOfLayers();

  if (numberOfLayers == 0)
  {
    mitkThrow() << "Tried to convert LabelSetImage without layers";
  }

  mitk::Image::Pointer output;
  AccessByItk_2(input->GetLayerImage(0), VectorOfMitkImagesToMitkVectorImage, output, input);

  return output;
}
Exemplo n.º 5
0
void mitk::ImageStatisticsHolder::ComputeImageStatistics(int t, unsigned int component)
{
  // timestep valid?
  if (!m_Image->IsValidTimeStep(t)) return;

  // image modified?
  if (this->m_Image->GetMTime() > m_LastRecomputeTimeStamp.GetMTime())
    this->ResetImageStatistics();

  Expand(t+1);

  // do we have valid information already?
  if( m_ScalarMin[t] != itk::NumericTraits<ScalarType>::max() ||
      m_Scalar2ndMin[t] != itk::NumericTraits<ScalarType>::max() ) return; // Values already calculated before...

  // used to avoid statistics calculation on qball images. property will be replaced as soons as bug 17928 is merged and the diffusion image refactoring is complete.
  mitk::BoolProperty* isqball = dynamic_cast< mitk::BoolProperty* >( m_Image->GetProperty( "IsQballImage" ).GetPointer() );
  const mitk::PixelType pType = m_Image->GetPixelType(0);
  if(pType.GetNumberOfComponents() == 1 && (pType.GetPixelType() != itk::ImageIOBase::UNKNOWNPIXELTYPE) && (pType.GetPixelType() != itk::ImageIOBase::VECTOR) )
  {
    // recompute
    mitk::ImageTimeSelector::Pointer timeSelector = this->GetTimeSelector();
    if(timeSelector.IsNotNull())
    {
      timeSelector->SetTimeNr(t);
      timeSelector->UpdateLargestPossibleRegion();
      const mitk::Image* image = timeSelector->GetOutput();
      AccessByItk_2( image, _ComputeExtremaInItkImage, this, t );
    }
  }
  else if (pType.GetPixelType() == itk::ImageIOBase::VECTOR && (!isqball || !isqball->GetValue()))  // we have a vector image
  {
      // recompute
      mitk::ImageTimeSelector::Pointer timeSelector = this->GetTimeSelector();
      if(timeSelector.IsNotNull())
      {
        timeSelector->SetTimeNr(t);
        timeSelector->UpdateLargestPossibleRegion();
        const mitk::Image* image = timeSelector->GetOutput();
        AccessVectorPixelTypeByItk_n( image, _ComputeExtremaInItkVectorImage, (this, t, component) );
      }
  }
  else
  {
    m_ScalarMin[t] = 0;
    m_ScalarMax[t] = 255;
    m_Scalar2ndMin[t] = 0;
    m_Scalar2ndMax[t] = 255;
  }
}
Exemplo n.º 6
0
void mitk::PlaneCutFilter::GenerateData()
{
  if (!this->m_Plane)
  {
    return;
  }

  InputImageType *input = const_cast<InputImageType*>(this->GetInput());

  if (!input)
  {
    return;
  }

  //Allocate output.
  OutputImageType *output = this->GetOutput();

  output->Initialize(input);
  output->SetImportVolume(input->GetData());

  //Do the intersection.
  AccessByItk_2(output, _computeIntersection, this->m_Plane, input->GetGeometry());
}
Exemplo n.º 7
0
void mitk::ImageStatisticsHolder::ComputeImageStatistics(int t)
{
  // timestep valid?
  if (!m_Image->IsValidTimeStep(t)) return;

  // image modified?
  if (this->m_Image->GetMTime() > m_LastRecomputeTimeStamp.GetMTime())
    this->ResetImageStatistics();

  Expand(t+1);

  // do we have valid information already?
  if( m_ScalarMin[t] != itk::NumericTraits<ScalarType>::max() ||
      m_Scalar2ndMin[t] != itk::NumericTraits<ScalarType>::max() ) return; // Values already calculated before...

  const mitk::PixelType pType = m_Image->GetPixelType(0);
  if(pType.GetNumberOfComponents() == 1 && (pType.GetPixelType() != itk::ImageIOBase::UNKNOWNPIXELTYPE) && (pType.GetPixelType() != itk::ImageIOBase::VECTOR) )
  {
    // recompute
    mitk::ImageTimeSelector::Pointer timeSelector = this->GetTimeSelector();
    if(timeSelector.IsNotNull())
    {
      timeSelector->SetTimeNr(t);
      timeSelector->UpdateLargestPossibleRegion();
      const mitk::Image* image = timeSelector->GetOutput();
      AccessByItk_2( image, _ComputeExtremaInItkImage, this, t );
    }
  }
  else
  {
    m_ScalarMin[t] = 0;
    m_ScalarMax[t] = 255;
    m_Scalar2ndMin[t] = 0;
    m_Scalar2ndMax[t] = 255;
  }
}
Exemplo n.º 8
0
void mitk::RegionGrow3DTool::RunSegmentation()
{
    //safety if no pointSet or pointSet empty
    mitk::PointSet::Pointer seedPointSet = dynamic_cast<mitk::PointSet*> (m_PointSetNode->GetData());
    if (seedPointSet.IsNull())
    {
        return;
    }
    if (!(seedPointSet->GetSize() > 0))
    {
        return;
    }

    mitk::PointSet::PointType seedPoint = seedPointSet->GetPointSet()->GetPoints()->Begin().Value();

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

    if (image.IsNotNull())
    {
        m_LowerThreshold = static_cast<int> (m_RoiMin);
        m_UpperThreshold = static_cast<int> (m_RoiMax);
        AccessByItk_2(image, StartRegionGrowing, image->GetGeometry(), seedPoint);
    }
}
Exemplo n.º 9
0
void mitk::CLUtil::CountVoxel(mitk::Image::Pointer image, unsigned int label, unsigned int & count)
{
  AccessByItk_2(image, mitk::CLUtil::itkCountVoxel, label, count);
}
Exemplo n.º 10
0
void mitk::CLUtil::InsertLabel(mitk::Image::Pointer & image, mitk::Image::Pointer & maskImage, unsigned int label)
{
  AccessByItk_2(image, mitk::CLUtil::itkInsertLabel, maskImage, label);
}
Exemplo n.º 11
0
int main(int argc, char* argv[])
{
  mitkCommandLineParser parser;
  parser.setArgumentPrefix("--", "-");
  // required params
  parser.addArgument("image", "i", mitkCommandLineParser::InputImage, "Input Image", "Path to the input VTK polydata", us::Any(), false);
  parser.addArgument("output", "o", mitkCommandLineParser::OutputFile, "Output text file", "Target file. The output statistic is appended to this file.", us::Any(), false);

  parser.addArgument("gaussian","g",mitkCommandLineParser::String, "Gaussian Filtering of the input images", "Gaussian Filter. Followed by the used variances seperated by ';' ",us::Any());
  parser.addArgument("difference-of-gaussian","dog",mitkCommandLineParser::String, "Difference of Gaussian Filtering of the input images", "Difference of Gaussian Filter. Followed by the used variances seperated by ';' ",us::Any());
  parser.addArgument("laplace-of-gauss","log",mitkCommandLineParser::String, "Laplacian of Gaussian Filtering", "Laplacian of Gaussian Filter. Followed by the used variances seperated by ';' ",us::Any());
  parser.addArgument("hessian-of-gauss","hog",mitkCommandLineParser::String, "Hessian of Gaussian Filtering", "Hessian of Gaussian Filter. Followed by the used variances seperated by ';' ",us::Any());
  parser.addArgument("local-histogram", "lh", mitkCommandLineParser::String, "Local Histograms", "Calculate the local histogram based feature. Specify Offset and Delta, for exampel -3;0.6 ", us::Any());
  // Miniapp Infos
  parser.setCategory("Classification Tools");
  parser.setTitle("Global Image Feature calculator");
  parser.setDescription("Calculates different global statistics for a given segmentation / image combination");
  parser.setContributor("MBI");

  std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);

  if (parsedArgs.size()==0)
  {
    return EXIT_FAILURE;
  }
  if ( parsedArgs.count("help") || parsedArgs.count("h"))
  {
    return EXIT_SUCCESS;
  }
  bool useCooc = parsedArgs.count("cooccurence");

  mitk::Image::Pointer image = mitk::IOUtil::LoadImage(parsedArgs["image"].ToString());
  std::string filename=parsedArgs["output"].ToString();

  ////////////////////////////////////////////////////////////////
  // CAlculate Gaussian Features
  ////////////////////////////////////////////////////////////////
  MITK_INFO << "Check for Local Histogram...";
  if (parsedArgs.count("local-histogram"))
  {
    std::vector<mitk::Image::Pointer> outs;
    auto ranges = splitDouble(parsedArgs["local-histogram"].ToString(), ';');
    if (ranges.size() < 2)
    {
      MITK_INFO << "Missing Delta and Offset for Local Histogram";
    }
    else
    {
      AccessByItk_3(image, LocalHistograms, outs, ranges[0], ranges[1]);
      for (int i = 0; i < outs.size(); ++i)
      {
        std::string name = filename + "-lh" + us::any_value_to_string<int>(i)+".nii.gz";
        mitk::IOUtil::SaveImage(outs[i], name);
      }
    }
  }

  ////////////////////////////////////////////////////////////////
  // CAlculate Gaussian Features
  ////////////////////////////////////////////////////////////////
  MITK_INFO << "Check for Gaussian...";
  if (parsedArgs.count("gaussian"))
  {
    MITK_INFO << "Calculate Gaussian... " << parsedArgs["gaussian"].ToString();
    auto ranges = splitDouble(parsedArgs["gaussian"].ToString(),';');

    for (int i = 0; i < ranges.size(); ++i)
    {
      mitk::Image::Pointer output;
      AccessByItk_2(image, GaussianFilter, ranges[i], output);
      std::string name = filename + "-gaussian-" + us::any_value_to_string(ranges[i])+".nii.gz";
      mitk::IOUtil::SaveImage(output, name);
    }
  }

  ////////////////////////////////////////////////////////////////
  // CAlculate Difference of Gaussian Features
  ////////////////////////////////////////////////////////////////
  MITK_INFO << "Check for DoG...";
  if (parsedArgs.count("difference-of-gaussian"))
  {
    MITK_INFO << "Calculate Difference of Gaussian... " << parsedArgs["difference-of-gaussian"].ToString();
    auto ranges = splitDouble(parsedArgs["difference-of-gaussian"].ToString(),';');

    for (int i = 0; i < ranges.size(); ++i)
    {
      mitk::Image::Pointer output;
      AccessByItk_2(image, DifferenceOfGaussFilter, ranges[i], output);
      std::string name = filename + "-dog-" + us::any_value_to_string(ranges[i])+".nii.gz";
      mitk::IOUtil::SaveImage(output, name);
    }
  }

  MITK_INFO << "Check for LoG...";
  ////////////////////////////////////////////////////////////////
  // CAlculate Laplacian Of Gauss Features
  ////////////////////////////////////////////////////////////////
  if (parsedArgs.count("laplace-of-gauss"))
  {
    MITK_INFO << "Calculate LoG... " << parsedArgs["laplace-of-gauss"].ToString();
    auto ranges = splitDouble(parsedArgs["laplace-of-gauss"].ToString(),';');

    for (int i = 0; i < ranges.size(); ++i)
    {
      mitk::Image::Pointer output;
      AccessByItk_2(image, LaplacianOfGaussianFilter, ranges[i], output);
      std::string name = filename + "-log-" + us::any_value_to_string(ranges[i])+".nii.gz";
      mitk::IOUtil::SaveImage(output, name);
    }
  }

  MITK_INFO << "Check for HoG...";
  ////////////////////////////////////////////////////////////////
  // CAlculate Hessian Of Gauss Features
  ////////////////////////////////////////////////////////////////
  if (parsedArgs.count("hessian-of-gauss"))
  {
    MITK_INFO << "Calculate HoG... " << parsedArgs["hessian-of-gauss"].ToString();
    auto ranges = splitDouble(parsedArgs["hessian-of-gauss"].ToString(),';');

    for (int i = 0; i < ranges.size(); ++i)
    {
      std::vector<mitk::Image::Pointer> outs;
      outs.push_back(mitk::Image::New());
      outs.push_back(mitk::Image::New());
      outs.push_back(mitk::Image::New());
      AccessByItk_2(image, HessianOfGaussianFilter, ranges[i], outs);
      std::string name = filename + "-hog0-" + us::any_value_to_string(ranges[i])+".nii.gz";
      mitk::IOUtil::SaveImage(outs[0], name);
      name = filename + "-hog1-" + us::any_value_to_string(ranges[i])+".nii.gz";
      mitk::IOUtil::SaveImage(outs[1], name);
      name = filename + "-hog2-" + us::any_value_to_string(ranges[i])+".nii.gz";
      mitk::IOUtil::SaveImage(outs[2], name);
    }
  }

  return 0;
}
Exemplo n.º 12
0
  static void TestOverlay(mitk::Image::Pointer original,
                          mitk::Image::Pointer truth,
                          const double lower,
                          const double upper)
  {
    mitk::Image::Pointer overlayImage;
    const double th[] = {lower, upper};
    typedef itk::Image<unsigned int, 3> ImageType;
    ImageType::Pointer itkOverlayImage = ImageType::New();

    AccessByItk_2(original, InternalThreshold, overlayImage, th);
    /*
        AccessFixedDimensionByItk_2( original, InternalThreshold2,
                                     3, itkOverlayImage,
                                     th );

        overlayImage = mitk::ImportItkImage( itkOverlayImage );
    */
    // mitk::IOUtil::Save(truth, "/tmp/truth_TestOverlay.nii");
    try
    {
      // mitk::Image::Pointer temp = overlayImage;
      mitk::IOUtil::Save(overlayImage, "/tmp/overlayImage_TestOverlay.nrrd");
    }
    catch (const itk::ExceptionObject &e)
    {
      MITK_ERROR << "Save image: exception : " << e.what();
    }

    typedef itk::Image<unsigned int, 3> InputImageType;

    InputImageType::Pointer overlayItk;
    try
    {
      mitk::CastToItkImage(overlayImage, overlayItk);
    }
    catch (const mitk::Exception &e)
    {
      MITK_ERROR << "(CAST) Catched exception while creating accessor " << e.what();
      // MITK_TEST_FAILED_MSG("Exception for ouverlay image");
    }

    /*
        typedef  itk::ImageFileWriter< InputImageType  > WriterType;
        WriterType::Pointer writer = WriterType::New();
        writer->SetFileName("/tmp/overlayITK_TestOverlay.nii");
        writer->SetInput(overlayItk);
        writer->Update();
    */
    InputImageType::Pointer truthItk;
    mitk::CastToItkImage(truth, truthItk);

    bool difference = false;
    /*
        try
        {
          typedef unsigned int TPixel;

          itk::ImageRegionConstIteratorWithIndex< InputImageType > iter( truthItk, truthItk->GetLargestPossibleRegion()
       );
          iter.GoToBegin();

          mitk::ImagePixelReadAccessor< TPixel, 3 > readAccessor( overlayImage, overlayImage->GetVolumeData(0),
       mitk::ImageAccessorBase::ExceptionIfLocked );

          while( !iter.IsAtEnd() )
          {
            TPixel ref = iter.Get();
            TPixel val = readAccessor.GetPixelByIndex( iter.GetIndex() );

            difference |= ( ref != val );
            //if( difference )
            //{
              std::cout << iter.GetIndex() << ":" << ref << " ? " << val << "\n";
            //}
            ++iter;
          }
        }
        catch( const mitk::Exception &e)
        {
          MITK_ERROR << "Catched exception while creating accessor "<< e.what();
          //MITK_TEST_FAILED_MSG("Exception for ouverlay image");
        }



    */

    /*
        typedef itk::Testing::ComparisonImageFilter
          <InputImageType, InputImageType> ComparisonImageFilterType;
        ComparisonImageFilterType::Pointer comp =
          ComparisonImageFilterType::New();
        comp->SetValidInput(truthItk);
        comp->SetTestInput(overlayItk);
        try
        {
          comp->Update();
        }
        catch( const itk::ExceptionObject& e)
        {
          MITK_ERROR << "ITK Exception: " << e.what();
        }
    */
    typedef unsigned int TPixel;

    itk::ImageRegionConstIteratorWithIndex<InputImageType> iter(truthItk, truthItk->GetLargestPossibleRegion());
    itk::ImageRegionConstIteratorWithIndex<InputImageType> iter2(overlayItk, overlayItk->GetLargestPossibleRegion());
    iter.GoToBegin();

    unsigned int counter = 0;
    while (!iter.IsAtEnd() && !iter2.IsAtEnd())
    {
      TPixel ref = iter.Get();
      TPixel val = iter2.Get();

      if (ref != val)
      {
        counter++;
        //     std::cout << iter.GetIndex() << ":" << ref << " ? " << val << "\n";
      }

      ++iter;
      ++iter2;
    }

    std::cout << "Differs in " << counter << "voxels" << std::endl;

    MITK_TEST_CONDITION_REQUIRED(
      // comp->GetNumberOfPixelsWithDifferences() == 0,
      counter == 0,
      "Comparing overlay with ground truth")
  }
void QmitkAdaptiveRegionGrowingToolGUI::RunSegmentation()
{
  if (m_InputImageNode.IsNull())
  {
    QMessageBox::information( NULL, "Adaptive Region Growing functionality", "Please specify the image in Datamanager!");
    return;
  }

  mitk::DataNode::Pointer node = m_RegionGrow3DTool->GetPointSetNode();

  if (node.IsNull())
  {
    QMessageBox::information( NULL, "Adaptive Region Growing functionality", "Please insert a seed point inside the image.\n\nFirst press the \"Define Seed Point\" button,\nthen click left mouse button inside the image.");
    return;
  }

  //safety if no pointSet or pointSet empty
  mitk::PointSet::Pointer seedPointSet = dynamic_cast<mitk::PointSet*> (node->GetData());
  if (seedPointSet.IsNull())
  {
    m_Controls.m_pbRunSegmentation->setEnabled(true);
    QMessageBox::information( NULL, "Adaptive Region Growing functionality", "The seed point is empty! Please choose a new seed point.");
    return;
  }

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

  if (!(seedPointSet->GetSize(timeStep)))
  {
    m_Controls.m_pbRunSegmentation->setEnabled(true);
    QMessageBox::information( NULL, "Adaptive Region Growing functionality", "The seed point is empty! Please choose a new seed point.");
    return;
  }

  QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );

  mitk::PointSet::PointType seedPoint = seedPointSet->GetPointSet(timeStep)->GetPoints()->Begin().Value();

  mitk::Image::Pointer orgImage = dynamic_cast<mitk::Image*> (m_InputImageNode->GetData());

  if (orgImage.IsNotNull())
  {
      if (orgImage->GetDimension() == 4)
      {
          mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New();
          timeSelector->SetInput(orgImage);
          timeSelector->SetTimeNr( timeStep );
          timeSelector->UpdateLargestPossibleRegion();
          mitk::Image* timedImage = timeSelector->GetOutput();
          AccessByItk_2( timedImage , StartRegionGrowing, timedImage->GetGeometry(), seedPoint);
      }
      else if (orgImage->GetDimension() == 3)
      {
          //QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); //set the cursor to waiting
          AccessByItk_2(orgImage, StartRegionGrowing, orgImage->GetGeometry(), seedPoint);
          //QApplication::restoreOverrideCursor();//reset cursor
      }
      else
      {
          QApplication::restoreOverrideCursor();//reset cursor
          QMessageBox::information( NULL, "Adaptive Region Growing functionality", "Only images of dimension 3 or 4 can be processed!");
          return;
      }
  }
  EnableControls(true); // Segmentation ran successfully, so enable all controls.
  node->SetVisibility(true);
  QApplication::restoreOverrideCursor();//reset cursor

}
Exemplo n.º 14
0
int main(int argc, char* argv[])
{
  mitkCommandLineParser parser;
  parser.setArgumentPrefix("--", "-");
  // required params
  parser.addArgument("planar", "p", mitkCommandLineParser::Directory, "Input Polydata", "Path to the input VTK polydata", us::Any(), false, false, false, mitkCommandLineParser::Input);
  parser.addArgument("image", "i", mitkCommandLineParser::Directory, "Input Image", "Image which defines the dimensions of the Segmentation", us::Any(), false, false, false, mitkCommandLineParser::Output);
  parser.addArgument("output", "o", mitkCommandLineParser::File, "Output file", "Output file. ", us::Any(), false, false, false, mitkCommandLineParser::Input);
  // Miniapp Infos
  parser.setCategory("Classification Tools");
  parser.setTitle("Planar Data to Nrrd Segmentation");
  parser.setDescription("Creates a Nrrd segmentation based on a 2d-vtk polydata.");
  parser.setContributor("MBI");

  std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);

  if (parsedArgs.size()==0)
  {
    return EXIT_FAILURE;
  }
  if ( parsedArgs.count("help") || parsedArgs.count("h"))
  {
    return EXIT_SUCCESS;
  }

  try
  {
    mitk::BaseData::Pointer data = mitk::IOUtil::Load(parsedArgs["planar"].ToString())[0];
    mitk::PlanarFigure::Pointer planar = dynamic_cast<mitk::PlanarFigure*>(data.GetPointer());

    mitk::Image::Pointer image = mitk::IOUtil::Load<mitk::Image>(parsedArgs["image"].ToString());

    mitk::PlanarFigureMaskGenerator::Pointer pfMaskGen = mitk::PlanarFigureMaskGenerator::New();
    pfMaskGen->SetPlanarFigure(planar);
    pfMaskGen->SetTimeStep(0);
    pfMaskGen->SetInputImage(image.GetPointer());

    mitk::Image::Pointer mask = pfMaskGen->GetMask();
    unsigned int axis = pfMaskGen->GetPlanarFigureAxis();
    unsigned int slice = pfMaskGen->GetPlanarFigureSlice();

    //itk::Image<unsigned short, 3>::IndexType index;
    mitk::Image::Pointer fullMask;
    MaskParameter param;
    param.slice = slice;
    param.axis = axis;
    param.mask = mask;
    AccessByItk_2(image, CreateNewMask, param, fullMask);

    std::string saveAs = parsedArgs["output"].ToString();
    MITK_INFO << "Save as: " << saveAs;
    mitk::IOUtil::Save(pfMaskGen->GetMask(), saveAs);
    mitk::IOUtil::Save(fullMask, saveAs);

    return 0;
  }
  catch (...)
  {
    return EXIT_FAILURE;
  }
}
Exemplo n.º 15
0
int main(int argc, char* argv[])
{
  // Commented : Updated to a common interface, include, if possible, mask is type unsigned short, uses Quantification, Comments
  //                                 Name follows standard scheme with Class Name::Feature Name
  // Commented 2: Updated to use automatic inclusion of list of parameters if required.
  mitk::GIFImageDescriptionFeatures::Pointer ipCalculator = mitk::GIFImageDescriptionFeatures::New(); // Commented 2, Tested
  mitk::GIFFirstOrderStatistics::Pointer firstOrderCalculator = mitk::GIFFirstOrderStatistics::New(); //Commented 2
  mitk::GIFFirstOrderHistogramStatistics::Pointer firstOrderHistoCalculator = mitk::GIFFirstOrderHistogramStatistics::New(); // Commented 2, Tested
  mitk::GIFFirstOrderNumericStatistics::Pointer firstOrderNumericCalculator = mitk::GIFFirstOrderNumericStatistics::New(); // Commented 2, Tested
  mitk::GIFVolumetricStatistics::Pointer volCalculator = mitk::GIFVolumetricStatistics::New();   // Commented 2, Tested
  mitk::GIFVolumetricDensityStatistics::Pointer voldenCalculator = mitk::GIFVolumetricDensityStatistics::New(); // Commented 2, Tested
  mitk::GIFCooccurenceMatrix::Pointer coocCalculator = mitk::GIFCooccurenceMatrix::New(); // Commented 2, Will not be tested
  mitk::GIFCooccurenceMatrix2::Pointer cooc2Calculator = mitk::GIFCooccurenceMatrix2::New(); //Commented 2
  mitk::GIFNeighbouringGreyLevelDependenceFeature::Pointer ngldCalculator = mitk::GIFNeighbouringGreyLevelDependenceFeature::New(); //Commented 2, Tested
  mitk::GIFGreyLevelRunLength::Pointer rlCalculator = mitk::GIFGreyLevelRunLength::New(); // Commented 2
  mitk::GIFGreyLevelSizeZone::Pointer glszCalculator = mitk::GIFGreyLevelSizeZone::New(); // Commented 2, Tested
  mitk::GIFGreyLevelDistanceZone::Pointer gldzCalculator = mitk::GIFGreyLevelDistanceZone::New(); //Commented 2, Tested
  mitk::GIFLocalIntensity::Pointer lociCalculator = mitk::GIFLocalIntensity::New(); //Commented 2, Tested
  mitk::GIFIntensityVolumeHistogramFeatures::Pointer ivohCalculator = mitk::GIFIntensityVolumeHistogramFeatures::New(); // Commented 2
  mitk::GIFNeighbourhoodGreyToneDifferenceFeatures::Pointer ngtdCalculator = mitk::GIFNeighbourhoodGreyToneDifferenceFeatures::New(); //Commented 2, Tested
  mitk::GIFCurvatureStatistic::Pointer curvCalculator = mitk::GIFCurvatureStatistic::New(); //Commented 2, Tested

  std::vector<mitk::AbstractGlobalImageFeature::Pointer> features;
  features.push_back(volCalculator.GetPointer());
  features.push_back(voldenCalculator.GetPointer());
  features.push_back(curvCalculator.GetPointer());
  features.push_back(firstOrderCalculator.GetPointer());
  features.push_back(firstOrderNumericCalculator.GetPointer());
  features.push_back(firstOrderHistoCalculator.GetPointer());
  features.push_back(ivohCalculator.GetPointer());
  features.push_back(lociCalculator.GetPointer());
  features.push_back(coocCalculator.GetPointer());
  features.push_back(cooc2Calculator.GetPointer());
  features.push_back(ngldCalculator.GetPointer());
  features.push_back(rlCalculator.GetPointer());
  features.push_back(glszCalculator.GetPointer());
  features.push_back(gldzCalculator.GetPointer());
  features.push_back(ipCalculator.GetPointer());
  features.push_back(ngtdCalculator.GetPointer());

  mitkCommandLineParser parser;
  parser.setArgumentPrefix("--", "-");
  mitk::cl::GlobalImageFeaturesParameter param;
  param.AddParameter(parser);

  parser.addArgument("--","-", mitkCommandLineParser::String, "---", "---", us::Any(),true);
  for (auto cFeature : features)
  {
    cFeature->AddArguments(parser);
  }

  parser.addArgument("--", "-", mitkCommandLineParser::String, "---", "---", us::Any(), true);
  parser.addArgument("description","d",mitkCommandLineParser::String,"Text","Description that is added to the output",us::Any());
  parser.addArgument("direction", "dir", mitkCommandLineParser::String, "Int", "Allows to specify the direction for Cooc and RL. 0: All directions, 1: Only single direction (Test purpose), 2,3,4... Without dimension 0,1,2... ", us::Any());
  parser.addArgument("slice-wise", "slice", mitkCommandLineParser::String, "Int", "Allows to specify if the image is processed slice-wise (number giving direction) ", us::Any());
  parser.addArgument("output-mode", "omode", mitkCommandLineParser::Int, "Int", "Defines if the results of an image / slice are written in a single row (0 , default) or column (1).");

  // Miniapp Infos
  parser.setCategory("Classification Tools");
  parser.setTitle("Global Image Feature calculator");
  parser.setDescription("Calculates different global statistics for a given segmentation / image combination");
  parser.setContributor("MBI");

  std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
  param.ParseParameter(parsedArgs);

  if (parsedArgs.size()==0)
  {
    return EXIT_FAILURE;
  }
  if ( parsedArgs.count("help") || parsedArgs.count("h"))
  {
    return EXIT_SUCCESS;
  }

  //bool savePNGofSlices = true;
  //std::string folderForPNGOfSlices = "E:\\tmp\\bonekamp\\fig\\";

  std::string version = "Version: 1.22";
  MITK_INFO << version;

  std::ofstream log;
  if (param.useLogfile)
  {
    log.open(param.logfilePath, std::ios::app);
    log << std::endl;
    log << version;
    log << "Image: " << param.imagePath;
    log << "Mask: " << param.maskPath;
  }


  if (param.useDecimalPoint)
  {
    std::cout.imbue(std::locale(std::cout.getloc(), new punct_facet<char>(param.decimalPoint)));
  }

  mitk::Image::Pointer image;
  mitk::Image::Pointer mask;

  mitk::Image::Pointer tmpImage = mitk::IOUtil::Load<mitk::Image>(param.imagePath);
  mitk::Image::Pointer tmpMask = mitk::IOUtil::Load<mitk::Image>(param.maskPath);
  image = tmpImage;
  mask = tmpMask;

  mitk::Image::Pointer morphMask = mask;
  if (param.useMorphMask)
  {
    morphMask = mitk::IOUtil::Load<mitk::Image>(param.morphPath);
  }

  log << " Check for Dimensions -";
  if ((image->GetDimension() != mask->GetDimension()))
  {
    MITK_INFO << "Dimension of image does not match. ";
    MITK_INFO << "Correct one image, may affect the result";
    if (image->GetDimension() == 2)
    {
      mitk::Convert2Dto3DImageFilter::Pointer multiFilter2 = mitk::Convert2Dto3DImageFilter::New();
      multiFilter2->SetInput(tmpImage);
      multiFilter2->Update();
      image = multiFilter2->GetOutput();
    }
    if (mask->GetDimension() == 2)
    {
      mitk::Convert2Dto3DImageFilter::Pointer multiFilter3 = mitk::Convert2Dto3DImageFilter::New();
      multiFilter3->SetInput(tmpMask);
      multiFilter3->Update();
      mask = multiFilter3->GetOutput();
    }
  }

  int writeDirection = 0;
  if (parsedArgs.count("output-mode"))
  {
    writeDirection = us::any_cast<int>(parsedArgs["output-mode"]);
  }

  log << " Check for Resolution -";
  if (param.resampleToFixIsotropic)
  {
    mitk::Image::Pointer newImage = mitk::Image::New();
    AccessByItk_2(image, ResampleImage, param.resampleResolution, newImage);
    image = newImage;
  }
  if ( ! mitk::Equal(mask->GetGeometry(0)->GetOrigin(), image->GetGeometry(0)->GetOrigin()))
  {
    MITK_INFO << "Not equal Origins";
    if (param.ensureSameSpace)
    {
      MITK_INFO << "Warning!";
      MITK_INFO << "The origin of the input image and the mask do not match. They are";
      MITK_INFO << "now corrected. Please check to make sure that the images still match";
      image->GetGeometry(0)->SetOrigin(mask->GetGeometry(0)->GetOrigin());
    } else
    {
      return -1;
    }
  }

  log << " Resample if required -";
  if (param.resampleMask)
  {
    mitk::Image::Pointer newMaskImage = mitk::Image::New();
    AccessByItk_2(mask, ResampleMask, image, newMaskImage);
    mask = newMaskImage;
  }

  log << " Check for Equality -";
  if ( ! mitk::Equal(mask->GetGeometry(0)->GetSpacing(), image->GetGeometry(0)->GetSpacing()))
  {
    MITK_INFO << "Not equal Spacing";
    if (param.ensureSameSpace)
    {
      MITK_INFO << "Warning!";
      MITK_INFO << "The spacing of the mask was set to match the spacing of the input image.";
      MITK_INFO << "This might cause unintended spacing of the mask image";
      image->GetGeometry(0)->SetSpacing(mask->GetGeometry(0)->GetSpacing());
    } else
    {
      MITK_INFO << "The spacing of the mask and the input images is not equal.";
      MITK_INFO << "Terminating the programm. You may use the '-fi' option";
      return -1;
    }
  }

  int direction = 0;
  if (parsedArgs.count("direction"))
  {
    direction = mitk::cl::splitDouble(parsedArgs["direction"].ToString(), ';')[0];
  }

  MITK_INFO << "Start creating Mask without NaN";

  mitk::Image::Pointer maskNoNaN = mitk::Image::New();
  AccessByItk_2(image, CreateNoNaNMask,  mask, maskNoNaN);
  //CreateNoNaNMask(mask, image, maskNoNaN);


  bool sliceWise = false;
  int sliceDirection = 0;
  unsigned int currentSlice = 0;
  bool imageToProcess = true;

  std::vector<mitk::Image::Pointer> floatVector;
  std::vector<mitk::Image::Pointer> maskVector;
  std::vector<mitk::Image::Pointer> maskNoNaNVector;
  std::vector<mitk::Image::Pointer> morphMaskVector;

  if ((parsedArgs.count("slice-wise")) && image->GetDimension() > 2)
  {
    MITK_INFO << "Enabled slice-wise";
    sliceWise = true;
    sliceDirection = mitk::cl::splitDouble(parsedArgs["slice-wise"].ToString(), ';')[0];
    MITK_INFO << sliceDirection;
    ExtractSlicesFromImages(image, mask, maskNoNaN, morphMask, sliceDirection, floatVector, maskVector, maskNoNaNVector, morphMaskVector);
    MITK_INFO << "Slice";
  }

  log << " Configure features -";
  for (auto cFeature : features)
  {
    if (param.defineGlobalMinimumIntensity)
    {
      cFeature->SetMinimumIntensity(param.globalMinimumIntensity);
      cFeature->SetUseMinimumIntensity(true);
    }
    if (param.defineGlobalMaximumIntensity)
    {
      cFeature->SetMaximumIntensity(param.globalMaximumIntensity);
      cFeature->SetUseMaximumIntensity(true);
    }
    if (param.defineGlobalNumberOfBins)
    {
      cFeature->SetBins(param.globalNumberOfBins);
      MITK_INFO << param.globalNumberOfBins;
    }
    cFeature->SetParameter(parsedArgs);
    cFeature->SetDirection(direction);
    cFeature->SetEncodeParameters(param.encodeParameter);
  }

  bool addDescription = parsedArgs.count("description");
  mitk::cl::FeatureResultWritter writer(param.outputPath, writeDirection);

  if (param.useDecimalPoint)
  {
    writer.SetDecimalPoint(param.decimalPoint);
  }

  std::string description = "";
  if (addDescription)
  {
    description = parsedArgs["description"].ToString();
  }

  mitk::Image::Pointer cImage = image;
  mitk::Image::Pointer cMask = mask;
  mitk::Image::Pointer cMaskNoNaN = maskNoNaN;
  mitk::Image::Pointer cMorphMask = morphMask;

  if (param.useHeader)
  {
    writer.AddColumn("SoftwareVersion");
    writer.AddColumn("Patient");
    writer.AddColumn("Image");
    writer.AddColumn("Segmentation");
  }

  // Create a QTApplication and a Datastorage
  // This is necessary in order to save screenshots of
  // each image / slice.
  QApplication qtapplication(argc, argv);
  QmitkRegisterClasses();

  std::vector<mitk::AbstractGlobalImageFeature::FeatureListType> allStats;

  log << " Begin Processing -";
  while (imageToProcess)
  {
    if (sliceWise)
    {
      cImage = floatVector[currentSlice];
      cMask = maskVector[currentSlice];
      cMaskNoNaN = maskNoNaNVector[currentSlice];
      cMorphMask = morphMaskVector[currentSlice];
      imageToProcess = (floatVector.size()-1 > (currentSlice)) ? true : false ;
    }
    else
    {
      imageToProcess = false;
    }

    if (param.writePNGScreenshots)
    {
      SaveSliceOrImageAsPNG(cImage, cMask, param.pngScreenshotsPath, currentSlice);
    }
    if (param.writeAnalysisImage)
    {
      mitk::IOUtil::Save(cImage, param.anaylsisImagePath);
    }
    if (param.writeAnalysisMask)
    {
      mitk::IOUtil::Save(cMask, param.analysisMaskPath);
    }

    mitk::AbstractGlobalImageFeature::FeatureListType stats;

    for (auto cFeature : features)
    {
      log << " Calculating " << cFeature->GetFeatureClassName() << " -";
      cFeature->SetMorphMask(cMorphMask);
      cFeature->CalculateFeaturesUsingParameters(cImage, cMask, cMaskNoNaN, stats);
    }

    for (std::size_t i = 0; i < stats.size(); ++i)
    {
      std::cout << stats[i].first << " - " << stats[i].second << std::endl;
    }

    writer.AddHeader(description, currentSlice, stats, param.useHeader, addDescription);
    if (true)
    {
      writer.AddSubjectInformation(MITK_REVISION);
      writer.AddSubjectInformation(param.imageFolder);
      writer.AddSubjectInformation(param.imageName);
      writer.AddSubjectInformation(param.maskName);
    }
    writer.AddResult(description, currentSlice, stats, param.useHeader, addDescription);

    allStats.push_back(stats);
    ++currentSlice;
  }

  log << " Process Slicewise -";
  if (sliceWise)
  {
    mitk::AbstractGlobalImageFeature::FeatureListType statMean, statStd;
    for (std::size_t i = 0; i < allStats[0].size(); ++i)
    {
      auto cElement1 = allStats[0][i];
      cElement1.first = "SliceWise Mean " + cElement1.first;
      cElement1.second = 0.0;
      auto cElement2 = allStats[0][i];
      cElement2.first = "SliceWise Var. " + cElement2.first;
      cElement2.second = 0.0;
      statMean.push_back(cElement1);
      statStd.push_back(cElement2);
    }

    for (auto cStat : allStats)
    {
      for (std::size_t i = 0; i < cStat.size(); ++i)
      {
        statMean[i].second += cStat[i].second / (1.0*allStats.size());
      }
    }

    for (auto cStat : allStats)
    {
      for (std::size_t i = 0; i < cStat.size(); ++i)
      {
        statStd[i].second += (cStat[i].second - statMean[i].second)*(cStat[i].second - statMean[i].second) / (1.0*allStats.size());
      }
    }

    for (std::size_t i = 0; i < statMean.size(); ++i)
    {
      std::cout << statMean[i].first << " - " << statMean[i].second << std::endl;
      std::cout << statStd[i].first << " - " << statStd[i].second << std::endl;
    }
    if (true)
    {
      writer.AddSubjectInformation(MITK_REVISION);
      writer.AddSubjectInformation(param.imageFolder);
      writer.AddSubjectInformation(param.imageName);
      writer.AddSubjectInformation(param.maskName + " - Mean");
    }
    writer.AddResult(description, currentSlice, statMean, param.useHeader, addDescription);
    if (true)
    {
      writer.AddSubjectInformation(MITK_REVISION);
      writer.AddSubjectInformation(param.imageFolder);
      writer.AddSubjectInformation(param.imageName);
      writer.AddSubjectInformation(param.maskName + " - Var.");
    }
    writer.AddResult(description, currentSlice, statStd, param.useHeader, addDescription);
  }

  if (param.useLogfile)
  {
    log << "Finished calculation" << std::endl;
    log.close();
  }
  return 0;
}