diff --git a/Modules/GraphAlgorithms/itkShortestPathCostFunctionLiveWire.txx b/Modules/GraphAlgorithms/itkShortestPathCostFunctionLiveWire.txx index 6563defd25..4f2fae2b42 100644 --- a/Modules/GraphAlgorithms/itkShortestPathCostFunctionLiveWire.txx +++ b/Modules/GraphAlgorithms/itkShortestPathCostFunctionLiveWire.txx @@ -1,442 +1,443 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __itkShortestPathCostFunctionLiveWire_txx #define __itkShortestPathCostFunctionLiveWire_txx #include "itkShortestPathCostFunctionLiveWire.h" #include #include #include #include #include #include #include #include namespace itk { // Constructor template ShortestPathCostFunctionLiveWire ::ShortestPathCostFunctionLiveWire() { m_UseRepulsivePoints = false; m_GradientMax = 0.0; m_Initialized = false; m_UseCostMap = false; m_MaxMapCosts = -1.0; } template void ShortestPathCostFunctionLiveWire ::AddRepulsivePoint( const IndexType& index ) { if (this->m_MaskImage.IsNotNull()) this->m_MaskImage->SetPixel(index, 255); m_UseRepulsivePoints = true; } template void ShortestPathCostFunctionLiveWire ::RemoveRepulsivePoint( const IndexType& index ) { if (this->m_MaskImage.IsNotNull()) this->m_MaskImage->SetPixel(index, 0); } template void ShortestPathCostFunctionLiveWire ::SetImage(const TInputImageType* _arg) { if (m_Image != _arg) { m_Image = _arg; // initialize mask image m_MaskImage = UnsignedCharImageType::New(); m_MaskImage->SetRegions(m_Image->GetLargestPossibleRegion()); m_MaskImage->SetOrigin( m_Image->GetOrigin() ); m_MaskImage->SetSpacing( m_Image->GetSpacing() ); m_MaskImage->SetDirection( m_Image->GetDirection() ); m_MaskImage->Allocate (); m_MaskImage->FillBuffer(0); this->Modified(); this->m_Initialized = false; } } template void ShortestPathCostFunctionLiveWire ::ClearRepulsivePoints() { m_UseRepulsivePoints = false; if (this->m_MaskImage.IsNotNull()) this->m_MaskImage->FillBuffer(0); } template double ShortestPathCostFunctionLiveWire ::GetCost(IndexType p1 ,IndexType p2) { // local component costs // weights double w1; double w2; double w3; double costs = 0.0; - // if we are on the mask, leave asap + // if we are on the mask, return asap if (m_UseRepulsivePoints) { - if (this->m_MaskImage->GetPixel(p2) != 0) - return 255; + if ( (this->m_MaskImage->GetPixel(p1) != 0) || + (this->m_MaskImage->GetPixel(p2) != 0) ) + return 255; } unsigned long xMAX = this->m_Image->GetLargestPossibleRegion().GetSize()[0]; unsigned long yMAX = this->m_Image->GetLargestPossibleRegion().GetSize()[1]; double gradientX, gradientY; gradientX = gradientY = 0.0; double gradientCost; double gradientMagnitude; // Gradient Magnitude costs gradientMagnitude = this->m_GradientMagnitudeImage->GetPixel(p2); gradientX = m_GradientImage->GetPixel(p2)[0]; gradientY = m_GradientImage->GetPixel(p2)[1]; if(m_UseCostMap && !m_CostMap.empty()) { std::map< int, int >::iterator end = m_CostMap.end(); std::map< int, int >::iterator last = --(m_CostMap.end()); //current position std::map< int, int >::iterator x; //std::map< int, int >::key_type keyOfX = static_cast::key_type>(gradientMagnitude * 1000); int keyOfX = static_cast(gradientMagnitude /* ShortestPathCostFunctionLiveWire::MAPSCALEFACTOR*/); x = m_CostMap.find( keyOfX ); std::map< int, int >::iterator left2; std::map< int, int >::iterator left1; std::map< int, int >::iterator right1; std::map< int, int >::iterator right2; if( x == end ) {//x can also be == end if the key is not in the map but between two other keys //search next key within map from x upwards right1 = m_CostMap.lower_bound( keyOfX ); } else { right1 = x; } if(right1 == end || right1 == last ) { right2 = end; } else//( right1 != (end-1) ) { std::map< int, int >::iterator temp = right1; right2 = ++right1;//rght1 + 1 right1 = temp; } if( right1 == m_CostMap.begin() ) { left1 = end; left2 = end; } else if( right1 == (++(m_CostMap.begin())) ) { std::map< int, int >::iterator temp = right1; left1 = --right1;//rght1 - 1 right1 = temp; left2 = end; } else { std::map< int, int >::iterator temp = right1; left1 = --right1;//rght1 - 1 left2 = --right1;//rght1 - 2 right1 = temp; } double partRight1, partRight2, partLeft1, partLeft2; partRight1 = partRight2 = partLeft1 = partLeft2 = 0.0; /* f(x) = v(bin) * e^ ( -1/2 * (|x-k(bin)| / sigma)^2 ) gaussian approximation where v(bin) is the value in the map k(bin) is the key */ if( left2 != end ) { partLeft2 = ShortestPathCostFunctionLiveWire::Gaussian(keyOfX, left2->first, left2->second); } if( left1 != end ) { partLeft1 = ShortestPathCostFunctionLiveWire::Gaussian(keyOfX, left1->first, left1->second); } if( right1 != end ) { partRight1 = ShortestPathCostFunctionLiveWire::Gaussian(keyOfX, right1->first, right1->second); } if( right2 != end ) { partRight2 = ShortestPathCostFunctionLiveWire::Gaussian(keyOfX, right2->first, right2->second); } if( m_MaxMapCosts > 0.0 ) { gradientCost = 1.0 - ( (partRight1 + partRight2 + partLeft1 + partLeft2) / m_MaxMapCosts ); } else {//use linear mapping gradientCost = 1.0 - (gradientMagnitude / m_GradientMax); } } else {//use linear mapping //value between 0 (good) and 1 (bad) gradientCost = 1.0 - (gradientMagnitude / m_GradientMax); } // Laplacian zero crossing costs // f(p) = 0; if I(p)=0 // or 1; if I(p)!=0 double laplacianCost; typename Superclass::PixelType laplaceImageValue; laplaceImageValue = m_EdgeImage->GetPixel(p2); if(laplaceImageValue < 0 || laplaceImageValue > 0) { laplacianCost = 1.0; } else { laplacianCost = 0.0; } // Gradient direction costs //vector q-p i.e. p2-p1 double vQP[2]; vQP[0] = p2[0] - p1[0]; vQP[1] = p2[1] - p1[1]; //------- //vector p-q i.e. p1-p2 double vPQ[2]; vPQ[0] = p1[0] - p2[0]; vPQ[1] = p1[1] - p2[1]; //------- // gradient vector at p1 double nGradientAtP1[2]; nGradientAtP1[0] = gradientX;//previously computed for gradient magnitude nGradientAtP1[1] = gradientY; //gradient direction unit vector of p1 nGradientAtP1[0] /= gradientMagnitude; nGradientAtP1[1] /= gradientMagnitude; //------- // gradient vector at p1 double nGradientAtP2[2]; nGradientAtP2[0] = m_GradientImage->GetPixel(p2)[0]; nGradientAtP2[1] = m_GradientImage->GetPixel(p2)[1]; nGradientAtP2[0] /= m_GradientMagnitudeImage->GetPixel(p2); nGradientAtP2[1] /= m_GradientMagnitudeImage->GetPixel(p2); double scalarProduct = (nGradientAtP1[0] * nGradientAtP2[0]) + (nGradientAtP1[1] * nGradientAtP2[1]); if( abs(scalarProduct) >= 1.0) { //this should probably not happen; make sure the input for acos is valid scalarProduct = 0.999999999; } double gradientDirectionCost = acos( scalarProduct ) / 3.14159265; if (this->m_UseCostMap) { w1 = 0.43; w2= 0.43; w3 = 0.14; }else{ w1 = 0.10; w2= 0.85; w3 = 0.05; } costs = w1 * laplacianCost + w2 * gradientCost + w3 * gradientDirectionCost; //scale by euclidian distance double costScale; if( p1[0] == p2[0] || p1[1] == p2[1]) { //horizontal or vertical neighbor costScale = 1.0; } else { //diagonal neighbor costScale = sqrt(2.0); } costs *= costScale; return costs; } template double ShortestPathCostFunctionLiveWire ::GetMinCost() { return minCosts; } template void ShortestPathCostFunctionLiveWire ::Initialize() { if(!m_Initialized) { typedef itk::CastImageFilter< TInputImageType, FloatImageType > CastFilterType; typename CastFilterType::Pointer castFilter = CastFilterType::New(); castFilter->SetInput(this->m_Image); // init gradient magnitude image typedef itk::GradientMagnitudeImageFilter< FloatImageType, FloatImageType> GradientMagnitudeFilterType; typename GradientMagnitudeFilterType::Pointer gradientFilter = GradientMagnitudeFilterType::New(); gradientFilter->SetInput(castFilter->GetOutput()); //gradientFilter->SetNumberOfThreads(4); //gradientFilter->GetOutput()->SetRequestedRegion(m_RequestedRegion); gradientFilter->Update(); this->m_GradientMagnitudeImage = gradientFilter->GetOutput(); typedef itk::StatisticsImageFilter StatisticsImageFilterType; typename StatisticsImageFilterType::Pointer statisticsImageFilter = StatisticsImageFilterType::New(); statisticsImageFilter->SetInput(this->m_GradientMagnitudeImage); statisticsImageFilter->Update(); m_GradientMax = statisticsImageFilter->GetMaximum(); typedef itk::GradientImageFilter< FloatImageType > GradientFilterType; typename GradientFilterType::Pointer filter = GradientFilterType::New(); //sigma is specified in millimeters //filter->SetSigma( 1.5 ); filter->SetInput(castFilter->GetOutput()); filter->Update(); m_GradientImage = filter->GetOutput(); // init zero crossings //typedef itk::ZeroCrossingImageFilter< TInputImageType, UnsignedCharImageType > ZeroCrossingImageFilterType; //ZeroCrossingImageFilterType::Pointer zeroCrossingImageFilter = ZeroCrossingImageFilterType::New(); //zeroCrossingImageFilter->SetInput(this->m_Image); //zeroCrossingImageFilter->SetBackgroundValue(1); //zeroCrossingImageFilter->SetForegroundValue(0); //zeroCrossingImageFilter->SetNumberOfThreads(4); //zeroCrossingImageFilter->Update(); //m_EdgeImage = zeroCrossingImageFilter->GetOutput(); //cast image to float to apply canny edge dection filter /*typedef itk::CastImageFilter< TInputImageType, FloatImageType > CastFilterType; CastFilterType::Pointer castFilter = CastFilterType::New(); castFilter->SetInput(this->m_Image);*/ //typedef itk::LaplacianImageFilter filterType; //filterType::Pointer laplacianFilter = filterType::New(); //laplacianFilter->SetInput( castFilter->GetOutput() ); // NOTE: input image type must be double or float //laplacianFilter->Update(); //m_EdgeImage = laplacianFilter->GetOutput(); //init canny edge detection typedef itk::CannyEdgeDetectionImageFilter CannyEdgeDetectionImageFilterType; typename CannyEdgeDetectionImageFilterType::Pointer cannyEdgeDetectionfilter = CannyEdgeDetectionImageFilterType::New(); cannyEdgeDetectionfilter->SetInput(castFilter->GetOutput()); cannyEdgeDetectionfilter->SetUpperThreshold(30); cannyEdgeDetectionfilter->SetLowerThreshold(15); cannyEdgeDetectionfilter->SetVariance(4); cannyEdgeDetectionfilter->SetMaximumError(.01f); cannyEdgeDetectionfilter->Update(); m_EdgeImage = cannyEdgeDetectionfilter->GetOutput(); // set minCosts minCosts = 0.0; // The lower, the more thouroughly! 0 = dijkstra. If estimate costs are lower than actual costs everything is fine. If estimation is higher than actual costs, you might not get the shortest but a different path. m_Initialized = true; } // check start/end point value startValue= this->m_Image->GetPixel(this->m_StartIndex); endValue= this->m_Image->GetPixel(this->m_EndIndex); } template double ShortestPathCostFunctionLiveWire::SigmoidFunction(double I, double max, double min, double alpha, double beta) { // Using the SIgmoid formula from ITK Software Guide 6.3.2 Non Linear Mappings double Exponent = -1 * ((I - beta) / alpha); double Factor = 1 / (1 + exp(Exponent)); double newI = (max - min) * Factor + min; return newI; } template double ShortestPathCostFunctionLiveWire::Gaussian(double x, double xOfGaussian, double yOfGaussian) { return yOfGaussian * exp( -0.5 * pow( (x - xOfGaussian), 2) ); } } // end namespace itk #endif // __itkShortestPathCostFunctionLiveWire_txx diff --git a/Modules/Segmentation/Algorithms/mitkImageLiveWireContourModelFilter.cpp b/Modules/Segmentation/Algorithms/mitkImageLiveWireContourModelFilter.cpp index 58b053ca98..a4f59edefd 100644 --- a/Modules/Segmentation/Algorithms/mitkImageLiveWireContourModelFilter.cpp +++ b/Modules/Segmentation/Algorithms/mitkImageLiveWireContourModelFilter.cpp @@ -1,444 +1,438 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkImageLiveWireContourModelFilter.h" #include #include #include mitk::ImageLiveWireContourModelFilter::ImageLiveWireContourModelFilter() { OutputType::Pointer output = dynamic_cast ( this->MakeOutput( 0 ).GetPointer() ); this->SetNumberOfRequiredInputs(1); this->SetNumberOfIndexedOutputs( 1 ); this->SetNthOutput(0, output.GetPointer()); m_CostFunction = CostFunctionType::New(); m_ShortestPathFilter = ShortestPathImageFilterType::New(); m_ShortestPathFilter->SetCostFunction(m_CostFunction); m_UseDynamicCostMap = false; m_ImageModified = false; m_TimeStep = 0; } mitk::ImageLiveWireContourModelFilter::~ImageLiveWireContourModelFilter() { - } - mitk::ImageLiveWireContourModelFilter::OutputType* mitk::ImageLiveWireContourModelFilter::GetOutput() { return Superclass::GetOutput(); } void mitk::ImageLiveWireContourModelFilter::SetInput ( const mitk::ImageLiveWireContourModelFilter::InputType* input ) { this->SetInput( 0, input ); } void mitk::ImageLiveWireContourModelFilter::SetInput ( unsigned int idx, const mitk::ImageLiveWireContourModelFilter::InputType* input ) { if ( idx + 1 > this->GetNumberOfInputs() ) { this->SetNumberOfRequiredInputs(idx + 1); } if ( input != static_cast ( this->ProcessObject::GetInput ( idx ) ) ) { this->ProcessObject::SetNthInput ( idx, const_cast ( input ) ); this->Modified(); this->m_ImageModified = true; m_ShortestPathFilter = ShortestPathImageFilterType::New(); m_ShortestPathFilter->SetCostFunction(m_CostFunction); } } - - const mitk::ImageLiveWireContourModelFilter::InputType* mitk::ImageLiveWireContourModelFilter::GetInput( void ) { if (this->GetNumberOfInputs() < 1) return NULL; return static_cast(this->ProcessObject::GetInput(0)); } - const mitk::ImageLiveWireContourModelFilter::InputType* mitk::ImageLiveWireContourModelFilter::GetInput( unsigned int idx ) { if (this->GetNumberOfInputs() < 1) return NULL; return static_cast(this->ProcessObject::GetInput(idx)); } - void mitk::ImageLiveWireContourModelFilter::GenerateData() { mitk::Image::ConstPointer input = dynamic_cast(this->GetInput()); if(!input) { MITK_ERROR << "No input available."; itkExceptionMacro("mitk::ImageToLiveWireContourFilter: No input available. Please set the input!"); return; } if( input->GetDimension() != 2 ) { MITK_ERROR << "Filter is only working on 2D images."; itkExceptionMacro("mitk::ImageToLiveWireContourFilter: Filter is only working on 2D images.. Please make sure that the input is 2D!"); return; } if( m_ImageModified ) { AccessFixedDimensionByItk(input, ItkPreProcessImage, 2); m_ImageModified = false; } input->GetGeometry()->WorldToIndex(m_StartPoint, m_StartPointInIndex); input->GetGeometry()->WorldToIndex(m_EndPoint, m_EndPointInIndex); //only start calculating if both indices are inside image geometry if( input->GetGeometry()->IsIndexInside(this->m_StartPointInIndex) && input->GetGeometry()->IsIndexInside(this->m_EndPointInIndex) ) { try { this->UpdateLiveWire(); } catch( itk::ExceptionObject & e ) { MITK_INFO << "Exception caught during live wiring calculation: " << e; m_ImageModified = true; return; } } } template void mitk::ImageLiveWireContourModelFilter::ItkPreProcessImage (itk::Image* inputImage) { typedef itk::Image< TPixel, VImageDimension > InputImageType; typedef itk::CastImageFilter< InputImageType, InternalImageType > CastFilterType; typename CastFilterType::Pointer castFilter = CastFilterType::New(); castFilter->SetInput(inputImage); castFilter->Update(); m_InternalImage = castFilter->GetOutput(); m_CostFunction->SetImage( m_InternalImage ); m_ShortestPathFilter->SetInput( m_InternalImage ); } void mitk::ImageLiveWireContourModelFilter::ClearRepulsivePoints() { m_CostFunction->ClearRepulsivePoints(); } void mitk::ImageLiveWireContourModelFilter::AddRepulsivePoint( const itk::Index<2>& idx ) { m_CostFunction->AddRepulsivePoint(idx); } void mitk::ImageLiveWireContourModelFilter::RemoveRepulsivePoint( const itk::Index<2>& idx ) { m_CostFunction->RemoveRepulsivePoint(idx); } void mitk::ImageLiveWireContourModelFilter::SetRepulsivePoints(const ShortestPathType& points) { m_CostFunction->ClearRepulsivePoints(); ShortestPathType::const_iterator iter = points.begin(); for (;iter != points.end(); iter++) { m_CostFunction->AddRepulsivePoint( (*iter) ); } } void mitk::ImageLiveWireContourModelFilter::UpdateLiveWire() { // compute the requested region for itk filters InternalImageType::IndexType startPoint, endPoint; startPoint[0] = m_StartPointInIndex[0]; startPoint[1] = m_StartPointInIndex[1]; endPoint[0] = m_EndPointInIndex[0]; endPoint[1] = m_EndPointInIndex[1]; // minimum value in each direction for startRegion InternalImageType::IndexType startRegion; startRegion[0] = startPoint[0] < endPoint[0] ? startPoint[0] : endPoint[0]; startRegion[1] = startPoint[1] < endPoint[1] ? startPoint[1] : endPoint[1]; // maximum value in each direction for size InternalImageType::SizeType size; size[0] = abs( startPoint[0] - endPoint[0] ) + 1; size[1] = abs( startPoint[1] - endPoint[1] ) + 1; CostFunctionType::RegionType region; region.SetSize( size ); region.SetIndex( startRegion ); //inputImage->SetRequestedRegion(region); // extracts features from image and calculates costs //m_CostFunction->SetImage(m_InternalImage); m_CostFunction->SetStartIndex(startPoint); m_CostFunction->SetEndIndex(endPoint); m_CostFunction->SetRequestedRegion(region); m_CostFunction->SetUseCostMap(m_UseDynamicCostMap); // calculate shortest path between start and end point m_ShortestPathFilter->SetFullNeighborsMode(true); //m_ShortestPathFilter->SetInput( m_CostFunction->SetImage(m_InternalImage) ); m_ShortestPathFilter->SetMakeOutputImage(false); //m_ShortestPathFilter->SetCalcAllDistances(true); m_ShortestPathFilter->SetStartIndex(startPoint); m_ShortestPathFilter->SetEndIndex(endPoint); m_ShortestPathFilter->Update(); // construct contour from path image //get the shortest path as vector ShortestPathType shortestPath = m_ShortestPathFilter->GetVectorPath(); //fill the output contour with control points from the path OutputType::Pointer output = dynamic_cast ( this->MakeOutput( 0 ).GetPointer() ); this->SetNthOutput(0, output.GetPointer()); // OutputType::Pointer output = dynamic_cast ( this->GetOutput() ); output->Expand(m_TimeStep+1); // output->Clear(); mitk::Image::ConstPointer input = dynamic_cast(this->GetInput()); ShortestPathType::const_iterator pathIterator = shortestPath.begin(); while(pathIterator != shortestPath.end()) { mitk::Point3D currentPoint; currentPoint[0] = static_cast( (*pathIterator)[0] ); currentPoint[1] = static_cast( (*pathIterator)[1] ); currentPoint[2] = 0.0; input->GetGeometry()->IndexToWorld(currentPoint, currentPoint); output->AddVertex(currentPoint, false, m_TimeStep); pathIterator++; } } bool mitk::ImageLiveWireContourModelFilter::CreateDynamicCostMap(mitk::ContourModel* path) { mitk::Image::ConstPointer input = dynamic_cast(this->GetInput()); if(!input) return false; try { AccessFixedDimensionByItk_1(input,CreateDynamicCostMapByITK, 2, path); } catch( itk::ExceptionObject & e ) { MITK_INFO << "Exception caught during dynamic cost map alculation: " << e; return false; } return true; } template void mitk::ImageLiveWireContourModelFilter::CreateDynamicCostMapByITK( itk::Image* inputImage, mitk::ContourModel* path ) { /*++++++++++ create dynamic cost transfer map ++++++++++*/ /* Compute the costs of the gradient magnitude dynamically. * using a map of the histogram of gradient magnitude image. * Use the histogram gradient map to interpolate the costs * with gaussing function including next two bins right and left * to current position x. With the histogram gradient costs are interpolated * with a gaussing function summation of next two bins right and left * to current position x. */ std::vector< itk::Index > shortestPath; mitk::Image::ConstPointer input = dynamic_cast(this->GetInput()); if(path == NULL) { OutputType::Pointer output = this->GetOutput(); mitk::ContourModel::VertexIterator it = output->IteratorBegin(); while( it != output->IteratorEnd() ) { itk::Index cur; mitk::Point3D c = (*it)->Coordinates; input->GetGeometry()->WorldToIndex(c, c); cur[0] = c[0]; cur[1] = c[1]; shortestPath.push_back( cur); it++; } } else { mitk::ContourModel::VertexIterator it = path->IteratorBegin(); while( it != path->IteratorEnd() ) { itk::Index cur; mitk::Point3D c = (*it)->Coordinates; input->GetGeometry()->WorldToIndex(c, c); cur[0] = c[0]; cur[1] = c[1]; shortestPath.push_back( cur); it++; } } // filter image gradient magnitude typedef itk::GradientMagnitudeImageFilter< itk::Image, itk::Image > GradientMagnitudeFilterType; typename GradientMagnitudeFilterType::Pointer gradientFilter = GradientMagnitudeFilterType::New(); gradientFilter->SetInput(inputImage); gradientFilter->Update(); typename itk::Image::Pointer gradientMagnImage = gradientFilter->GetOutput(); //get the path //iterator of path typename std::vector< itk::Index >::iterator pathIterator = shortestPath.begin(); std::map< int, int > histogram; //create histogram within path while(pathIterator != shortestPath.end()) { //count pixel values //use scale factor to avoid mapping gradients between 0.0 and 1.0 to same bin histogram[ static_cast( gradientMagnImage->GetPixel((*pathIterator)) * ImageLiveWireContourModelFilter::CostFunctionType::MAPSCALEFACTOR ) ] += 1; pathIterator++; } double max = 1.0; if( !histogram.empty() ) { std::map< int, int >::iterator itMAX; //get max of histogramm int currentMaxValue = 0; std::map< int, int >::iterator it = histogram.begin(); while( it != histogram.end()) { if((*it).second > currentMaxValue) { itMAX = it; currentMaxValue = (*it).second; } it++; } std::map< int, int >::key_type keyOfMax = itMAX->first; // compute the to max of gaussian summation std::map< int, int >::iterator end = histogram.end(); std::map< int, int >::iterator last = --(histogram.end()); std::map< int, int >::iterator left2; std::map< int, int >::iterator left1; std::map< int, int >::iterator right1; std::map< int, int >::iterator right2; right1 = itMAX; if(right1 == end || right1 == last ) { right2 = end; } else//( right1 <= last ) { std::map< int, int >::iterator temp = right1; right2 = ++right1;//rght1 + 1 right1 = temp; } if( right1 == histogram.begin() ) { left1 = end; left2 = end; } else if( right1 == (++(histogram.begin())) ) { std::map< int, int >::iterator temp = right1; left1 = --right1;//rght1 - 1 right1 = temp; left2 = end; } else { std::map< int, int >::iterator temp = right1; left1 = --right1;//rght1 - 1 left2 = --right1;//rght1 - 2 right1 = temp; } double partRight1, partRight2, partLeft1, partLeft2; partRight1 = partRight2 = partLeft1 = partLeft2 = 0.0; /* f(x) = v(bin) * e^ ( -1/2 * (|x-k(bin)| / sigma)^2 ) gaussian approximation where v(bin) is the value in the map k(bin) is the key */ if( left2 != end ) { partLeft2 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, left2->first, left2->second); } if( left1 != end ) { partLeft1 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, left1->first, left1->second); } if( right1 != end ) { partRight1 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, right1->first, right1->second); } if( right2 != end ) { partRight2 = ImageLiveWireContourModelFilter::CostFunctionType::Gaussian(keyOfMax, right2->first, right2->second); } max = (partRight1 + partRight2 + partLeft1 + partLeft2); } this->m_CostFunction->SetDynamicCostMap(histogram); this->m_CostFunction->SetCostMapMaximum(max); } diff --git a/Modules/Segmentation/DataManagement/mitkContourElement.cpp b/Modules/Segmentation/DataManagement/mitkContourElement.cpp index f70b092c84..e98d3cbaea 100644 --- a/Modules/Segmentation/DataManagement/mitkContourElement.cpp +++ b/Modules/Segmentation/DataManagement/mitkContourElement.cpp @@ -1,717 +1,721 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include mitk::ContourElement::ContourElement() { this->m_Vertices = new VertexListType(); this->m_IsClosed = false; } mitk::ContourElement::ContourElement(const mitk::ContourElement &other) : m_Vertices(other.m_Vertices), m_IsClosed(other.m_IsClosed) { } mitk::ContourElement::~ContourElement() { delete this->m_Vertices; } void mitk::ContourElement::AddVertex(mitk::Point3D &vertex, bool isControlPoint) { this->m_Vertices->push_back(new VertexType(vertex, isControlPoint)); } void mitk::ContourElement::AddVertex(VertexType &vertex) { this->m_Vertices->push_back(&vertex); } void mitk::ContourElement::AddVertexAtFront(mitk::Point3D &vertex, bool isControlPoint) { this->m_Vertices->push_front(new VertexType(vertex, isControlPoint)); } void mitk::ContourElement::AddVertexAtFront(VertexType &vertex) { this->m_Vertices->push_front(&vertex); } void mitk::ContourElement::InsertVertexAtIndex(mitk::Point3D &vertex, bool isControlPoint, int index) { if(index > 0 && this->GetSize() > index) { VertexIterator _where = this->m_Vertices->begin(); _where += index; this->m_Vertices->insert(_where, new VertexType(vertex, isControlPoint)); } } mitk::ContourElement::VertexType* mitk::ContourElement::GetVertexAt(int index) { return this->m_Vertices->at(index); } +bool mitk::ContourElement::IsEmpty() +{ + return this->m_Vertices->empty(); +} mitk::ContourElement::VertexType* mitk::ContourElement::GetVertexAt(const mitk::Point3D &point, float eps) { /* current version iterates over the whole deque - should some kind of an octree with spatial query*/ if(eps > 0) { //currently no method with better performance is available return BruteForceGetVertexAt(point, eps); }//if eps < 0 return NULL; } mitk::ContourElement::VertexType* mitk::ContourElement::BruteForceGetVertexAt(const mitk::Point3D &point, float eps) { if(eps > 0) { std::deque< std::pair > nearestlist; ConstVertexIterator it = this->m_Vertices->begin(); ConstVertexIterator end = this->m_Vertices->end(); while(it != end) { mitk::Point3D currentPoint = (*it)->Coordinates; double distance = currentPoint.EuclideanDistanceTo(point); if(distance < eps) { //if list is emtpy, add point to list if(nearestlist.size() < 1) { nearestlist.push_front(std::pair( (*it)->Coordinates.EuclideanDistanceTo(point), (*it) )); } //found an approximate point - check if current is closer then first in nearestlist else if( distance < nearestlist.front().first ) { //found even closer vertex nearestlist.push_front(std::pair( (*it)->Coordinates.EuclideanDistanceTo(point), (*it) )); } }//if distance > eps it++; }//while if(nearestlist.size() > 0) { /*++++++++++++++++++++ return the nearest active point if one was found++++++++++++++++++*/ std::deque< std::pair >::iterator it = nearestlist.begin(); std::deque< std::pair >::iterator end = nearestlist.end(); while(it != end) { if( (*it).second->IsControlPoint ) { return (*it).second; } it++; } /*---------------------------------------------------------------------------------------*/ //return closest point return nearestlist.front().second; } } return NULL; } mitk::ContourElement::VertexType* mitk::ContourElement::OptimizedGetVertexAt(const mitk::Point3D &point, float eps) { if( (eps > 0) && (this->m_Vertices->size()>0) ) { int k = 1; int dim = 3; int nPoints = this->m_Vertices->size(); ANNpointArray pointsArray; ANNpoint queryPoint; ANNidxArray indexArray; ANNdistArray distanceArray; ANNkd_tree* kdTree; queryPoint = annAllocPt(dim); pointsArray = annAllocPts(nPoints, dim); indexArray = new ANNidx[k]; distanceArray = new ANNdist[k]; int i = 0; //fill points array with our control points for(VertexIterator it = this->m_Vertices->begin(); it != this->m_Vertices->end(); it++, i++) { mitk::Point3D cur = (*it)->Coordinates; pointsArray[i][0]= cur[0]; pointsArray[i][1]= cur[1]; pointsArray[i][2]= cur[2]; } //create the kd tree kdTree = new ANNkd_tree(pointsArray,nPoints, dim); //fill mitk::Point3D into ANN query point queryPoint[0] = point[0]; queryPoint[1] = point[1]; queryPoint[2] = point[2]; //k nearest neighbour search kdTree->annkSearch(queryPoint, k, indexArray, distanceArray, eps); VertexType* ret = NULL; try { ret = this->m_Vertices->at(indexArray[0]); } catch(std::out_of_range ex) { //ret stays NULL return ret; } //clean up ANN delete [] indexArray; delete [] distanceArray; delete kdTree; annClose(); return ret; } return NULL; } mitk::ContourElement::VertexListType* mitk::ContourElement::GetVertexList() { return this->m_Vertices; } bool mitk::ContourElement::IsClosed() { return this->m_IsClosed; } bool mitk::ContourElement::IsNearContour(const mitk::Point3D &point, float eps) { ConstVertexIterator it1 = this->m_Vertices->begin(); ConstVertexIterator it2 = this->m_Vertices->begin(); it2 ++; // it2 runs one position ahead ConstVertexIterator end = this->m_Vertices->end(); int counter = 0; for (; it1 != end; it1++, it2++, counter++) { if (it2 == end) it2 = this->m_Vertices->begin(); mitk::Point3D v1 = (*it1)->Coordinates; mitk::Point3D v2 = (*it2)->Coordinates; const float l2 = v1.SquaredEuclideanDistanceTo(v2); mitk::Vector3D p_v1 = point - v1; mitk::Vector3D v2_v1 = v2 - v1; double tc = (p_v1 * v2_v1) / l2; // take into account we have line segments and not (infinite) lines if (tc < 0.0) tc = 0.0; if (tc > 1.0) tc = 1.0; mitk::Point3D crossPoint = v1 + v2_v1 * tc; double distance = point.SquaredEuclideanDistanceTo(crossPoint); if (distance < eps) { return true; } } return false; } void mitk::ContourElement::Close() { this->m_IsClosed = true; } void mitk::ContourElement::Open() { this->m_IsClosed = false; } void mitk::ContourElement::SetIsClosed( bool isClosed) { isClosed ? this->Close() : this->Open(); } mitk::ContourElement::VertexListType* mitk::ContourElement::GetControlVertices() { VertexListType* newVertices = new VertexListType(); VertexIterator it = this->m_Vertices->begin(); VertexIterator end = this->m_Vertices->end(); while(it != end) { if((*it)->IsControlPoint) { newVertices->push_back((*it)); } it++; } return newVertices; } void mitk::ContourElement::Concatenate(mitk::ContourElement* other) { if( other->GetSize() > 0) { ConstVertexIterator it = other->m_Vertices->begin(); ConstVertexIterator end = other->m_Vertices->end(); //add all vertices of other after last vertex while(it != end) { this->m_Vertices->push_back(*it); it++; } } } std::pair mitk::ContourElement::FindFirstIntersection(mitk::ContourElement* other) { VertexIterator thisIt = this->m_Vertices->begin(); VertexIterator thisEnd = this->m_Vertices->end(); VertexIterator otherEnd = other->m_Vertices->end(); std::pair match(thisEnd,otherEnd); while (thisIt != thisEnd) { VertexIterator otherIt = other->m_Vertices->begin(); while (otherIt != otherEnd) { if ( (*thisIt)->Coordinates == (*otherIt)->Coordinates ) { match.first = thisIt; match.second = otherIt; return match; } otherIt++; } thisIt++; } return match; } void mitk::ContourElement::RemoveIntersections(mitk::ContourElement* other) { if( other->GetSize() > 0) { // VertexIterator _where = this->FindFirstIntersection(other); std::pair match = this->FindFirstIntersection(other); this->m_Vertices->erase(match.first, this->m_Vertices->end()); other->m_Vertices->erase(other->m_Vertices->begin(), match.second ); } } bool mitk::ContourElement::RemoveVertex(mitk::ContourElement::VertexType* vertex) { VertexIterator it = this->m_Vertices->begin(); VertexIterator end = this->m_Vertices->end(); //search for vertex and remove it if exists while(it != end) { if((*it) == vertex) { this->m_Vertices->erase(it); return true; } it++; } return false; } bool mitk::ContourElement::RemoveVertexAt(int index) { if( index >= 0 && index < this->m_Vertices->size() ) { this->m_Vertices->erase(this->m_Vertices->begin()+index); return true; } else { return false; } } bool mitk::ContourElement::RemoveVertexAt(mitk::Point3D &point, float eps) { /* current version iterates over the whole deque - should be some kind of an octree with spatial query*/ if(eps > 0){ VertexIterator it = this->m_Vertices->begin(); VertexIterator end = this->m_Vertices->end(); while(it != end) { mitk::Point3D currentPoint = (*it)->Coordinates; if(currentPoint.EuclideanDistanceTo(point) < eps) { //approximate point found //now erase it this->m_Vertices->erase(it); return true; } it++; } } return false; } void mitk::ContourElement::Clear() { this->m_Vertices->clear(); } //---------------------------------------------------------------------- void mitk::ContourElement::Interpolate() { VertexListType* newVertices = new VertexListType(); int nverts = this->m_Vertices->size(); for (int i=0; (i+1)DoBezierInterpolation(i, i+1, newVertices); } if ( this->IsClosed() ) { this->DoBezierInterpolation(nverts-1, 0, newVertices); } delete this->m_Vertices; this->m_Vertices = newVertices; } //---------------------------------------------------------------------- void mitk::ContourElement::RedistributeControlVertices(const VertexType* selected, int period) { int counter = 0; VertexIterator _where = this->m_Vertices->begin(); if (selected != NULL) { while (_where != this->m_Vertices->end()) { if ((*_where) == selected) { break; } _where++; } } VertexIterator _iter = _where; while (_iter != this->m_Vertices->end()) { div_t divresult; divresult = div (counter,period); (*_iter)->IsControlPoint = (divresult.rem == 0); counter++; _iter++; } _iter = _where; counter = 0; while (_iter != this->m_Vertices->begin()) { div_t divresult; divresult = div (counter,period); (*_iter)->IsControlPoint = (divresult.rem == 0); counter++; _iter--; } } //---------------------------------------------------------------------- void mitk::ContourElement::DoBezierInterpolation( int idx1, int idx2, VertexListType* vertices ) { mitk::Point3D mp1; mp1 = this->m_Vertices->at(idx1)->Coordinates; mitk::Point3D mp2; mp2 = this->m_Vertices->at(idx2)->Coordinates; // this->RemoveIntermediateVerticesAt(idx1); // this->AddIntermediateVertex(mp1, idx1); vertices->push_back(new VertexType(mp1, this->m_Vertices->at(idx1)->IsControlPoint)); int maxRecursion = 0; int tmp = 3; const int MaximumCurveLineSegments = 100; const double MaximumCurveError = 0.005; while ( 2*tmp < MaximumCurveLineSegments ) { tmp *= 2; maxRecursion++; } // There are four control points with 3 components each, plus one // value for the recursion depth of this point double *controlPointsStack = new double[(3*4+1)*(maxRecursion+1)]; int stackCount = 0; double slope1[3]; double slope2[3]; this->GetNthNodeSlope( idx1, slope1 ); this->GetNthNodeSlope( idx2, slope2 ); controlPointsStack[0] = 0; double *p1 = controlPointsStack+1; double *p2 = controlPointsStack+4; double *p3 = controlPointsStack+7; double *p4 = controlPointsStack+10; const VertexType* vertex1 = this->m_Vertices->at(idx1); p1[0] = vertex1->Coordinates[0]; p1[1] = vertex1->Coordinates[1]; p1[2] = vertex1->Coordinates[2]; const VertexType* vertex2 = this->m_Vertices->at(idx2); p4[0] = vertex2->Coordinates[0]; p4[1] = vertex2->Coordinates[1]; p4[2] = vertex2->Coordinates[2]; double distance = sqrt( vtkMath::Distance2BetweenPoints( p1, p4 ) ); p2[0] = p1[0] + .333*distance*slope1[0]; p2[1] = p1[1] + .333*distance*slope1[1]; p2[2] = p1[2] + .333*distance*slope1[2]; p3[0] = p4[0] - .333*distance*slope2[0]; p3[1] = p4[1] - .333*distance*slope2[1]; p3[2] = p4[2] - .333*distance*slope2[2]; stackCount++; while ( stackCount ) { //process last point on stack int recursionLevel = static_cast(controlPointsStack[13*(stackCount-1)]); p1 = controlPointsStack + 13*(stackCount-1)+1; p2 = controlPointsStack + 13*(stackCount-1)+4; p3 = controlPointsStack + 13*(stackCount-1)+7; p4 = controlPointsStack + 13*(stackCount-1)+10; double totalDist = 0; totalDist += sqrt(vtkMath::Distance2BetweenPoints(p1,p2)); totalDist += sqrt(vtkMath::Distance2BetweenPoints(p2,p3)); totalDist += sqrt(vtkMath::Distance2BetweenPoints(p3,p4)); distance = sqrt(vtkMath::Distance2BetweenPoints(p1,p4)); if ( recursionLevel >= maxRecursion || distance == 0 || (totalDist - distance)/distance < MaximumCurveError ) { mitk::Point3D mp2; mp2[0] = p2[0]; mp2[1] = p2[1]; mp2[2] = p2[2]; //this->InsertVertexAtIndex(mp2, false, idx1); vertices->push_back(new VertexType(mp2, false)); mitk::Point3D mp3; mp3[0] = p3[0]; mp3[1] = p3[1]; mp3[2] = p3[2]; //this->InsertVertexAtIndex(mp3, false, idx1); vertices->push_back(new VertexType(mp3, false)); if ( stackCount > 1 ) { mitk::Point3D mp4; mp4[0] = p4[0]; mp4[1] = p4[1]; mp4[2] = p4[2]; //this->InsertVertexAtIndex(mp4, false, idx1); vertices->push_back(new VertexType(mp4, false)); } stackCount--; } else { double p12[3], p23[3], p34[3], p123[3], p234[3], p1234[3]; this->ComputeMidpoint( p1, p2, p12 ); this->ComputeMidpoint( p2, p3, p23 ); this->ComputeMidpoint( p3, p4, p34 ); this->ComputeMidpoint( p12, p23, p123 ); this->ComputeMidpoint( p23, p34, p234 ); this->ComputeMidpoint( p123, p234, p1234 ); // add these two points to the stack controlPointsStack[13*(stackCount-1)] = recursionLevel+1; controlPointsStack[13*(stackCount)] = recursionLevel+1; double *newp1 = controlPointsStack + 13*(stackCount)+1; double *newp2 = controlPointsStack + 13*(stackCount)+4; double *newp3 = controlPointsStack + 13*(stackCount)+7; double *newp4 = controlPointsStack + 13*(stackCount)+10; newp1[0] = p1[0]; newp1[1] = p1[1]; newp1[2] = p1[2]; newp2[0] = p12[0]; newp2[1] = p12[1]; newp2[2] = p12[2]; newp3[0] = p123[0]; newp3[1] = p123[1]; newp3[2] = p123[2]; newp4[0] = p1234[0]; newp4[1] = p1234[1]; newp4[2] = p1234[2]; p1[0] = p1234[0]; p1[1] = p1234[1]; p1[2] = p1234[2]; p2[0] = p234[0]; p2[1] = p234[1]; p2[2] = p234[2]; p3[0] = p34[0]; p3[1] = p34[1]; p3[2] = p34[2]; stackCount++; } } delete [] controlPointsStack; } //---------------------------------------------------------------------- bool mitk::ContourElement::GetNthNodeSlope( int index, double slope[3]) { if ( index < 0 || static_cast(index) >= this->m_Vertices->size() ) { return false; } int idx1, idx2; if ( index == 0 && !this->IsClosed() ) { idx1 = 0; idx2 = 1; } else if ( index == this->m_Vertices->size()-1 && !this->IsClosed() ) { idx1 = this->m_Vertices->size()-2; idx2 = idx1+1; } else { idx1 = index - 1; idx2 = index + 1; if ( idx1 < 0 ) { idx1 += this->m_Vertices->size(); } if ( idx2 >= this->m_Vertices->size() ) { idx2 -= this->m_Vertices->size(); } } slope[0] = this->m_Vertices->at(idx2)->Coordinates[0] - this->m_Vertices->at(idx1)->Coordinates[0]; slope[1] = this->m_Vertices->at(idx2)->Coordinates[1] - this->m_Vertices->at(idx1)->Coordinates[1]; slope[2] = this->m_Vertices->at(idx2)->Coordinates[2] - this->m_Vertices->at(idx1)->Coordinates[2]; vtkMath::Normalize( slope ); return true; } diff --git a/Modules/Segmentation/DataManagement/mitkContourElement.h b/Modules/Segmentation/DataManagement/mitkContourElement.h index 2f4cafb578..21df9bdb0b 100644 --- a/Modules/Segmentation/DataManagement/mitkContourElement.h +++ b/Modules/Segmentation/DataManagement/mitkContourElement.h @@ -1,277 +1,281 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _mitkContourElement_H_ #define _mitkContourElement_H_ #include "mitkCommon.h" #include "SegmentationExports.h" #include #include #include namespace mitk { /** \brief Represents a contour in 3D space. A ContourElement is consisting of linked vertices implicitely defining the contour. They are stored in a double ended queue making it possible to add vertices at front and end of the contour and to iterate in both directions. To mark a vertex as a special one it can be set as a control point. \Note It is highly not recommend to use this class directly as no secure mechanism is used here. Use mitk::ContourModel instead providing some additional features. */ class Segmentation_EXPORT ContourElement : public itk::LightObject { public: mitkClassMacro(ContourElement, itk::LightObject); itkNewMacro(Self); mitkCloneMacro(Self); // Data container representing vertices /** \brief Represents a single vertex of contour. */ struct ContourModelVertex { ContourModelVertex(mitk::Point3D &point, bool active=false) : Coordinates(point), IsControlPoint(active) { }; /** \brief Treat point special. */ bool IsControlPoint; /** \brief Coordinates in 3D space. */ mitk::Point3D Coordinates; }; // END Data container representing vertices typedef ContourModelVertex VertexType; typedef std::deque VertexListType; typedef VertexListType::iterator VertexIterator; typedef VertexListType::const_iterator ConstVertexIterator; // start of inline methods /** \brief Return a const iterator a the front. */ virtual ConstVertexIterator ConstIteratorBegin() { return this->m_Vertices->begin(); } /** \brief Return a const iterator a the end. */ virtual ConstVertexIterator ConstIteratorEnd() { return this->m_Vertices->end(); } /** \brief Return an iterator a the front. */ virtual VertexIterator IteratorBegin() { return this->m_Vertices->begin(); } /** \brief Return an iterator a the end. */ virtual VertexIterator IteratorEnd() { return this->m_Vertices->end(); } /** \brief Returns the number of contained vertices. */ virtual int GetSize() { return this->m_Vertices->size(); } // end of inline methods /** \brief Add a vertex at the end of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a special control point. */ virtual void AddVertex(mitk::Point3D &point, bool isControlPoint); /** \brief Add a vertex at the end of the contour \param vertex - a contour element vertex. */ virtual void AddVertex(VertexType &vertex); /** \brief Add a vertex at the front of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a control point. */ virtual void AddVertexAtFront(mitk::Point3D &point, bool isControlPoint); /** \brief Add a vertex at the front of the contour \param vertex - a contour element vertex. */ virtual void AddVertexAtFront(VertexType &vertex); /** \brief Add a vertex at a given index of the contour \param point - coordinates in 3D space. \param isControlPoint - is the vertex a special control point. \param index - the index to be inserted at. */ virtual void InsertVertexAtIndex(mitk::Point3D &point, bool isControlPoint, int index); /** \brief Returns the vertex a given index \param index */ virtual VertexType* GetVertexAt(int index); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ virtual VertexType* GetVertexAt(const mitk::Point3D &point, float eps); /** \brief Returns the container of the vertices. */ VertexListType* GetVertexList(); + /** \brief Returns whether the contour element is empty. + */ + bool IsEmpty(); + /** \brief Returns if the conour is closed or not. */ virtual bool IsClosed(); /** \brief Returns whether a given point is near a contour, according to eps. \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ virtual bool IsNearContour(const mitk::Point3D &point, float eps); /** \brief Close the contour. Connect first with last element. */ virtual void Close(); /** \brief Open the contour. Disconnect first and last element. */ virtual void Open(); /** \brief Set the contours IsClosed property. \param isClosed - true = closed; false = open; */ virtual void SetIsClosed(bool isClosed); /** \brief Concatenate the contuor with a another contour. All vertices of the other contour will be add after last vertex. */ void Concatenate(mitk::ContourElement* other); /** \brief Removes intersected vertices between two contour elements \param other - a given contour element. */ void RemoveIntersections(mitk::ContourElement* other); /** \brief Remove the given vertex from the container if exists. \param vertex - the vertex to be removed. */ virtual bool RemoveVertex(VertexType* vertex); /** \brief Remove a vertex at given index within the container if exists. \param index - the index to be removed at. */ virtual bool RemoveVertexAt(int index); /** \brief Remove the approximate nearest vertex at given position in 3D space if one exists. \param point - query point in 3D space. \param eps - error bound for search algorithm. */ virtual bool RemoveVertexAt(mitk::Point3D &point, float eps); /** \brief Clear the storage container. */ virtual void Clear(); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ VertexType* BruteForceGetVertexAt(const mitk::Point3D &point, float eps); /** \brief Returns the approximate nearest vertex a given posoition in 3D space \param point - query position in 3D space. \param eps - the error bound for search algorithm. */ VertexType* OptimizedGetVertexAt(const mitk::Point3D &point, float eps); /** \brief Generate and interpolated version of the contour element based on the active interpolation method */ void Interpolate(); VertexListType* GetControlVertices(); /** \brief Uniformly redistribute control points with a given period (in number of vertices) \param period - number of vertices between control points. */ void RedistributeControlVertices(const VertexType* selected, int period); protected: ContourElement(); ContourElement(const mitk::ContourElement &other); virtual ~ContourElement(); /** \brief Finds the 4-th order bezier curve between given indexes. Adapted from vtkBezierContourLineInterpolator \param idx1 - first index \param idx2 - second index */ void DoBezierInterpolation( int idx1, int idx2, VertexListType* vertices ); /** \brief Returns a pair with two iterators pointing to the vertices where the contour element intersects (i.e. has the same coordinates) with another given contour element \param other - a given contour element. */ std::pair FindFirstIntersection(mitk::ContourElement* other); /** \brief Calculates the slope at a given index \param index - the index to get the slope at. \param slope - splope at given index. */ bool GetNthNodeSlope( int index, double slope[3]); void ComputeMidpoint( double p1[3], double p2[3], double mid[3] ) { mid[0] = (p1[0] + p2[0])/2; mid[1] = (p1[1] + p2[1])/2; mid[2] = (p1[2] + p2[2])/2; } VertexListType* m_Vertices; //double ended queue with vertices bool m_IsClosed; }; } // namespace mitk #endif // _mitkContourElement_H_ diff --git a/Modules/Segmentation/DataManagement/mitkContourModel.cpp b/Modules/Segmentation/DataManagement/mitkContourModel.cpp index 6a4562af7b..6382c9b212 100644 --- a/Modules/Segmentation/DataManagement/mitkContourModel.cpp +++ b/Modules/Segmentation/DataManagement/mitkContourModel.cpp @@ -1,612 +1,621 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include mitk::ContourModel::ContourModel() { //set to initial state this->InitializeEmpty(); } mitk::ContourModel::ContourModel(const mitk::ContourModel &other) : m_ContourSeries(other.m_ContourSeries), m_lineInterpolation(other.m_lineInterpolation) { m_SelectedVertex = NULL; } mitk::ContourModel::~ContourModel() { m_SelectedVertex = NULL; this->m_ContourSeries.clear();//TODO check destruction } void mitk::ContourModel::AddVertex(mitk::Point3D &vertex, int timestep) { if(!this->IsEmptyTimeStep(timestep) ) { this->AddVertex(vertex, false, timestep); } } void mitk::ContourModel::AddVertex(mitk::Point3D &vertex, bool isControlPoint, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { this->m_ContourSeries[timestep]->AddVertex(vertex, isControlPoint); this->InvokeEvent( ContourModelSizeChangeEvent() ); this->Modified(); } } void mitk::ContourModel::AddVertex(VertexType &vertex, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { this->m_ContourSeries[timestep]->AddVertex(vertex); this->InvokeEvent( ContourModelSizeChangeEvent() ); this->Modified(); } } void mitk::ContourModel::AddVertexAtFront(mitk::Point3D &vertex, int timestep) { if(!this->IsEmptyTimeStep(timestep) ) { this->AddVertexAtFront(vertex, false, timestep); } } void mitk::ContourModel::AddVertexAtFront(mitk::Point3D &vertex, bool isControlPoint, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { this->m_ContourSeries[timestep]->AddVertexAtFront(vertex, isControlPoint); this->InvokeEvent( ContourModelSizeChangeEvent() ); this->Modified(); } } void mitk::ContourModel::AddVertexAtFront(VertexType &vertex, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { this->m_ContourSeries[timestep]->AddVertexAtFront(vertex); this->InvokeEvent( ContourModelSizeChangeEvent() ); this->Modified(); } } void mitk::ContourModel::InsertVertexAtIndex(mitk::Point3D &vertex, int index, bool isControlPoint, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { if(index > 0 && this->m_ContourSeries[timestep]->GetSize() > index) { this->m_ContourSeries[timestep]->InsertVertexAtIndex(vertex, isControlPoint, index); this->InvokeEvent( ContourModelSizeChangeEvent() ); this->Modified(); } } } +bool mitk::ContourModel::IsEmpty( int timestep) +{ + if(!this->IsEmptyTimeStep(timestep)) + { + return this->m_ContourSeries[timestep]->IsEmpty(); + } + return true; +} + int mitk::ContourModel::GetNumberOfVertices( int timestep) { if(!this->IsEmptyTimeStep(timestep)) { return this->m_ContourSeries[timestep]->GetSize(); } return -1; } const mitk::ContourModel::VertexType* mitk::ContourModel::GetVertexAt(int index, int timestep) const { if(!this->IsEmptyTimeStep(timestep)) { return this->m_ContourSeries[timestep]->GetVertexAt(index); } return NULL; } void mitk::ContourModel::Close( int timestep) { if(!this->IsEmptyTimeStep(timestep)) { this->m_ContourSeries[timestep]->Close(); this->InvokeEvent( ContourModelClosedEvent() ); this->Modified(); } } void mitk::ContourModel::Open( int timestep) { if(!this->IsEmptyTimeStep(timestep)) { this->m_ContourSeries[timestep]->Open(); this->InvokeEvent( ContourModelClosedEvent() ); this->Modified(); } } void mitk::ContourModel::SetIsClosed(bool isClosed, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { this->m_ContourSeries[timestep]->SetIsClosed(isClosed); this->InvokeEvent( ContourModelClosedEvent() ); this->Modified(); } } bool mitk::ContourModel::IsEmptyTimeStep( int t) const { return (t < 0) || (this->m_ContourSeries.size() <= t); } bool mitk::ContourModel::IsNearContour(mitk::Point3D &point, float eps, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { return this->m_ContourSeries[timestep]->IsNearContour(point, eps); } return false; } void mitk::ContourModel::Concatenate(mitk::ContourModel* other, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { if( !this->m_ContourSeries[timestep]->IsClosed() ) { this->m_ContourSeries[timestep]->Concatenate(other->m_ContourSeries[timestep]); this->InvokeEvent( ContourModelSizeChangeEvent() ); this->Modified(); } } } void mitk::ContourModel::RemoveIntersections(mitk::ContourModel* other, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { if( !this->m_ContourSeries[timestep]->IsClosed() ) { this->m_ContourSeries[timestep]->RemoveIntersections(other->m_ContourSeries[timestep]); this->InvokeEvent( ContourModelSizeChangeEvent() ); this->Modified(); } } } mitk::ContourModel::VertexIterator mitk::ContourModel::IteratorBegin( int timestep) { if(!this->IsEmptyTimeStep(timestep)) { return this->m_ContourSeries[timestep]->IteratorBegin(); } else { mitkThrow() << "No iterator at invalid timestep " << timestep << ". There are only " << this->GetTimeSteps() << " timesteps available."; } } mitk::ContourModel::VertexIterator mitk::ContourModel::IteratorEnd( int timestep) { if(!this->IsEmptyTimeStep(timestep)) { return this->m_ContourSeries[timestep]->IteratorEnd(); } else { mitkThrow() << "No iterator at invalid timestep " << timestep << ". There are only " << this->GetTimeSteps() << " timesteps available."; } } bool mitk::ContourModel::IsClosed( int timestep) { if(!this->IsEmptyTimeStep(timestep)) { return this->m_ContourSeries[timestep]->IsClosed(); } return false; } bool mitk::ContourModel::SelectVertexAt(mitk::Point3D &point, float eps, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { this->m_SelectedVertex = this->m_ContourSeries[timestep]->GetVertexAt(point, eps); } return this->m_SelectedVertex != NULL; } bool mitk::ContourModel::SelectVertexAt(int index, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { return (this->m_SelectedVertex = this->m_ContourSeries[timestep]->GetVertexAt(index)); } return false; } bool mitk::ContourModel::SetControlVertexAt(mitk::Point3D &point, float eps, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { VertexType* vertex = this->m_ContourSeries[timestep]->GetVertexAt(point, eps); if (vertex != NULL) { vertex->IsControlPoint = true; return true; } } return false; } bool mitk::ContourModel::SetControlVertexAt(int index, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { VertexType* vertex = this->m_ContourSeries[timestep]->GetVertexAt(index); if (vertex != NULL) { vertex->IsControlPoint = true; return true; } } return false; } bool mitk::ContourModel::RemoveVertex(VertexType* vertex, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { if(this->m_ContourSeries[timestep]->RemoveVertex(vertex)) { this->Modified(); this->InvokeEvent( ContourModelSizeChangeEvent() ); return true; } } return false; } bool mitk::ContourModel::RemoveVertexAt(int index, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { if(this->m_ContourSeries[timestep]->RemoveVertexAt(index)) { this->Modified(); this->InvokeEvent( ContourModelSizeChangeEvent() ); return true; } } return false; } bool mitk::ContourModel::RemoveVertexAt(mitk::Point3D &point, float eps, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { if(this->m_ContourSeries[timestep]->RemoveVertexAt(point, eps)) { this->Modified(); this->InvokeEvent( ContourModelSizeChangeEvent() ); return true; } } return false; } void mitk::ContourModel::ShiftSelectedVertex(mitk::Vector3D &translate) { if(this->m_SelectedVertex) { this->ShiftVertex(this->m_SelectedVertex,translate); this->Modified(); } } void mitk::ContourModel::ShiftContour(mitk::Vector3D &translate, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { VertexListType* vList = this->m_ContourSeries[timestep]->GetVertexList(); VertexIterator it = vList->begin(); VertexIterator end = vList->end(); //shift all vertices while(it != end) { this->ShiftVertex((*it),translate); it++; } this->Modified(); this->InvokeEvent( ContourModelShiftEvent() ); } } void mitk::ContourModel::ShiftVertex(VertexType* vertex, mitk::Vector3D &vector) { vertex->Coordinates[0] += vector[0]; vertex->Coordinates[1] += vector[1]; vertex->Coordinates[2] += vector[2]; } void mitk::ContourModel::Clear(int timestep) { if(!this->IsEmptyTimeStep(timestep)) { //clear data at timestep this->m_ContourSeries[timestep]->Clear(); this->InitializeEmpty(); this->Modified(); } } void mitk::ContourModel::Expand( int timeSteps ) { int oldSize = this->m_ContourSeries.size(); if( timeSteps > 0 && timeSteps > oldSize ) { Superclass::Expand(timeSteps); //insert contours for each new timestep for( int i = oldSize; i < timeSteps; i++) { m_ContourSeries.push_back(mitk::ContourElement::New()); } this->InvokeEvent( ContourModelExpandTimeBoundsEvent() ); } } void mitk::ContourModel::SetRequestedRegionToLargestPossibleRegion () { //no support for regions } bool mitk::ContourModel::RequestedRegionIsOutsideOfTheBufferedRegion () { //no support for regions return false; } bool mitk::ContourModel::VerifyRequestedRegion () { //no support for regions return true; } const mitk::Geometry3D * mitk::ContourModel::GetUpdatedGeometry (int t) { return Superclass::GetUpdatedGeometry(t); } mitk::Geometry3D* mitk::ContourModel::GetGeometry (int t)const { return Superclass::GetGeometry(t); } void mitk::ContourModel::SetRequestedRegion( const itk::DataObject *data) { //no support for regions } void mitk::ContourModel::Clear() { //clear data and set to initial state again this->ClearData(); this->InitializeEmpty(); this->Modified(); } void mitk::ContourModel::Interpolate(int timestep) { if(!this->IsEmptyTimeStep(timestep)) { this->m_ContourSeries[timestep]->Interpolate(); this->InvokeEvent( ContourModelClosedEvent() ); this->Modified(); } } void mitk::ContourModel::RedistributeControlVertices(int period, int timestep) { if(!this->IsEmptyTimeStep(timestep)) { this->m_ContourSeries[timestep]->RedistributeControlVertices(this->GetSelectedVertex(), period); this->InvokeEvent( ContourModelClosedEvent() ); this->Modified(); } } void mitk::ContourModel::ClearData() { //call the superclass, this releases the data of BaseData Superclass::ClearData(); //clear out the time resolved contours this->m_ContourSeries.clear(); } void mitk::ContourModel::InitializeEmpty() { //clear data at timesteps this->m_ContourSeries.resize(0); this->m_ContourSeries.push_back(mitk::ContourElement::New()); //set number of timesteps to one this->InitializeTimeSlicedGeometry(1); m_SelectedVertex = NULL; this->m_lineInterpolation = ContourModel::LINEAR; } void mitk::ContourModel::UpdateOutputInformation() { if ( this->GetSource() ) { this->GetSource()->UpdateOutputInformation(); } //update the bounds of the geometry according to the stored vertices float mitkBounds[6]; //calculate the boundingbox at each timestep typedef itk::BoundingBox BoundingBoxType; typedef BoundingBoxType::PointsContainer PointsContainer; int timesteps = this->GetTimeSteps(); //iterate over the timesteps for(int currenTimeStep = 0; currenTimeStep < timesteps; currenTimeStep++) { if( dynamic_cast< mitk::PlaneGeometry* >(this->GetGeometry(currenTimeStep)) ) { //do not update bounds for 2D geometries, as they are unfortunately defined with min bounds 0! return; } else {//we have a 3D geometry -> let's update bounds //only update bounds if the contour was modified if (this->GetMTime() > this->GetGeometry(currenTimeStep)->GetBoundingBox()->GetMTime()) { mitkBounds[0] = 0.0; mitkBounds[1] = 0.0; mitkBounds[2] = 0.0; mitkBounds[3] = 0.0; mitkBounds[4] = 0.0; mitkBounds[5] = 0.0; BoundingBoxType::Pointer boundingBox = BoundingBoxType::New(); PointsContainer::Pointer points = PointsContainer::New(); VertexIterator it = this->IteratorBegin(currenTimeStep); VertexIterator end = this->IteratorEnd(currenTimeStep); //fill the boundingbox with the points while(it != end) { Point3D currentP = (*it)->Coordinates; BoundingBoxType::PointType p; p.CastFrom(currentP); points->InsertElement(points->Size(), p); it++; } //construct the new boundingBox boundingBox->SetPoints(points); boundingBox->ComputeBoundingBox(); BoundingBoxType::BoundsArrayType tmp = boundingBox->GetBounds(); mitkBounds[0] = tmp[0]; mitkBounds[1] = tmp[1]; mitkBounds[2] = tmp[2]; mitkBounds[3] = tmp[3]; mitkBounds[4] = tmp[4]; mitkBounds[5] = tmp[5]; //set boundingBox at current timestep Geometry3D* geometry3d = this->GetGeometry(currenTimeStep); geometry3d->SetBounds(mitkBounds); } } } GetTimeSlicedGeometry()->UpdateInformation(); } void mitk::ContourModel::ExecuteOperation(mitk::Operation* operation) { //not supported yet } diff --git a/Modules/Segmentation/DataManagement/mitkContourModel.h b/Modules/Segmentation/DataManagement/mitkContourModel.h index 79bffa37cc..ec83260af0 100644 --- a/Modules/Segmentation/DataManagement/mitkContourModel.h +++ b/Modules/Segmentation/DataManagement/mitkContourModel.h @@ -1,422 +1,427 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _MITK_CONTOURMODEL_H_ #define _MITK_CONTOURMODEL_H_ #include "mitkCommon.h" #include "SegmentationExports.h" #include "mitkBaseData.h" #include namespace mitk { /** \brief ContourModel is a structure of linked vertices defining a contour in 3D space. The vertices are stored in a mitk::ContourElement is stored for each timestep. The contour line segments are implicitly defined by the given linked vertices. By default two control points are are linked by a straight line.It is possible to add vertices at front and end of the contour and to iterate in both directions. Points are specified containing coordinates and additional (data) information, see mitk::ContourElement. For accessing a specific vertex either an index or a position in 3D Space can be used. The vertices are best accessed by using a VertexIterator. Interaction with the contour is thus available without any mitk interactor class using the api of ContourModel. It is possible to shift single vertices also as shifting the whole contour. A contour can be either open like a single curved line segment or closed. A closed contour can for example represent a jordan curve. \section mitkPointSetDisplayOptions The default mappers for this data structure are mitk::ContourModelGLMapper2D and mitk::ContourModelMapper3D. See these classes for display options which can can be set via properties. */ class Segmentation_EXPORT ContourModel : public BaseData { public: mitkClassMacro(ContourModel, BaseData); itkNewMacro(Self); mitkCloneMacro(Self); /*+++++++++++++++ typedefs +++++++++++++++++++++++++++++++*/ typedef mitk::ContourElement::VertexType VertexType; typedef mitk::ContourElement::VertexListType VertexListType; typedef mitk::ContourElement::VertexIterator VertexIterator; typedef mitk::ContourElement::ConstVertexIterator ConstVertexIterator; typedef std::vector< mitk::ContourElement::Pointer > ContourModelSeries; /*+++++++++++++++ END typedefs ++++++++++++++++++++++++++++*/ /** \brief Possible interpolation of the line segments between control points */ enum LineSegmentInterpolation{ LINEAR, B_SPLINE }; /*++++++++++++++++ inline methods +++++++++++++++++++++++*/ /** \brief Get the current selected vertex. */ VertexType* GetSelectedVertex() { return this->m_SelectedVertex; } /** \brief Deselect vertex. */ void Deselect() { this->m_SelectedVertex = NULL; } /** \brief Set selected vertex as control point */ void SetSelectedVertexAsControlPoint(bool isControlPoint=true) { if (this->m_SelectedVertex) { m_SelectedVertex->IsControlPoint = isControlPoint; this->Modified(); } } /** \brief Set the interpolation of the line segments between control points. */ void SetLineSegmentInterpolation(LineSegmentInterpolation interpolation) { this->m_lineInterpolation = interpolation; this->Modified(); } /** \brief Get the interpolation of the line segments between control points. */ LineSegmentInterpolation GetLineSegmentInterpolation() { return this->m_lineInterpolation; } /*++++++++++++++++ END inline methods +++++++++++++++++++++++*/ /** \brief Add a vertex to the contour at given timestep. The vertex is added at the end of contour. \pararm vertex - coordinate representation of a control point \pararm timestep - the timestep at which the vertex will be add ( default 0) @Note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeSlicedGeometry will not be expanded. */ void AddVertex(mitk::Point3D &vertex, int timestep=0); /** \brief Add a vertex to the contour at given timestep. The vertex is added at the end of contour. \param vertex - coordinate representation of a control point \param timestep - the timestep at which the vertex will be add ( default 0) @Note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeSlicedGeometry will not be expanded. */ void AddVertex(VertexType &vertex, int timestep=0); /** \brief Add a vertex to the contour. \pararm vertex - coordinate representation of a control point \pararm timestep - the timestep at which the vertex will be add ( default 0) \pararm isControlPoint - specifies the vertex to be handled in a special way (e.g. control points will be rendered). @Note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeSlicedGeometry will not be expanded. */ void AddVertex(mitk::Point3D &vertex, bool isControlPoint, int timestep=0); /** \brief Add a vertex to the contour at given timestep AT THE FRONT of the contour. The vertex is added at the FRONT of contour. \pararm vertex - coordinate representation of a control point \pararm timestep - the timestep at which the vertex will be add ( default 0) @Note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeSlicedGeometry will not be expanded. */ void AddVertexAtFront(mitk::Point3D &vertex, int timestep=0); /** \brief Add a vertex to the contour at given timestep AT THE FRONT of the contour. The vertex is added at the FRONT of contour. \pararm vertex - coordinate representation of a control point \pararm timestep - the timestep at which the vertex will be add ( default 0) @Note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeSlicedGeometry will not be expanded. */ void AddVertexAtFront(VertexType &vertex, int timestep=0); /** \brief Add a vertex to the contour at given timestep AT THE FRONT of the contour. \pararm vertex - coordinate representation of a control point \pararm timestep - the timestep at which the vertex will be add ( default 0) \pararm isControlPoint - specifies the vertex to be handled in a special way (e.g. control points will be rendered). @Note Adding a vertex to a timestep which exceeds the timebounds of the contour will not be added, the TimeSlicedGeometry will not be expanded. */ void AddVertexAtFront(mitk::Point3D &vertex, bool isControlPoint, int timestep=0); /** \brief Insert a vertex at given index. */ void InsertVertexAtIndex(mitk::Point3D &vertex, int index, bool isControlPoint=false, int timestep=0); /** \brief Return if the contour is closed or not. */ bool IsClosed( int timestep=0); /** \brief Concatenate two contours. The starting control point of the other will be added at the end of the contour. */ void Concatenate(mitk::ContourModel* other, int timestep=0); void RemoveIntersections(mitk::ContourModel* other, int timestep=0); /** \brief Returns a const VertexIterator at the start element of the contour. @throw mitk::Exception if the timestep is invalid. */ VertexIterator IteratorBegin( int timestep=0); /** \brief Returns a const VertexIterator at the end element of the contour. @throw mitk::Exception if the timestep is invalid. */ VertexIterator IteratorEnd( int timestep=0); /** \brief Close the contour. The last control point will be linked with the first point. */ virtual void Close( int timestep=0); /** \brief Set isClosed to false contour. The link between the last control point the first point will be removed. */ virtual void Open( int timestep=0); /** \brief Set isClosed to given boolean. false - The link between the last control point the first point will be removed. true - The last control point will be linked with the first point. */ virtual void SetIsClosed(bool isClosed, int timestep=0); /** \brief Returns the number of vertices at a given timestep. \pararm timestep - default = 0 */ int GetNumberOfVertices( int timestep=0); + /** \brief Returns whether the contour model is empty at a given timestep. + + \pararm timestep - default = 0 + */ + bool IsEmpty( int timestep=0); + /** \brief Returns the vertex at the index position within the container. */ virtual const VertexType* GetVertexAt(int index, int timestep=0) const; /** \brief Check if there isn't something at this timestep. */ virtual bool IsEmptyTimeStep( int t) const; /** \brief Check if mouse cursor is near the contour. */ virtual bool IsNearContour(mitk::Point3D &point, float eps, int timestep); /** \brief Mark a vertex at an index in the container as selected. */ bool SelectVertexAt(int index, int timestep=0); /** \brief Mark a vertex at an index in the container as control point. */ bool SetControlVertexAt(int index, int timestep=0); /** \brief Mark a vertex at a given position in 3D space. \pararm point - query point in 3D space \pararm eps - radius for nearest neighbour search (error bound). \pararm timestep - search at this timestep @return true = vertex found; false = no vertex found */ bool SelectVertexAt(mitk::Point3D &point, float eps, int timestep=0); /* \pararm point - query point in 3D space \pararm eps - radius for nearest neighbour search (error bound). \pararm timestep - search at this timestep @return true = vertex found; false = no vertex found */ bool SetControlVertexAt(mitk::Point3D &point, float eps, int timestep=0); /** \brief Remove a vertex at given index within the container. @return true = the vertex was successfuly removed; false = wrong index. */ bool RemoveVertexAt(int index, int timestep=0); /** \brief Remove a vertex at given timestep within the container. @return true = the vertex was successfuly removed. */ bool RemoveVertex(VertexType* vertex, int timestep=0); /** \brief Remove a vertex at a query position in 3D space. The vertex to be removed will be search by nearest neighbour search. Note that possibly no vertex at this position and eps is stored inside the contour. @return true = the vertex was successfuly removed; false = no vertex found. */ bool RemoveVertexAt(mitk::Point3D &point, float eps, int timestep=0); /** \brief Shift the currently selected vertex by a translation vector. \pararm translate - the translation vector. */ void ShiftSelectedVertex(mitk::Vector3D &translate); /** \brief Shift the whole contour by a translation vector at given timestep. \pararm translate - the translation vector. \pararm timestep - at this timestep the contour will be shifted. */ void ShiftContour(mitk::Vector3D &translate, int timestep=0); /** \brief Clear the storage container at given timestep. All control points are removed at timestep. */ virtual void Clear(int timestep); /*++++++++++++++++++ method inherit from base data +++++++++++++++++++++++++++*/ /** \brief Inherit from base data - no region support available for contourModel objects. */ virtual void SetRequestedRegionToLargestPossibleRegion (); /** \brief Inherit from base data - no region support available for contourModel objects. */ virtual bool RequestedRegionIsOutsideOfTheBufferedRegion (); /** \brief Inherit from base data - no region support available for contourModel objects. */ virtual bool VerifyRequestedRegion (); /** \brief Get the updated geometry with recomputed bounds. */ virtual const mitk::Geometry3D* GetUpdatedGeometry (int t=0); /** \brief Get the Geometry3D for timestep t. */ virtual mitk::Geometry3D* GetGeometry (int t=0) const; /** \brief Inherit from base data - no region support available for contourModel objects. */ virtual void SetRequestedRegion( const itk::DataObject *data); /** \brief Expand the timebounds of the TimeSlicedGeometry to given number of timesteps. */ virtual void Expand( int timeSteps ); /** \brief Update the OutputInformation of a ContourModel object The BoundingBox of the contour will be updated, if necessary. */ virtual void UpdateOutputInformation(); /** \brief Clear the storage container. The object is set to initial state. All control points are removed and the number of timesteps are set to 1. */ virtual void Clear(); /** \brief overwrite if the Data can be called by an Interactor (StateMachine). */ void ExecuteOperation(Operation* operation); /** \brief Rebuilds all line segments for timestep according to the active type of interpolation method \param timestep - at this timestep all lines will be rebuilt. */ virtual void Interpolate(int timestep); virtual void RedistributeControlVertices(int period, int timestep); protected: ContourModel(); ContourModel(const mitk::ContourModel &other); virtual ~ContourModel(); //inherit from BaseData. called by Clear() virtual void ClearData(); //inherit from BaseData. Initial state of a contour with no vertices and a single timestep. virtual void InitializeEmpty(); //Shift a vertex void ShiftVertex(VertexType* vertex, mitk::Vector3D &vector); - //Storage with time resolved support. ContourModelSeries m_ContourSeries; //The currently selected vertex. VertexType* m_SelectedVertex; //The interpolation of the line segment between control points. LineSegmentInterpolation m_lineInterpolation; }; itkEventMacro( ContourModelEvent, itk::AnyEvent ); itkEventMacro( ContourModelShiftEvent, ContourModelEvent ); itkEventMacro( ContourModelSizeChangeEvent, ContourModelEvent ); itkEventMacro( ContourModelAddEvent, ContourModelSizeChangeEvent ); itkEventMacro( ContourModelRemoveEvent, ContourModelSizeChangeEvent ); itkEventMacro( ContourModelExpandTimeBoundsEvent, ContourModelEvent ); itkEventMacro( ContourModelClosedEvent, ContourModelEvent ); } #endif diff --git a/Modules/Segmentation/Interactions/mitkContourModelLiveWireInteractor.cpp b/Modules/Segmentation/Interactions/mitkContourModelLiveWireInteractor.cpp index b85c97969f..67ef96d0e7 100644 --- a/Modules/Segmentation/Interactions/mitkContourModelLiveWireInteractor.cpp +++ b/Modules/Segmentation/Interactions/mitkContourModelLiveWireInteractor.cpp @@ -1,427 +1,434 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourModelLiveWireInteractor.h" #include "mitkToolManager.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include #include #include mitk::ContourModelLiveWireInteractor::ContourModelLiveWireInteractor(DataNode* dataNode) :ContourModelInteractor(dataNode) { m_LiveWireFilter = mitk::ImageLiveWireContourModelFilter::New(); m_NextActiveVertexDown.Fill(0); m_NextActiveVertexUp.Fill(0); } mitk::ContourModelLiveWireInteractor::~ContourModelLiveWireInteractor() { } bool mitk::ContourModelLiveWireInteractor::OnCheckPointClick( Action* action, const StateEvent* stateEvent) { const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) { this->HandleEvent( new mitk::StateEvent(EIDNO, stateEvent->GetEvent()) ); return false; } mitk::StateEvent* newStateEvent = NULL; int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep(); mitk::ContourModel *contour = dynamic_cast( m_DataNode->GetData() ); assert ( contour ); contour->Deselect(); // Check distance to any vertex. // Transition YES if click close to a vertex mitk::Point3D click = positionEvent->GetWorldPosition(); if (contour->SelectVertexAt(click, 1.5, timestep) ) { contour->SetSelectedVertexAsControlPoint(false); m_lastMousePosition = click; m_ContourLeft = mitk::ContourModel::New(); //get coordinates of next active vertex downwards from selected vertex int downIndex = this->SplitContourFromSelectedVertex( contour, m_ContourLeft, false, timestep); m_NextActiveVertexDownIter = contour->IteratorBegin() + downIndex; m_NextActiveVertexDown = (*m_NextActiveVertexDownIter)->Coordinates; m_ContourRight = mitk::ContourModel::New(); //get coordinates of next active vertex upwards from selected vertex int upIndex = this->SplitContourFromSelectedVertex( contour, m_ContourRight, true, timestep); m_NextActiveVertexUpIter = contour->IteratorBegin() + upIndex; m_NextActiveVertexUp = (*m_NextActiveVertexUpIter)->Coordinates; // clear previous void positions this->m_LiveWireFilter->ClearRepulsivePoints(); // set the current contour as void positions in the cost map // start with down side mitk::ContourModel::VertexIterator iter = contour->IteratorBegin(timestep); for (;iter != m_NextActiveVertexDownIter; iter++) { itk::Index<2> idx; this->m_WorkingImage->GetGeometry()->WorldToIndex((*iter)->Coordinates, idx); this->m_LiveWireFilter->AddRepulsivePoint( idx ); } // continue with upper side iter = m_NextActiveVertexUpIter + 1; for (;iter != contour->IteratorEnd(timestep); iter++) { itk::Index<2> idx; this->m_WorkingImage->GetGeometry()->WorldToIndex((*iter)->Coordinates, idx); this->m_LiveWireFilter->AddRepulsivePoint( idx ); } // let us have the selected point as a control point contour->SetSelectedVertexAsControlPoint(true); // finally, allow for leave newStateEvent = new mitk::StateEvent(EIDYES, stateEvent->GetEvent()); } else { // do not allow for leave newStateEvent = new mitk::StateEvent(EIDNO, stateEvent->GetEvent()); } this->HandleEvent( newStateEvent ); assert( positionEvent->GetSender()->GetRenderWindow() ); mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() ); return true; } bool mitk::ContourModelLiveWireInteractor::OnDeletePoint( Action* action, const StateEvent* stateEvent) { int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep(); mitk::ContourModel *contour = dynamic_cast( m_DataNode->GetData() ); assert ( contour ); if (contour->GetSelectedVertex()) { mitk::ContourModel::Pointer newContour = mitk::ContourModel::New(); newContour->Expand(contour->GetTimeSteps()); newContour->Concatenate( m_ContourLeft, timestep ); //recompute contour between neighbored two active control points this->m_LiveWireFilter->SetStartPoint( this->m_NextActiveVertexDown ); this->m_LiveWireFilter->SetEndPoint( this->m_NextActiveVertexUp ); this->m_LiveWireFilter->ClearRepulsivePoints(); this->m_LiveWireFilter->Update(); mitk::ContourModel *liveWireContour = this->m_LiveWireFilter->GetOutput(); assert ( liveWireContour ); + if ( liveWireContour->IsEmpty(timestep) ) + return false; + liveWireContour->RemoveVertexAt( 0, timestep); liveWireContour->RemoveVertexAt( liveWireContour->GetNumberOfVertices(timestep) - 1, timestep); //insert new live wire computed points newContour->Concatenate( liveWireContour, timestep ); // insert right side of original contour newContour->Concatenate( this->m_ContourRight, timestep ); newContour->SetIsClosed(contour->IsClosed(timestep), timestep); m_DataNode->SetData(newContour); assert( stateEvent->GetEvent()->GetSender()->GetRenderWindow() ); mitk::RenderingManager::GetInstance()->RequestUpdate( stateEvent->GetEvent()->GetSender()->GetRenderWindow() ); return true; } return false; } bool mitk::ContourModelLiveWireInteractor::OnMovePoint( Action* action, const StateEvent* stateEvent) { const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent()); if (!positionEvent) return false; int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep(); mitk::Point3D currentPosition = positionEvent->GetWorldPosition(); mitk::ContourModel *contour = dynamic_cast( m_DataNode->GetData() ); assert ( contour ); // recompute left live wire, i.e. the contour between previous active vertex and selected vertex this->m_LiveWireFilter->SetStartPoint( this->m_NextActiveVertexDown ); this->m_LiveWireFilter->SetEndPoint( currentPosition ); + // remove void positions from the last portion of the contour that was modified, i.e. between + // previous active vertex and next active vertex. if (!m_ContourBeingModified.empty()) { - // remove void positions from the last portion of the contour that was modified std::vector< itk::Index< 2 > >::const_iterator msIter = m_ContourBeingModified.begin(); for (;msIter != m_ContourBeingModified.end(); msIter++) { this->m_LiveWireFilter->RemoveRepulsivePoint( (*msIter) ); } } - // update to get the left livewire. Remember that the rest of the contour is already + // update to get the left livewire. Remember that the points in the rest of the contour are already // set as void positions in the filter this->m_LiveWireFilter->Update(); mitk::ContourModel::Pointer leftLiveWire = this->m_LiveWireFilter->GetOutput(); assert ( leftLiveWire ); - leftLiveWire->RemoveVertexAt(0, timestep); + if ( !leftLiveWire->IsEmpty(timestep) ) + leftLiveWire->RemoveVertexAt(0, timestep); - // now the container has to be emty + // at this point the container has to be empty m_ContourBeingModified.clear(); // add points from already calculated left live wire contour mitk::ContourModel::VertexIterator iter = leftLiveWire->IteratorBegin(timestep); for (;iter != leftLiveWire->IteratorEnd(timestep); iter++) { itk::Index<2> idx; this->m_WorkingImage->GetGeometry()->WorldToIndex((*iter)->Coordinates, idx); this->m_LiveWireFilter->AddRepulsivePoint( idx ); // keep points from left live wire contour m_ContourBeingModified.push_back(idx); } // recompute right live wire, i.e. the contour between selected vertex and next active vertex this->m_LiveWireFilter->SetStartPoint( currentPosition ); this->m_LiveWireFilter->SetEndPoint( m_NextActiveVertexUp ); // update filter with all contour points set as void but the right live wire portion to be calculated now this->m_LiveWireFilter->Update(); mitk::ContourModel::Pointer rightLiveWire = this->m_LiveWireFilter->GetOutput(); assert ( rightLiveWire ); - rightLiveWire->RemoveVertexAt(0, timestep); + if ( !rightLiveWire->IsEmpty(timestep) ) + rightLiveWire->RemoveVertexAt(0, timestep); - leftLiveWire->SetControlVertexAt(leftLiveWire->GetNumberOfVertices()-1, timestep); + if ( !leftLiveWire->IsEmpty(timestep) ) + leftLiveWire->SetControlVertexAt(leftLiveWire->GetNumberOfVertices()-1, timestep); //leftLiveWire->SelectVertexAt(leftLiveWire->GetNumberOfVertices()-1, timestep); // set corrected left live wire to its node m_LeftLiveWireContourNode->SetData(leftLiveWire); // set corrected right live wire to its node m_RightLiveWireContourNode->SetData(rightLiveWire); iter = rightLiveWire->IteratorBegin(timestep); for (;iter != rightLiveWire->IteratorEnd(timestep); iter++) { itk::Index<2> idx; this->m_WorkingImage->GetGeometry()->WorldToIndex((*iter)->Coordinates, idx); // keep points from right live wire contour m_ContourBeingModified.push_back(idx); } mitk::ContourModel::Pointer newContour = mitk::ContourModel::New(); newContour->Expand(contour->GetTimeSteps()); // concatenate left original contour newContour->Concatenate( this->m_ContourLeft, timestep ); newContour->Deselect(); // concatenate left live wire newContour->Concatenate( leftLiveWire, timestep ); // set last inserted vertex as selected newContour->SelectVertexAt(newContour->GetNumberOfVertices()-1, timestep); // concatenate right live wire newContour->Concatenate( rightLiveWire, timestep ); // concatenate right original contour newContour->Concatenate( this->m_ContourRight, timestep ); newContour->SetIsClosed(contour->IsClosed(timestep), timestep); m_DataNode->SetData(newContour); this->m_lastMousePosition = positionEvent->GetWorldPosition(); assert( positionEvent->GetSender()->GetRenderWindow() ); mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() ); return true; } int mitk::ContourModelLiveWireInteractor::SplitContourFromSelectedVertex(mitk::ContourModel* srcContour, mitk::ContourModel* destContour, bool fromSelectedUpwards, int timestep) { mitk::ContourModel::VertexIterator end = srcContour->IteratorEnd(); mitk::ContourModel::VertexIterator begin = srcContour->IteratorBegin(); //search next active control point to left and rigth and set as start and end point for filter mitk::ContourModel::VertexIterator itSelected = begin; // move iterator to position while ((*itSelected) != srcContour->GetSelectedVertex()) { itSelected++; } // CASE search upwards for next control point if(fromSelectedUpwards) { mitk::ContourModel::VertexIterator itUp = itSelected; if(itUp != end) { itUp++;//step once up otherwise the loop breaks immediately } while( itUp != end && !((*itUp)->IsControlPoint)) { itUp++; } mitk::ContourModel::VertexIterator it = itUp; if (itSelected != begin) { //copy the rest of the original contour while (it != end) { destContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep); it++; } } //else do not copy the contour //return the offset of iterator at one before next-vertex-upwards if(itUp != begin) { return std::distance( begin, itUp) - 1; } else { return std::distance( begin, itUp); } } else //CASE search downwards for next control point { mitk::ContourModel::VertexIterator itDown = itSelected; mitk::ContourModel::VertexIterator it = srcContour->IteratorBegin(); if( itSelected != begin ) { if(itDown != begin) { itDown--;//step once down otherwise the the loop breaks immediately } while( itDown != begin && !((*itDown)->IsControlPoint)){ itDown--; } if(it != end)//if not empty { //always add the first vertex destContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep); it++; } //copy from begin to itDown while(it <= itDown) { destContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep); it++; } } else { //if selected vertex is the first element search from end of contour downwards itDown = end; itDown--; while(!((*itDown)->IsControlPoint)){itDown--;} //move one forward as we don't want the first control point it++; //move iterator to second control point while( (it!=end) && !((*it)->IsControlPoint) ){it++;} //copy from begin to itDown while(it <= itDown) { //copy the contour from second control point to itDown destContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep); it++; } } /* //add vertex at itDown - it's not considered during while loop if( it != begin && it != end) { //destContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep); } */ //return the offset of iterator at one after next-vertex-downwards if( itDown != end) { return std::distance( begin, itDown);// + 1;//index of next vertex } else { return std::distance( begin, itDown) - 1; } } } bool mitk::ContourModelLiveWireInteractor::OnFinishEditing( Action* action, const StateEvent* stateEvent) { int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep(); mitk::ContourModel *leftLiveWire = dynamic_cast( this->m_LeftLiveWireContourNode->GetData() ); assert ( leftLiveWire ); leftLiveWire->Clear(timestep); mitk::ContourModel *rightLiveWire = dynamic_cast( this->m_RightLiveWireContourNode->GetData() ); assert ( rightLiveWire ); rightLiveWire->Clear(timestep); assert( stateEvent->GetEvent()->GetSender()->GetRenderWindow() ); mitk::RenderingManager::GetInstance()->RequestUpdate( stateEvent->GetEvent()->GetSender()->GetRenderWindow() ); return true; }