diff --git a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkNonLocalMeansDenoisingFilter.txx b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkNonLocalMeansDenoisingFilter.txx index e6ade2505c..59ad9d019a 100644 --- a/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkNonLocalMeansDenoisingFilter.txx +++ b/Modules/DiffusionImaging/DiffusionCore/Algorithms/itkNonLocalMeansDenoisingFilter.txx @@ -1,278 +1,321 @@ /*=================================================================== 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 __itkNonLocalMeansDenoisingFilter_txx #define __itkNonLocalMeansDenoisingFilter_txx #include #include #include #define _USE_MATH_DEFINES #include #include "itkImageRegionIterator.h" #include "itkNeighborhoodIterator.h" #include +#include namespace itk { template< class TPixelType > NonLocalMeansDenoisingFilter< TPixelType > ::NonLocalMeansDenoisingFilter() { this->SetNumberOfRequiredInputs( 2 ); } template< class TPixelType > void NonLocalMeansDenoisingFilter< TPixelType > ::BeforeThreadedGenerateData() { typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0)); typename OutputImageType::PixelType px; px.SetSize(1); px.SetElement(0,0); outputImage->FillBuffer(px); typename InputImageType::Pointer inImage = static_cast< InputImageType* >(this->ProcessObject::GetInput(0)); typename MaskImageType::Pointer mask = static_cast< MaskImageType* >(this->ProcessObject::GetInput(1)); int size = inImage->GetVectorLength(); m_Deviations.SetSize(size); typename ImageExtractorType::Pointer extractor = ImageExtractorType::New(); extractor->SetInput(inImage); - /// calculate max value of mask, for correct inversion + // calculate max value of mask, for correct inversion typename StatisticsFilterType::Pointer statisticsFilter = StatisticsFilterType::New(); statisticsFilter->SetInput(mask); statisticsFilter->Update(); - /// invert mask, to mask the backround + // invert mask, to mask the backround typename InvertImageFilterType::Pointer inverter = InvertImageFilterType::New(); inverter->SetInput(mask); inverter->SetMaximum(statisticsFilter->GetMaximum()); inverter->Update(); - /// make sure inverted mask has same origin is the brainmask + // make sure inverted mask has same origin is the brainmask typename ChangeInformationType::Pointer changeMaskFilter = ChangeInformationType::New(); changeMaskFilter->ChangeOriginOn(); changeMaskFilter->SetInput(inverter->GetOutput()); changeMaskFilter->SetOutputOrigin(mask->GetOrigin()); changeMaskFilter->Update(); typename MaskImageType::Pointer invertedMask = changeMaskFilter->GetOutput(); typename MaskImageType::PointType imageOrigin = inImage->GetOrigin(); typename MaskImageType::PointType maskOrigin = invertedMask->GetOrigin(); long offset[3]; typedef itk::ContinuousIndex ContinousIndexType; ContinousIndexType maskOriginContinousIndex, imageOriginContinousIndex; inImage->TransformPhysicalPointToContinuousIndex(maskOrigin, maskOriginContinousIndex); inImage->TransformPhysicalPointToContinuousIndex(imageOrigin, imageOriginContinousIndex); - /// make sure there is no misalignment between mask and image + // make sure there is no misalignment between mask and image for ( unsigned int i = 0; i < 3; ++i ) { double misalignment = maskOriginContinousIndex[i] - floor( maskOriginContinousIndex[i] + 0.5 ); if ( fabs( misalignment ) > mitk::eps ) { itkExceptionMacro( << "Pixels/voxels of mask and image are not sufficiently aligned! (Misalignment: " << misalignment << ")" ); } double indexCoordDistance = maskOriginContinousIndex[i] - imageOriginContinousIndex[i]; offset[i] = (int) indexCoordDistance + inImage->GetBufferedRegion().GetIndex()[i]; } - /// calculate for each channel the stddev + // calculate for each channel the stddev for ( int i = 0; i < size; ++i) { /// extract channel i of the input extractor->SetIndex(i); extractor->Update(); - /// adapt mask to the image + // adapt mask to the image typename ChangeInformationType::Pointer adaptMaskFilter; adaptMaskFilter = ChangeInformationType::New(); adaptMaskFilter->ChangeOriginOn(); adaptMaskFilter->ChangeRegionOn(); adaptMaskFilter->SetInput( invertedMask ); adaptMaskFilter->SetOutputOrigin( extractor->GetOutput()->GetOrigin() /*image->GetOrigin()*/ ); adaptMaskFilter->SetOutputOffset( offset ); adaptMaskFilter->Update(); - /// extract backround as the ROI + // extract backround as the ROI typename MaskImageType::Pointer adaptedMaskImage = adaptMaskFilter->GetOutput(); typename ExtractImageFilterType::Pointer extractImageFilter = ExtractImageFilterType::New(); extractImageFilter->SetInput( extractor->GetOutput() ); extractImageFilter->SetExtractionRegion( adaptedMaskImage->GetBufferedRegion() ); extractImageFilter->Update(); - /// calculate statistics of ROI + // calculate statistics of ROI typename MaskImageType::Pointer adaptedImage = extractImageFilter->GetOutput(); typename LabelStatisticsFilterType::Pointer labelStatisticsFilter = LabelStatisticsFilterType::New(); labelStatisticsFilter->SetInput(adaptedImage); labelStatisticsFilter->SetLabelInput(adaptedMaskImage); labelStatisticsFilter->UseHistogramsOff(); labelStatisticsFilter->GetOutput()->SetRequestedRegion( adaptedMaskImage->GetLargestPossibleRegion() ); labelStatisticsFilter->Update(); - /// save the stddev of each channel + // save the stddev of each channel m_Deviations.SetElement(i, labelStatisticsFilter->GetSigma(1)); } m_CurrentVoxelCount = 0; } template< class TPixelType > void NonLocalMeansDenoisingFilter< TPixelType > ::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType ) { - /// initialize iterators + // initialize iterators typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0)); ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread); oit.GoToBegin(); typedef ImageRegionIteratorWithIndex InputIteratorType; typename InputImageType::Pointer inputImagePointer = NULL; inputImagePointer = static_cast< InputImageType * >( this->ProcessObject::GetInput(0) ); InputIteratorType git(inputImagePointer, outputRegionForThread ); InputIteratorType njit(inputImagePointer, outputRegionForThread ); InputIteratorType niit(inputImagePointer, outputRegionForThread ); InputIteratorType hit(inputImagePointer, outputRegionForThread); git.GoToBegin(); - double Z = std::pow((double)(m_SearchRadius*2+1), 3); - double size = std::pow((double)(m_ComparisonRadius*2+1), 3); - - /// iterate over complete image region + // iterate over complete image region while( !git.IsAtEnd() ) { + + typename OutputImageType::PixelType outpix; outpix.SetSize (inputImagePointer->GetVectorLength()); - /// count amount of same voxels in neighborhood V around xi, to determine normalization constant Z for (int i = 0; i < (int)inputImagePointer->GetVectorLength(); ++i) { + double Z = 0; double sumj = 0; - double wj = 0; + double w = 0; double deviation = m_Deviations.GetElement(i); + std::vector wj; + std::vector p; for (int x = git.GetIndex().GetElement(0) - m_SearchRadius; x <= git.GetIndex().GetElement(0) + m_SearchRadius; ++x) { for (int y = git.GetIndex().GetElement(1) - m_SearchRadius; y <= git.GetIndex().GetElement(1) + m_SearchRadius; ++y) { for (int z = git.GetIndex().GetElement(2) - m_SearchRadius; z <= git.GetIndex().GetElement(2) + m_SearchRadius; ++z) { typename InputIteratorType::IndexType idx; idx.SetElement(0, x); idx.SetElement(1, y); idx.SetElement(2, z); if (inputImagePointer->GetLargestPossibleRegion().IsInside(idx)) { hit.SetIndex(idx); TPixelType pixelJ = hit.Get()[i]; double sumk = 0; + double size = 0; + for (int xi = git.GetIndex().GetElement(0) - m_ComparisonRadius, xj = hit.GetIndex().GetElement(0) - m_ComparisonRadius; xi <= git.GetIndex().GetElement(0) + m_ComparisonRadius; ++xi, ++xj) + { + for (int yi = git.GetIndex().GetElement(1) - m_ComparisonRadius, yj = hit.GetIndex().GetElement(1) - m_ComparisonRadius; yi <= git.GetIndex().GetElement(1) + m_ComparisonRadius; ++yi, ++yj) + { + for (int zi = git.GetIndex().GetElement(2) - m_ComparisonRadius, zj = hit.GetIndex().GetElement(2) - m_ComparisonRadius; zi <= git.GetIndex().GetElement(2) + m_ComparisonRadius; ++zi, ++zj) + { + typename InputIteratorType::IndexType indexI, indexJ; + indexI.SetElement(0, xi); + indexI.SetElement(1, yi); + indexI.SetElement(2, zi); + indexJ.SetElement(0, xj); + indexJ.SetElement(1, yj); + indexJ.SetElement(2, zj); + // Count amount of used neighbors + if (inputImagePointer->GetLargestPossibleRegion().IsInside(indexI) && inputImagePointer->GetLargestPossibleRegion().IsInside(indexJ)) + { + if (m_UseJointInformation) + { + for (int d = i - m_ChannelRadius; d <= i + m_ChannelRadius; ++d) + { + if (d >= 0 && d < (int)inputImagePointer->GetVectorLength()) + { + size++; + } + } + } + else + { + size++; + } + } + } + } + } for (int xi = git.GetIndex().GetElement(0) - m_ComparisonRadius, xj = hit.GetIndex().GetElement(0) - m_ComparisonRadius; xi <= git.GetIndex().GetElement(0) + m_ComparisonRadius; ++xi, ++xj) { for (int yi = git.GetIndex().GetElement(1) - m_ComparisonRadius, yj = hit.GetIndex().GetElement(1) - m_ComparisonRadius; yi <= git.GetIndex().GetElement(1) + m_ComparisonRadius; ++yi, ++yj) { for (int zi = git.GetIndex().GetElement(2) - m_ComparisonRadius, zj = hit.GetIndex().GetElement(2) - m_ComparisonRadius; zi <= git.GetIndex().GetElement(2) + m_ComparisonRadius; ++zi, ++zj) { typename InputIteratorType::IndexType indexI, indexJ; indexI.SetElement(0, xi); indexI.SetElement(1, yi); indexI.SetElement(2, zi); indexJ.SetElement(0, xj); indexJ.SetElement(1, yj); indexJ.SetElement(2, zj); - /// Compare neighborhoods ni & nj + // Compare neighborhoods ni & nj if (inputImagePointer->GetLargestPossibleRegion().IsInside(indexI) && inputImagePointer->GetLargestPossibleRegion().IsInside(indexJ)) { niit.SetIndex(indexI); njit.SetIndex(indexJ); if (m_UseJointInformation) { - /// if filter should use joint information it is used a 4d Neighborhood including surrounding channels + // if filter should use joint information. A 4d Neighborhood including surrounding channels is used. for (int d = i - m_ChannelRadius; d <= i + m_ChannelRadius; ++d) { if (d >= 0 && d < (int)inputImagePointer->GetVectorLength()) { int diff = niit.Get()[d] - njit.Get()[d]; sumk += (double)(diff*diff); } } } else { int diff = niit.Get()[i] - njit.Get()[i]; sumk += (double)(diff*diff); } } } } } - /// weight all found neighborhoods - wj = std::exp( - (std::sqrt((sumk / size)) / (deviation * deviation)))/Z; - - /// calculate NLMr - sumj += wj * (double)(pixelJ*pixelJ); + // weight all neighborhoods + w = std::exp( - (std::sqrt((sumk / size)) / (deviation * deviation))); + wj.push_back(w); + p.push_back((double)(pixelJ*pixelJ)); + Z += w; } } } } - if (sumj < 0) + for (unsigned int n = 0; n < wj.size(); ++n) + { + sumj += (wj[n]/Z) * p[n]; + } + double df = sumj - (2 * deviation * deviation); + if (df < 0) { - sumj = 0; + df = 0; } - TPixelType outval = std::floor(std::sqrt(sumj - (2 * deviation * deviation)) + 0.5); + TPixelType outval = std::floor(std::sqrt(df) + 0.5); outpix.SetElement(i, outval); } + oit.Set(outpix); ++oit; ++m_CurrentVoxelCount; ++git; } MITK_INFO << "One Thread finished calculation"; } template< class TPixelType > void NonLocalMeansDenoisingFilter< TPixelType >::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); } template< class TPixelType > void NonLocalMeansDenoisingFilter< TPixelType >::SetInputImage(const InputImageType* image) { this->SetNthInput(0, const_cast< InputImageType* >(image)); } template< class TPixelType > void NonLocalMeansDenoisingFilter< TPixelType >::SetInputMask(const MaskImageType* mask) { this->SetNthInput(1, const_cast< MaskImageType* >(mask)); } } #endif // __itkNonLocalMeansDenoisingFilter_txx diff --git a/Modules/DiffusionImaging/MiniApps/DwiDenoising.cpp b/Modules/DiffusionImaging/MiniApps/DwiDenoising.cpp index 8edbd4cdc0..0bdac8ead8 100644 --- a/Modules/DiffusionImaging/MiniApps/DwiDenoising.cpp +++ b/Modules/DiffusionImaging/MiniApps/DwiDenoising.cpp @@ -1,172 +1,172 @@ /*=================================================================== 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 "MiniAppManager.h" #include #include #include "ctkCommandLineParser.h" #include #include #include #include #include typedef mitk::DiffusionImage DiffusionImageType; typedef itk::Image ImageType; mitk::BaseData::Pointer LoadFile(std::string filename) { if( filename.empty() ) return NULL; const std::string s1="", s2=""; std::vector infile = mitk::BaseDataIO::LoadBaseDataFromFile( filename, s1, s2, false ); if( infile.empty() ) { MITK_INFO << "File " << filename << " could not be read!"; return NULL; } mitk::BaseData::Pointer baseData = infile.at(0); return baseData; } /** - * Calculate indices derived from Qball or tensor images + * Denoises DWI using the Nonlocal - Means algorithm */ int DwiDenoising(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input image (DWI)", us::Any(), false); parser.addArgument("mask", "m", ctkCommandLineParser::String, "brainmask for input image", us::Any(), false); parser.addArgument("search", "s", ctkCommandLineParser::Int, "search radius", us::Any(), false); parser.addArgument("compare", "c", ctkCommandLineParser::Int, "compare radius", us::Any(), false); parser.addArgument("channels", "ch", ctkCommandLineParser::Int, "radius of used channels", us::Any(), true); map parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; string inFileName = us::any_cast(parsedArgs["input"]); string maskName = us::any_cast(parsedArgs["mask"]); string outFileName = inFileName; boost::algorithm::erase_all(outFileName, ".dwi"); int search = us::any_cast(parsedArgs["search"]); int compare = us::any_cast(parsedArgs["compare"]); int channels = 0; if (parsedArgs.count("channels")) channels = us::any_cast(parsedArgs["channels"]); try { if( boost::algorithm::ends_with(inFileName, ".dwi")) { DiffusionImageType::Pointer dwi = dynamic_cast(LoadFile(inFileName).GetPointer()); mitk::Image::Pointer mask = dynamic_cast(LoadFile(maskName).GetPointer()); ImageType::Pointer itkMask = ImageType::New(); mitk::CastToItkImage(mask, itkMask); itk::NonLocalMeansDenoisingFilter::Pointer filter = itk::NonLocalMeansDenoisingFilter::New(); filter->SetNumberOfThreads(12); filter->SetInputImage(dwi->GetVectorImage()); filter->SetInputMask(itkMask); if (channels == 0) { MITK_INFO << "Denoising with: s = " << search << "; c = " << compare; filter->SetUseJointInformation(false); filter->SetSearchRadius(search); filter->SetComparisonRadius(compare); filter->Update(); DiffusionImageType::Pointer output = DiffusionImageType::New(); output->SetVectorImage(filter->GetOutput()); output->SetReferenceBValue(dwi->GetReferenceBValue()); output->SetDirections(dwi->GetDirections()); output->InitializeFromVectorImage(); std::stringstream name; name << outFileName << "_NLMr_" << search << "-" << compare << ".dwi"; MITK_INFO << "Writing: " << name.str(); mitk::NrrdDiffusionImageWriter::Pointer writer = mitk::NrrdDiffusionImageWriter::New(); writer->SetInput(output); writer->SetFileName(name.str()); writer->Update(); } else { MITK_INFO << "Denoising with: s = " << search << "; c = " << compare << "; ch = " << channels; filter->SetUseJointInformation(true); filter->SetSearchRadius(search); filter->SetComparisonRadius(compare); filter->SetChannelRadius(channels); filter->Update(); DiffusionImageType::Pointer output = DiffusionImageType::New(); output->SetVectorImage(filter->GetOutput()); output->SetReferenceBValue(dwi->GetReferenceBValue()); output->SetDirections(dwi->GetDirections()); output->InitializeFromVectorImage(); std::stringstream name; name << outFileName << "_NLMv_" << search << "-" << compare << "-" << channels << ".dwi"; MITK_INFO << "Writing " << name.str(); mitk::NrrdDiffusionImageWriter::Pointer writer = mitk::NrrdDiffusionImageWriter::New(); writer->SetInput(output); writer->SetFileName(name.str()); writer->Update(); } MITK_INFO << "Finish!"; } else { MITK_INFO << "Only supported for .dwi!"; } } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } return EXIT_SUCCESS; } RegisterDiffusionMiniApp(DwiDenoising); diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDenoisingView.cpp b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDenoisingView.cpp index 08fcf66e9f..e91810749f 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDenoisingView.cpp +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDenoisingView.cpp @@ -1,488 +1,500 @@ /*=================================================================== 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. ===================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkDenoisingView.h" #include #include QmitkDenoisingWorker::QmitkDenoisingWorker(QmitkDenoisingView *view) : m_View(view) { } void QmitkDenoisingWorker::run() { if (m_View->m_ImageNode.IsNotNull() && m_View->m_BrainMaskNode.IsNotNull()) { switch (m_View->m_SelectedFilter) { case 0: case 3: { break; } case 1: case 2: { - m_View->m_NonLocalMeansFilter->Update(); - break; + try + { + m_View->m_NoExceptionThrown = true; + m_View->m_NonLocalMeansFilter->Update(); + } + catch (itk::ExceptionObject& e) + { + m_View->m_NoExceptionThrown = false; + MITK_ERROR << e.what(); + } + break; } } m_View->m_DenoisingThread.quit(); } } const std::string QmitkDenoisingView::VIEW_ID = "org.mitk.views.denoisingview"; QmitkDenoisingView::QmitkDenoisingView() : QmitkFunctionality() , m_Controls( 0 ) , m_ImageNode(NULL) , m_BrainMaskNode(NULL) , m_DenoisingWorker(this) , m_ThreadIsRunning(false) , m_NonLocalMeansFilter(NULL) , m_InputImage(NULL) , m_LastProgressCount(0) , m_MaxProgressCount(0) { m_DenoisingWorker.moveToThread(&m_DenoisingThread); connect(&m_DenoisingThread, SIGNAL(started()), this, SLOT(BeforeThread())); connect(&m_DenoisingThread, SIGNAL(started()), &m_DenoisingWorker, SLOT(run())); connect(&m_DenoisingThread, SIGNAL(finished()), this, SLOT(AfterThread())); connect(&m_DenoisingThread, SIGNAL(terminated()), this, SLOT(AfterThread())); m_DenoisingTimer = new QTimer(this); } QmitkDenoisingView::~QmitkDenoisingView() { delete m_DenoisingTimer; } void QmitkDenoisingView::CreateQtPartControl( QWidget *parent ) { // build up qt view, unless already done if ( !m_Controls ) { // create GUI widgets from the Qt Designer's .ui file m_Controls = new Ui::QmitkDenoisingViewControls; m_Controls->setupUi( parent ); CreateConnections(); ResetParameterPanel(); } } void QmitkDenoisingView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_ApplyButton), SIGNAL(clicked()), this, SLOT(StartDenoising())); connect( (QObject*)(m_Controls->m_SelectFilterComboBox), SIGNAL(activated(int)), this, SLOT(SelectFilter(int))); connect( m_DenoisingTimer, SIGNAL(timeout()), this, SLOT(UpdateProgress())); } } void QmitkDenoisingView::Activated() { QmitkFunctionality::Activated(); m_Controls->m_SelectFilterComboBox->clear(); m_Controls->m_SelectFilterComboBox->insertItem(NOFILTERSELECTED, QString( QApplication::translate("QmitkDenoisingView", "Please select a filter", 0, QApplication::UnicodeUTF8) )); m_Controls->m_SelectFilterComboBox->insertItem(NLMR, QString( QApplication::translate("QmitkDenoisingView", "Non local means filter", 0, QApplication::UnicodeUTF8) )); m_Controls->m_SelectFilterComboBox->insertItem(NLMV, QString( QApplication::translate("QmitkDenoisingView", "Non local means filter with joint information", 0, QApplication::UnicodeUTF8) )); m_Controls->m_SelectFilterComboBox->insertItem(GAUSS, QString( QApplication::translate("QmitkDenoisingView", "Discrete gaussian filter", 0, QApplication::UnicodeUTF8) )); } void QmitkDenoisingView::OnSelectionChanged( std::vector nodes ) { if (m_ThreadIsRunning) return; if (m_SelectedFilter != NOFILTERSELECTED) { m_Controls->m_InputImageLabel->setText("mandatory"); m_Controls->m_InputBrainMaskLabel->setText("mandatory"); } else { m_Controls->m_InputImageLabel->setText("mandatory"); } m_Controls->m_ApplyButton->setEnabled(false); m_ImageNode = NULL; m_BrainMaskNode = NULL; // iterate selection for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast(node->GetData())) { m_Controls->m_InputImageLabel->setText(node->GetName().c_str()); m_ImageNode = node; } bool isBinary = false; node->GetBoolProperty("binary", isBinary); // look for a brainmask in selection if( node.IsNotNull() && static_cast(node->GetData()) && isBinary) { m_Controls->m_InputBrainMaskLabel->setText(node->GetName().c_str()); m_BrainMaskNode = node; } } // Preparation of GUI to start denoising if a filter is selected if (m_ImageNode.IsNotNull() && m_BrainMaskNode.IsNotNull()) { if(m_SelectedFilter != NOFILTERSELECTED) { m_Controls->m_ApplyButton->setEnabled(true); } } else if (m_ImageNode.IsNotNull() && m_SelectedFilter == GAUSS) { m_Controls->m_ApplyButton->setEnabled(true); } } void QmitkDenoisingView::StartDenoising() { if (m_ImageNode.IsNotNull() && m_BrainMaskNode.IsNotNull() && m_SelectedFilter != GAUSS) { m_LastProgressCount = 0; switch (m_SelectedFilter) { case NOFILTERSELECTED: case GAUSS: { break; } case NLMR: { // initialize NLMr m_InputImage = dynamic_cast (m_ImageNode->GetData()); m_ImageMask = dynamic_cast(m_BrainMaskNode->GetData()); itk::Image::Pointer itkMask = itk::Image::New(); mitk::CastToItkImage(m_ImageMask, itkMask); m_NonLocalMeansFilter = NonLocalMeansDenoisingFilterType::New(); m_NonLocalMeansFilter->SetNumberOfThreads(12); m_NonLocalMeansFilter->SetInputImage(m_InputImage->GetVectorImage()); m_NonLocalMeansFilter->SetInputMask(itkMask); m_NonLocalMeansFilter->SetUseJointInformation(false); m_NonLocalMeansFilter->SetSearchRadius(m_Controls->m_SpinBoxParameter1->value()); m_NonLocalMeansFilter->SetComparisonRadius(m_Controls->m_SpinBoxParameter2->value()); // initialize the progressbar m_MaxProgressCount = m_InputImage->GetDimension(0) * m_InputImage->GetDimension(1) * m_InputImage->GetDimension(2); mitk::ProgressBar::GetInstance()->AddStepsToDo(m_MaxProgressCount); // start denoising in detached thread m_DenoisingThread.start(QThread::HighestPriority); break; } case NLMV: { // initialize NLMv m_InputImage = dynamic_cast (m_ImageNode->GetData()); m_ImageMask = dynamic_cast(m_BrainMaskNode->GetData()); itk::Image::Pointer itkMask = itk::Image::New(); mitk::CastToItkImage(m_ImageMask, itkMask); m_NonLocalMeansFilter = NonLocalMeansDenoisingFilterType::New(); m_NonLocalMeansFilter->SetNumberOfThreads(12); m_NonLocalMeansFilter->SetInputImage(m_InputImage->GetVectorImage()); m_NonLocalMeansFilter->SetInputMask(itkMask); m_NonLocalMeansFilter->SetUseJointInformation(true); m_NonLocalMeansFilter->SetSearchRadius(m_Controls->m_SpinBoxParameter1->value()); m_NonLocalMeansFilter->SetComparisonRadius(m_Controls->m_SpinBoxParameter2->value()); m_NonLocalMeansFilter->SetChannelRadius(m_Controls->m_SpinBoxParameter3->value()); // initialize the progressbar m_MaxProgressCount = m_InputImage->GetDimension(0) * m_InputImage->GetDimension(1) * m_InputImage->GetDimension(2); mitk::ProgressBar::GetInstance()->AddStepsToDo(m_MaxProgressCount); // start denoising in detached thread m_DenoisingThread.start(QThread::HighestPriority); break; } } } else if(m_SelectedFilter == GAUSS && m_ImageNode.IsNotNull()) { // initialize GAUSS m_InputImage = dynamic_cast (m_ImageNode->GetData()); ExtractFilterType::Pointer extractor = ExtractFilterType::New(); extractor->SetInput(m_InputImage->GetVectorImage()); ComposeFilterType::Pointer composer = ComposeFilterType::New(); for (unsigned int i = 0; i < m_InputImage->GetVectorImage()->GetVectorLength(); ++i) { extractor->SetIndex(i); extractor->Update(); m_GaussianFilter = GaussianFilterType::New(); m_GaussianFilter->SetInput(extractor->GetOutput()); m_GaussianFilter->SetVariance(m_Controls->m_SpinBoxParameter1->value()); m_GaussianFilter->Update(); composer->SetInput(i, m_GaussianFilter->GetOutput()); } composer->Update(); DiffusionImageType::Pointer image = DiffusionImageType::New(); image->SetVectorImage(composer->GetOutput()); image->SetReferenceBValue(m_InputImage->GetReferenceBValue()); image->SetDirections(m_InputImage->GetDirections()); image->InitializeFromVectorImage(); mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); imageNode->SetData( image ); QString name = m_ImageNode->GetName().c_str(); imageNode->SetName((name+"_gauss_"+QString::number(m_Controls->m_SpinBoxParameter1->value())).toStdString().c_str()); GetDefaultDataStorage()->Add(imageNode); } } void QmitkDenoisingView::ResetParameterPanel() { m_Controls->m_DwiLabel->setEnabled(false); m_Controls->m_InputImageLabel->setEnabled(false); m_Controls->m_BrainMaskLabel->hide(); m_Controls->m_InputBrainMaskLabel->hide(); m_Controls->m_ParameterBox->hide(); m_Controls->m_LabelParameter_1->hide(); m_Controls->m_LabelParameter_2->hide(); m_Controls->m_LabelParameter_3->hide(); m_Controls->m_SpinBoxParameter1->hide(); m_Controls->m_SpinBoxParameter2->hide(); m_Controls->m_SpinBoxParameter3->hide(); } void QmitkDenoisingView::SelectFilter(int filter) { if (m_ThreadIsRunning) return; //Prepare GUI this->ResetParameterPanel(); switch (filter) { case 0: { m_SelectedFilter = NOFILTERSELECTED; break; } case 1: { m_SelectedFilter = NLMR; m_Controls->m_DwiLabel->setEnabled(true); m_Controls->m_InputImageLabel->setEnabled(true); m_Controls->m_BrainMaskLabel->show(); m_Controls->m_InputBrainMaskLabel->show(); m_Controls->m_ParameterBox->show(); m_Controls->m_LabelParameter_1->show(); m_Controls->m_LabelParameter_1->setText("Search Radius:"); m_Controls->m_LabelParameter_2->show(); m_Controls->m_LabelParameter_2->setText("Comparision Radius:"); m_Controls->m_SpinBoxParameter1->show(); m_Controls->m_SpinBoxParameter1->setValue(1); m_Controls->m_SpinBoxParameter2->show(); m_Controls->m_SpinBoxParameter2->setValue(1); break; } case 2: { m_SelectedFilter = NLMV; m_Controls->m_DwiLabel->setEnabled(true); m_Controls->m_InputImageLabel->setEnabled(true); m_Controls->m_BrainMaskLabel->show(); m_Controls->m_InputBrainMaskLabel->show(); m_Controls->m_ParameterBox->show(); m_Controls->m_LabelParameter_1->show(); m_Controls->m_LabelParameter_1->setText("Search Radius:"); m_Controls->m_LabelParameter_2->show(); m_Controls->m_LabelParameter_2->setText("Comparision Radius:"); m_Controls->m_LabelParameter_3->show(); m_Controls->m_LabelParameter_3->setText("Number of neighboring gradients:"); m_Controls->m_SpinBoxParameter1->show(); m_Controls->m_SpinBoxParameter1->setValue(1); m_Controls->m_SpinBoxParameter2->show(); m_Controls->m_SpinBoxParameter2->setValue(1); m_Controls->m_SpinBoxParameter3->show(); m_Controls->m_SpinBoxParameter3->setValue(1); break; } case 3: { m_SelectedFilter = GAUSS; m_Controls->m_DwiLabel->setEnabled(true); m_Controls->m_InputImageLabel->setEnabled(true); m_Controls->m_ParameterBox->show(); m_Controls->m_LabelParameter_1->show(); m_Controls->m_LabelParameter_1->setText("Variance:"); m_Controls->m_SpinBoxParameter1->show(); m_Controls->m_SpinBoxParameter1->setValue(2); m_Controls->m_LabelParameter_2->hide(); m_Controls->m_SpinBoxParameter2->hide(); } } if (m_ImageNode.IsNull()) { if (m_SelectedFilter != NOFILTERSELECTED) m_Controls->m_InputImageLabel->setText("mandatory"); else m_Controls->m_InputImageLabel->setText("mandatory"); } if (m_ImageNode.IsNotNull()) { m_Controls->m_ApplyButton->setEnabled(false); switch(filter) { case NOFILTERSELECTED: { break; } case NLMR: case NLMV: { if (m_BrainMaskNode.IsNotNull()) m_Controls->m_ApplyButton->setEnabled(true); break; } case GAUSS: { m_Controls->m_ApplyButton->setEnabled(true); break; } } } } void QmitkDenoisingView::BeforeThread() { m_ThreadIsRunning = true; // initialize timer to update the progressbar at each timestep m_DenoisingTimer->start(500); m_Controls->m_LabelParameter_1->setEnabled(false); m_Controls->m_LabelParameter_2->setEnabled(false); m_Controls->m_LabelParameter_3->setEnabled(false); m_Controls->m_SpinBoxParameter1->setEnabled(false); m_Controls->m_SpinBoxParameter2->setEnabled(false); m_Controls->m_SpinBoxParameter3->setEnabled(false); m_Controls->m_SelectFilterComboBox->setEnabled(false); m_Controls->m_ApplyButton->setEnabled(false); } void QmitkDenoisingView::AfterThread() { m_ThreadIsRunning = false; // stop timer to stop updates of progressbar m_DenoisingTimer->stop(); // make sure progressbar is finished mitk::ProgressBar::GetInstance()->Progress(m_MaxProgressCount); - switch (m_SelectedFilter) + if (m_NoExceptionThrown) { - case NOFILTERSELECTED: - case GAUSS: + switch (m_SelectedFilter) { - break; - } + case NOFILTERSELECTED: + case GAUSS: + { + break; + } - case NLMR: - { - DiffusionImageType::Pointer image = DiffusionImageType::New(); - image->SetVectorImage(m_NonLocalMeansFilter->GetOutput()); - image->SetReferenceBValue(m_InputImage->GetReferenceBValue()); - image->SetDirections(m_InputImage->GetDirections()); - image->InitializeFromVectorImage(); - mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); - imageNode->SetData( image ); - QString name = m_ImageNode->GetName().c_str(); - - imageNode->SetName((name+"_NLMr_"+QString::number(m_Controls->m_SpinBoxParameter1->value())+"-"+QString::number(m_Controls->m_SpinBoxParameter2->value())).toStdString().c_str()); - GetDefaultDataStorage()->Add(imageNode); - break; - } + case NLMR: + { + DiffusionImageType::Pointer image = DiffusionImageType::New(); + image->SetVectorImage(m_NonLocalMeansFilter->GetOutput()); + image->SetReferenceBValue(m_InputImage->GetReferenceBValue()); + image->SetDirections(m_InputImage->GetDirections()); + image->InitializeFromVectorImage(); + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( image ); + QString name = m_ImageNode->GetName().c_str(); + + imageNode->SetName((name+"_NLMr_"+QString::number(m_Controls->m_SpinBoxParameter1->value())+"-"+QString::number(m_Controls->m_SpinBoxParameter2->value())).toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode); + break; + } - case NLMV: - { - DiffusionImageType::Pointer image = DiffusionImageType::New(); - image->SetVectorImage(m_NonLocalMeansFilter->GetOutput()); - image->SetReferenceBValue(m_InputImage->GetReferenceBValue()); - image->SetDirections(m_InputImage->GetDirections()); - image->InitializeFromVectorImage(); - mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); - imageNode->SetData( image ); - QString name = m_ImageNode->GetName().c_str(); - - imageNode->SetName((name+"_NLMv_"+QString::number(m_Controls->m_SpinBoxParameter1->value())+"-"+QString::number(m_Controls->m_SpinBoxParameter2->value())+"-"+QString::number(m_Controls->m_SpinBoxParameter3->value())).toStdString().c_str()); - GetDefaultDataStorage()->Add(imageNode); - - m_Controls->m_LabelParameter_3->setEnabled(true); - m_Controls->m_SpinBoxParameter3->setEnabled(true); - break; + case NLMV: + { + DiffusionImageType::Pointer image = DiffusionImageType::New(); + image->SetVectorImage(m_NonLocalMeansFilter->GetOutput()); + image->SetReferenceBValue(m_InputImage->GetReferenceBValue()); + image->SetDirections(m_InputImage->GetDirections()); + image->InitializeFromVectorImage(); + mitk::DataNode::Pointer imageNode = mitk::DataNode::New(); + imageNode->SetData( image ); + QString name = m_ImageNode->GetName().c_str(); + + imageNode->SetName((name+"_NLMv_"+QString::number(m_Controls->m_SpinBoxParameter1->value())+"-"+QString::number(m_Controls->m_SpinBoxParameter2->value())+"-"+QString::number(m_Controls->m_SpinBoxParameter3->value())).toStdString().c_str()); + GetDefaultDataStorage()->Add(imageNode); + + m_Controls->m_LabelParameter_3->setEnabled(true); + m_Controls->m_SpinBoxParameter3->setEnabled(true); + break; + } } } m_Controls->m_LabelParameter_1->setEnabled(true); m_Controls->m_LabelParameter_2->setEnabled(true); m_Controls->m_SpinBoxParameter1->setEnabled(true); m_Controls->m_SpinBoxParameter2->setEnabled(true); m_Controls->m_SelectFilterComboBox->setEnabled(true); m_Controls->m_ApplyButton->setEnabled(true); } void QmitkDenoisingView::UpdateProgress() { switch (m_SelectedFilter) { case NOFILTERSELECTED: case GAUSS: { break; } case NLMR: case NLMV: { unsigned int currentProgressCount = m_NonLocalMeansFilter->GetCurrentVoxelCount(); mitk::ProgressBar::GetInstance()->Progress(currentProgressCount-m_LastProgressCount); m_LastProgressCount = currentProgressCount; break; } } } diff --git a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDenoisingView.h b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDenoisingView.h index 75f2f9a478..d804268379 100644 --- a/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDenoisingView.h +++ b/Plugins/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkDenoisingView.h @@ -1,130 +1,131 @@ /*=================================================================== 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 _QMITKQmitkDenoisingView_H_INCLUDED #define _QMITKQmitkDenoisingView_H_INCLUDED #include #include #include "ui_QmitkDenoisingViewControls.h" #include #include #include #include #include #include #include #include #include class QmitkDenoisingView; class QmitkDenoisingWorker : public QObject { Q_OBJECT public: QmitkDenoisingWorker(QmitkDenoisingView* view); public slots: void run(); private: QmitkDenoisingView* m_View; }; /*! \brief View displaying details to denoise diffusionweighted images. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkDenoisingView : public QmitkFunctionality { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: static const std::string VIEW_ID; QmitkDenoisingView(); virtual ~QmitkDenoisingView(); /** Typedefs */ typedef short DiffusionPixelType; typedef mitk::DiffusionImage< DiffusionPixelType > DiffusionImageType; typedef mitk::Image MaskImageType; typedef itk::NonLocalMeansDenoisingFilter< DiffusionPixelType > NonLocalMeansDenoisingFilterType; typedef itk::DiscreteGaussianImageFilter < itk::Image< DiffusionPixelType, 3>, itk::Image< DiffusionPixelType, 3> > GaussianFilterType; typedef itk::VectorImageToImageFilter < DiffusionPixelType > ExtractFilterType; typedef itk::ComposeImageFilter < itk::Image > ComposeFilterType; virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Creation of the connections of the FilterComboBox virtual void Activated(); protected slots: void StartDenoising(); ///< prepares filter condition and starts thread for denoising void SelectFilter(int filter); ///< updates which filter is selected void BeforeThread(); ///< starts timer & disables all buttons while denoising void AfterThread(); ///< stops timer & creates a new datanode of the denoised image void UpdateProgress(); ///< updates the progressbar each timestep private: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); void ResetParameterPanel(); Ui::QmitkDenoisingViewControls* m_Controls; mitk::DataNode::Pointer m_ImageNode; mitk::DataNode::Pointer m_BrainMaskNode; QmitkDenoisingWorker m_DenoisingWorker; QThread m_DenoisingThread; bool m_ThreadIsRunning; + bool m_NoExceptionThrown; NonLocalMeansDenoisingFilterType::Pointer m_NonLocalMeansFilter; GaussianFilterType::Pointer m_GaussianFilter; DiffusionImageType::Pointer m_InputImage; MaskImageType::Pointer m_ImageMask; QTimer* m_DenoisingTimer; unsigned int m_LastProgressCount; unsigned int m_MaxProgressCount; enum FilterType { NOFILTERSELECTED, NLMR, NLMV, GAUSS }m_SelectedFilter; friend class QmitkDenoisingWorker; }; #endif // _QmitkDenoisingView_H_INCLUDED