diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.cpp b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.cpp index 2b1a874e7b..d5acaa8a1f 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.cpp +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/QmitkODFRenderWidget.cpp @@ -1,131 +1,131 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkODFRenderWidget.h" #include #include #include #include #include QmitkODFRenderWidget::QmitkODFRenderWidget(QWidget* parent, Qt::WindowFlags f): QWidget(parent, f) { //create Layouts QmitkODFRenderWidgetLayout = new QHBoxLayout( this ); //Set Layout to widget this->setLayout(QmitkODFRenderWidgetLayout); //Create RenderWindow m_RenderWindow = new QmitkRenderWindow(this, "odf render widget"); m_RenderWindow->setMaximumSize(300,300); m_RenderWindow->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); //m_RenderWindow->SetLayoutIndex( 3 ); QmitkODFRenderWidgetLayout->addWidget( m_RenderWindow ); } QmitkODFRenderWidget::~QmitkODFRenderWidget() { } void QmitkODFRenderWidget::GenerateODF( itk::OrientationDistributionFunction odf ) { m_Surface = mitk::Surface::New(); m_ds = mitk::StandaloneDataStorage::New(); m_Node = mitk::DataNode::New(); vtkPolyData* m_TemplateOdf = itk::OrientationDistributionFunction::GetBaseMesh(); vtkPolyData *polyData = vtkPolyData::New(); vtkPoints *points = vtkPoints::New(); vtkFloatArray *scalars = vtkFloatArray::New(); double max = -10000; double min = 10000; for (int i=0; imax) max = odf[i]; - if (std::abs(max)GetPoints()->GetPoint(i,p); double val = odf[i]; p[0] *= val; p[1] *= val; p[2] *= val; points->InsertPoint(i,p); // scalars->InsertTuple1(i, 1-val/max); scalars->InsertTuple1(i, 1-val/max); } polyData->SetPoints(points); vtkCellArray* polys = m_TemplateOdf->GetPolys(); polyData->SetPolys(polys); polyData->GetPointData()->SetScalars(scalars); polys->Delete(); scalars->Delete(); points->Delete(); m_Surface->SetVtkPolyData(polyData); m_Node->SetData(m_Surface); mitk::LookupTable::Pointer mitkLut = mitk::LookupTable::New(); vtkLookupTable* vtkLut = mitkLut->GetVtkLookupTable(); vtkLut->SetTableRange(0, 1); vtkLut->Build(); mitk::LookupTableProperty::Pointer mitkLutProp = mitk::LookupTableProperty::New(); mitkLutProp->SetLookupTable(mitkLut); m_Node->SetProperty( "LookupTable", mitkLutProp ); m_Node->SetProperty("scalar visibility", mitk::BoolProperty::New(true)); m_Node->SetProperty("color mode", mitk::BoolProperty::New(true)); m_Node->SetProperty("material.specularCoefficient", mitk::FloatProperty::New(0.5)); m_ds->Add(m_Node); m_RenderWindow->GetRenderer()->SetDataStorage( m_ds ); // adjust camera to current plane rotation mitk::Geometry2D::ConstPointer worldGeometry = mitk::GlobalInteraction::GetInstance()->GetFocus()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast( worldGeometry.GetPointer() ); mitk::Vector3D normal = worldPlaneGeometry->GetNormal(); mitk::Vector3D up = worldPlaneGeometry->GetAxisVector(1); normal.Normalize(); up.Normalize(); vtkSmartPointer cam = vtkSmartPointer::New(); const double camPos[3] = {normal[0],normal[1],normal[2]}; const double camUp[3] = {up[0],up[1],up[2]}; cam->SetPosition(camPos); cam->SetViewUp(camUp); cam->SetParallelProjection(1); m_RenderWindow->GetRenderer()->GetVtkRenderer()->SetActiveCamera(cam); } diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp index a7e2228919..51de7a71ee 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkControlVisualizationPropertiesView.cpp @@ -1,1651 +1,1643 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date: 2009-05-28 17:19:30 +0200 (Do, 28 Mai 2009) $ Version: $Revision: 17495 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "QmitkControlVisualizationPropertiesView.h" #include "mitkNodePredicateDataType.h" #include "mitkDataNodeObject.h" #include "mitkOdfNormalizationMethodProperty.h" #include "mitkOdfScaleByProperty.h" #include "mitkResliceMethodProperty.h" #include "mitkRenderingManager.h" #include "mitkTbssImage.h" #include "mitkPlanarFigure.h" -#include "mitkFiberBundle.h" +#include "mitkFiberBundleX.h" #include "QmitkDataStorageComboBox.h" #include "QmitkStdMultiWidget.h" #include "mitkFiberBundleInteractor.h" #include "mitkPlanarFigureInteractor.h" #include #include #include #include "mitkGlobalInteraction.h" #include "mitkGeometry2D.h" #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryISelectionService.h" #include "berryConstants.h" #include "berryPlatformUI.h" #include "itkRGBAPixel.h" -#include "itkTractsToProbabilityImageFilter.h" +#include #include "qwidgetaction.h" #include "qcolordialog.h" const std::string QmitkControlVisualizationPropertiesView::VIEW_ID = "org.mitk.views.controlvisualizationpropertiesview"; using namespace berry; struct CvpSelListener : ISelectionListener { berryObjectMacro(CvpSelListener); CvpSelListener(QmitkControlVisualizationPropertiesView* view) { m_View = view; } void ApplySettings(mitk::DataNode::Pointer node) { bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } int val; node->GetIntProperty("ShowMaxNumber", val); m_View->m_Controls->m_ShowMaxNumber->setValue(val); m_View->m_Controls->m_NormalizationDropdown->setCurrentIndex(dynamic_cast(node->GetProperty("Normalization"))->GetValueAsId()); float fval; node->GetFloatProperty("Scaling",fval); m_View->m_Controls->m_ScalingFactor->setValue(fval); m_View->m_Controls->m_AdditionalScaling->setCurrentIndex(dynamic_cast(node->GetProperty("ScaleBy"))->GetValueAsId()); node->GetFloatProperty("IndexParam1",fval); m_View->m_Controls->m_IndexParam1->setValue(fval); node->GetFloatProperty("IndexParam2",fval); m_View->m_Controls->m_IndexParam2->setValue(fval); } void DoSelectionChanged(ISelection::ConstPointer selection) { // save current selection in member variable m_View->m_CurrentSelection = selection.Cast(); m_View->m_Controls->m_VisibleOdfsON_T->setVisible(false); m_View->m_Controls->m_VisibleOdfsON_S->setVisible(false); m_View->m_Controls->m_VisibleOdfsON_C->setVisible(false); m_View->m_Controls->m_TextureIntON->setVisible(false); m_View->m_Controls->m_ImageControlsFrame->setVisible(false); m_View->m_Controls->m_PlanarFigureControlsFrame->setVisible(false); m_View->m_Controls->m_BundleControlsFrame->setVisible(false); m_View->m_SelectedNode = 0; if(m_View->m_CurrentSelection.IsNull()) return; if(m_View->m_CurrentSelection->Size() == 1) { mitk::DataNodeObject::Pointer nodeObj = m_View->m_CurrentSelection->Begin()->Cast(); if(nodeObj.IsNotNull()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); if(dynamic_cast(node->GetData()) != 0) { m_View->m_Controls->m_PlanarFigureControlsFrame->setVisible(true); m_View->m_SelectedNode = node; float val; node->GetFloatProperty("planarfigure.line.width", val); m_View->m_Controls->m_PFWidth->setValue((int)(val*10.0)); QString label = "Width %1"; label = label.arg(val); m_View->m_Controls->label_pfwidth->setText(label); float color[3]; node->GetColor( color, NULL, "planarfigure.default.line.color"); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color[0]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[1]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[2]*255.0)); styleSheet.append(")"); m_View->m_Controls->m_PFColor->setAutoFillBackground(true); m_View->m_Controls->m_PFColor->setStyleSheet(styleSheet); node->GetColor( color, NULL, "color"); styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color[0]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[1]*255.0)); styleSheet.append(","); styleSheet.append(QString::number(color[2]*255.0)); styleSheet.append(")"); m_View->PlanarFigureFocus(); } - if(dynamic_cast(node->GetData()) != 0) + if(dynamic_cast(node->GetData()) != 0) { m_View->m_Controls->m_BundleControlsFrame->setVisible(true); m_View->m_SelectedNode = node; if(m_View->m_CurrentPickingNode != 0 && node.GetPointer() != m_View->m_CurrentPickingNode) { m_View->m_Controls->m_Crosshair->setEnabled(false); } else { m_View->m_Controls->m_Crosshair->setEnabled(true); } float val; node->GetFloatProperty("TubeRadius", val); m_View->m_Controls->m_TubeRadius->setValue((int)(val * 100.0)); QString label = "Radius %1"; label = label.arg(val); m_View->m_Controls->label_tuberadius->setText(label); int width; node->GetIntProperty("LineWidth", width); m_View->m_Controls->m_LineWidth->setValue(width); label = "Width %1"; label = label.arg(width); m_View->m_Controls->label_linewidth->setText(label); float range; node->GetFloatProperty("Fiber2DSliceThickness",range); label = "Range %1"; label = label.arg(range*0.1); m_View->m_Controls->label_range->setText(label); // mitk::ColorProperty* nodecolor= mitk::ColorProperty::New(); // node->GetProperty(nodecolor,"color"); // m_View->m_Controls->m_Color->setAutoFillBackground(true); // QString styleSheet = "background-color:rgb("; // styleSheet.append(QString::number(nodecolor->GetColor().GetRed()*255.0)); // styleSheet.append(","); // styleSheet.append(QString::number(nodecolor->GetColor().GetGreen()*255.0)); // styleSheet.append(","); // styleSheet.append(QString::number(nodecolor->GetColor().GetBlue()*255.0)); // styleSheet.append(")"); // m_View->m_Controls->m_Color->setStyleSheet(styleSheet); } } } if(m_View->m_CurrentSelection->Size() > 0 && m_View->m_SelectedNode == 0) { m_View->m_Controls->m_ImageControlsFrame->setVisible(true); bool foundDiffusionImage = false; bool foundQBIVolume = false; bool foundTensorVolume = false; bool foundImage = false; bool foundMultipleOdfImages = false; bool foundRGBAImage = false; bool foundTbssImage = false; // do something with the selected items if(m_View->m_CurrentSelection) { // iterate selection for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); i != m_View->m_CurrentSelection->End(); ++i) { // extract datatree node if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); // only look at interesting types if(QString("DiffusionImage").compare(node->GetData()->GetNameOfClass())==0) { foundDiffusionImage = true; bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } int val; node->GetIntProperty("DisplayChannel", val); m_View->m_Controls->m_DisplayIndex->setValue(val); QString label = "Channel %1"; label = label.arg(val); m_View->m_Controls->label_channel->setText(label); int maxVal = (dynamic_cast* >(node->GetData()))->GetVectorImage()->GetVectorLength(); m_View->m_Controls->m_DisplayIndex->setMaximum(maxVal-1); } if(QString("TbssImage").compare(node->GetData()->GetNameOfClass())==0) { foundTbssImage = true; bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } int val; node->GetIntProperty("DisplayChannel", val); m_View->m_Controls->m_DisplayIndex->setValue(val); QString label = "Channel %1"; label = label.arg(val); m_View->m_Controls->label_channel->setText(label); int maxVal = (dynamic_cast(node->GetData()))->GetImage()->GetVectorLength(); m_View->m_Controls->m_DisplayIndex->setMaximum(maxVal-1); } else if(QString("QBallImage").compare(node->GetData()->GetNameOfClass())==0) { foundMultipleOdfImages = foundQBIVolume || foundTensorVolume; foundQBIVolume = true; ApplySettings(node); } else if(QString("TensorImage").compare(node->GetData()->GetNameOfClass())==0) { foundMultipleOdfImages = foundQBIVolume || foundTensorVolume; foundTensorVolume = true; ApplySettings(node); } else if(QString("Image").compare(node->GetData()->GetNameOfClass())==0) { foundImage = true; mitk::Image::Pointer img = dynamic_cast(node->GetData()); if(img.IsNotNull() && img->GetPixelType().GetItkTypeId() == &typeid(itk::RGBAPixel) ) { foundRGBAImage = true; } bool tex_int; node->GetBoolProperty("texture interpolation", tex_int); if(tex_int) { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexON); m_View->m_Controls->m_TextureIntON->setChecked(true); m_View->m_TexIsOn = true; } else { m_View->m_Controls->m_TextureIntON->setIcon(*m_View->m_IconTexOFF); m_View->m_Controls->m_TextureIntON->setChecked(false); m_View->m_TexIsOn = false; } } } } } m_View->m_FoundSingleOdfImage = (foundQBIVolume || foundTensorVolume) && !foundMultipleOdfImages; m_View->m_Controls->m_NumberGlyphsFrame->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_NormalizationDropdown->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->label->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_ScalingFactor->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_AdditionalScaling->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_NormalizationScalingFrame->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->OpacMinFrame->setVisible(foundRGBAImage || m_View->m_FoundSingleOdfImage); // changed for SPIE paper, Principle curvature scaling //m_View->m_Controls->params_frame->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->params_frame->setVisible(false); m_View->m_Controls->m_VisibleOdfsON_T->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_VisibleOdfsON_S->setVisible(m_View->m_FoundSingleOdfImage); m_View->m_Controls->m_VisibleOdfsON_C->setVisible(m_View->m_FoundSingleOdfImage); bool foundAnyImage = foundDiffusionImage || foundQBIVolume || foundTensorVolume || foundImage || foundTbssImage; m_View->m_Controls->m_Reinit->setVisible(foundAnyImage); m_View->m_Controls->m_TextureIntON->setVisible(foundAnyImage); m_View->m_Controls->m_TSMenu->setVisible(foundAnyImage); if(m_View->m_IsInitialized) { //m_View->GetSite()->GetWorkbenchWindow()->GetActivePage() // ->HideView(IViewPart::Pointer(m_View)); //berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage() // ->ShowView(QmitkControlVisualizationPropertiesView::VIEW_ID, // "", berry::IWorkbenchPage::VIEW_VISIBLE); } } } void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) { // check, if selection comes from datamanager if (part) { QString partname(part->GetPartName().c_str()); if(partname.compare("Datamanager")==0) { // apply selection DoSelectionChanged(selection); } } } QmitkControlVisualizationPropertiesView* m_View; }; QmitkControlVisualizationPropertiesView::QmitkControlVisualizationPropertiesView() : QmitkFunctionality(), m_Controls(NULL), m_MultiWidget(NULL), m_NodeUsedForOdfVisualization(NULL), m_IconTexOFF(new QIcon(":/QmitkDiffusionImaging/texIntOFFIcon.png")), m_IconTexON(new QIcon(":/QmitkDiffusionImaging/texIntONIcon.png")), m_IconGlyOFF_T(new QIcon(":/QmitkDiffusionImaging/glyphsoff_T.png")), m_IconGlyON_T(new QIcon(":/QmitkDiffusionImaging/glyphson_T.png")), m_IconGlyOFF_C(new QIcon(":/QmitkDiffusionImaging/glyphsoff_C.png")), m_IconGlyON_C(new QIcon(":/QmitkDiffusionImaging/glyphson_C.png")), m_IconGlyOFF_S(new QIcon(":/QmitkDiffusionImaging/glyphsoff_S.png")), m_IconGlyON_S(new QIcon(":/QmitkDiffusionImaging/glyphson_S.png")), m_CurrentSelection(0), m_CurrentPickingNode(0), m_GlyIsOn_S(false), m_GlyIsOn_C(false), m_GlyIsOn_T(false) { currentThickSlicesMode = 1; m_MyMenu = NULL; } QmitkControlVisualizationPropertiesView::QmitkControlVisualizationPropertiesView(const QmitkControlVisualizationPropertiesView& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } QmitkControlVisualizationPropertiesView::~QmitkControlVisualizationPropertiesView() { this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->RemovePostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); } void QmitkControlVisualizationPropertiesView::OnThickSlicesModeSelected( QAction* action ) { currentThickSlicesMode = action->data().toInt(); switch(currentThickSlicesMode) { default: case 1: this->m_Controls->m_TSMenu->setText("MIP"); break; case 2: this->m_Controls->m_TSMenu->setText("SUM"); break; case 3: this->m_Controls->m_TSMenu->setText("WEIGH"); break; } mitk::DataNode* n; n = GetDataStorage()->GetNamedNode("widget1Plane"); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = GetDataStorage()->GetNamedNode("widget2Plane"); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = GetDataStorage()->GetNamedNode("widget3Plane"); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow2()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow3()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer->GetRenderingManager()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::OnTSNumChanged(int num) { if(num==0) { mitk::DataNode* n; n = GetDataStorage()->GetNamedNode("widget1Plane"); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); n = GetDataStorage()->GetNamedNode("widget2Plane"); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); n = GetDataStorage()->GetNamedNode("widget3Plane"); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( 0 ) ); } else { mitk::DataNode* n; n = GetDataStorage()->GetNamedNode("widget1Plane"); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = GetDataStorage()->GetNamedNode("widget2Plane"); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = GetDataStorage()->GetNamedNode("widget3Plane"); if(n) n->SetProperty( "reslice.thickslices", mitk::ResliceMethodProperty::New( currentThickSlicesMode ) ); n = GetDataStorage()->GetNamedNode("widget1Plane"); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); n = GetDataStorage()->GetNamedNode("widget2Plane"); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); n = GetDataStorage()->GetNamedNode("widget3Plane"); if(n) n->SetProperty( "reslice.thickslices.num", mitk::IntProperty::New( num ) ); } m_TSLabel->setText(QString::number(num*2+1)); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow2()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer = this->GetActiveStdMultiWidget()->GetRenderWindow3()->GetRenderer(); if(renderer.IsNotNull()) { renderer->SendUpdateSlice(); } renderer->GetRenderingManager()->RequestUpdateAll(mitk::RenderingManager::REQUEST_UPDATE_2DWINDOWS); } void QmitkControlVisualizationPropertiesView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkControlVisualizationPropertiesViewControls; m_Controls->setupUi(parent); this->CreateConnections(); m_MyMenu = new QMenu(parent); connect( m_MyMenu, SIGNAL( aboutToShow() ), this, SLOT(OnMenuAboutToShow()) ); // button for changing rotation mode m_Controls->m_TSMenu->setMenu( m_MyMenu ); //m_CrosshairModeButton->setIcon( QIcon( iconCrosshairMode_xpm ) ); m_Controls->params_frame->setVisible(false); QIcon icon5(":/QmitkDiffusionImaging/Refresh_48.png"); m_Controls->m_Reinit->setIcon(icon5); m_Controls->m_Focus->setIcon(icon5); QIcon iconColor(":/QmitkDiffusionImaging/color24.gif"); m_Controls->m_PFColor->setIcon(iconColor); m_Controls->m_Color->setIcon(iconColor); QIcon iconReset(":/QmitkDiffusionImaging/reset.png"); m_Controls->m_ResetColoring->setIcon(iconReset); m_Controls->m_PFColor->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); QIcon iconCrosshair(":/QmitkDiffusionImaging/crosshair.png"); m_Controls->m_Crosshair->setIcon(iconCrosshair); // was is los QIcon iconPaint(":/QmitkDiffusionImaging/paint2.png"); m_Controls->m_TDI->setIcon(iconPaint); QIcon iconFiberFade(":/QmitkDiffusionImaging/MapperEfx2D.png"); m_Controls->m_FiberFading2D->setIcon(iconFiberFade); m_Controls->m_TextureIntON->setCheckable(true); #ifndef DIFFUSION_IMAGING_EXTENDED int size = m_Controls->m_AdditionalScaling->count(); for(int t=0; tm_AdditionalScaling->itemText(t).toStdString() == "Scale by ASR") { m_Controls->m_AdditionalScaling->removeItem(t); } } #endif m_Controls->m_OpacitySlider->setRange(0.0,1.0); m_Controls->m_OpacitySlider->setLowerValue(0.0); m_Controls->m_OpacitySlider->setUpperValue(0.0); m_Controls->m_ScalingFrame->setVisible(false); m_Controls->m_NormalizationFrame->setVisible(false); } m_IsInitialized = false; m_SelListener = berry::ISelectionListener::Pointer(new CvpSelListener(this)); this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); m_IsInitialized = true; } void QmitkControlVisualizationPropertiesView::OnMenuAboutToShow () { // THICK SLICE SUPPORT QMenu *myMenu = m_MyMenu; myMenu->clear(); QActionGroup* thickSlicesActionGroup = new QActionGroup(myMenu); thickSlicesActionGroup->setExclusive(true); mitk::BaseRenderer::Pointer renderer = this->GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer(); int currentTSMode = 0; { mitk::ResliceMethodProperty::Pointer m = dynamic_cast(renderer->GetCurrentWorldGeometry2DNode()->GetProperty( "reslice.thickslices" )); if( m.IsNotNull() ) currentTSMode = m->GetValueAsId(); } const int maxTS = 30; int currentNum = 0; { mitk::IntProperty::Pointer m = dynamic_cast(renderer->GetCurrentWorldGeometry2DNode()->GetProperty( "reslice.thickslices.num" )); if( m.IsNotNull() ) { currentNum = m->GetValue(); if(currentNum < 0) currentNum = 0; if(currentNum > maxTS) currentNum = maxTS; } } if(currentTSMode==0) currentNum=0; QSlider *m_TSSlider = new QSlider(myMenu); m_TSSlider->setMinimum(0); m_TSSlider->setMaximum(maxTS-1); m_TSSlider->setValue(currentNum); m_TSSlider->setOrientation(Qt::Horizontal); connect( m_TSSlider, SIGNAL( valueChanged(int) ), this, SLOT( OnTSNumChanged(int) ) ); QHBoxLayout* _TSLayout = new QHBoxLayout; _TSLayout->setContentsMargins(4,4,4,4); _TSLayout->addWidget(m_TSSlider); _TSLayout->addWidget(m_TSLabel=new QLabel(QString::number(currentNum*2+1),myMenu)); QWidget* _TSWidget = new QWidget; _TSWidget->setLayout(_TSLayout); QActionGroup* thickSliceModeActionGroup = new QActionGroup(myMenu); thickSliceModeActionGroup->setExclusive(true); QWidgetAction *m_TSSliderAction = new QWidgetAction(myMenu); m_TSSliderAction->setDefaultWidget(_TSWidget); myMenu->addAction(m_TSSliderAction); QAction* mipThickSlicesAction = new QAction(myMenu); mipThickSlicesAction->setActionGroup(thickSliceModeActionGroup); mipThickSlicesAction->setText("MIP (max. intensity proj.)"); mipThickSlicesAction->setCheckable(true); mipThickSlicesAction->setChecked(currentThickSlicesMode==1); mipThickSlicesAction->setData(1); myMenu->addAction( mipThickSlicesAction ); QAction* sumThickSlicesAction = new QAction(myMenu); sumThickSlicesAction->setActionGroup(thickSliceModeActionGroup); sumThickSlicesAction->setText("SUM (sum intensity proj.)"); sumThickSlicesAction->setCheckable(true); sumThickSlicesAction->setChecked(currentThickSlicesMode==2); sumThickSlicesAction->setData(2); myMenu->addAction( sumThickSlicesAction ); QAction* weightedThickSlicesAction = new QAction(myMenu); weightedThickSlicesAction->setActionGroup(thickSliceModeActionGroup); weightedThickSlicesAction->setText("WEIGHTED (gaussian proj.)"); weightedThickSlicesAction->setCheckable(true); weightedThickSlicesAction->setChecked(currentThickSlicesMode==3); weightedThickSlicesAction->setData(3); myMenu->addAction( weightedThickSlicesAction ); connect( thickSliceModeActionGroup, SIGNAL(triggered(QAction*)), this, SLOT(OnThickSlicesModeSelected(QAction*)) ); } void QmitkControlVisualizationPropertiesView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkControlVisualizationPropertiesView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } void QmitkControlVisualizationPropertiesView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->m_DisplayIndex), SIGNAL(valueChanged(int)), this, SLOT(DisplayIndexChanged(int)) ); connect( (QObject*)(m_Controls->m_TextureIntON), SIGNAL(clicked()), this, SLOT(TextIntON()) ); connect( (QObject*)(m_Controls->m_Reinit), SIGNAL(clicked()), this, SLOT(Reinit()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_T), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_T()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_S), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_S()) ); connect( (QObject*)(m_Controls->m_VisibleOdfsON_C), SIGNAL(clicked()), this, SLOT(VisibleOdfsON_C()) ); connect( (QObject*)(m_Controls->m_ShowMaxNumber), SIGNAL(editingFinished()), this, SLOT(ShowMaxNumberChanged()) ); connect( (QObject*)(m_Controls->m_NormalizationDropdown), SIGNAL(currentIndexChanged(int)), this, SLOT(NormalizationDropdownChanged(int)) ); connect( (QObject*)(m_Controls->m_ScalingFactor), SIGNAL(valueChanged(double)), this, SLOT(ScalingFactorChanged(double)) ); connect( (QObject*)(m_Controls->m_AdditionalScaling), SIGNAL(currentIndexChanged(int)), this, SLOT(AdditionalScaling(int)) ); connect( (QObject*)(m_Controls->m_IndexParam1), SIGNAL(valueChanged(double)), this, SLOT(IndexParam1Changed(double)) ); connect( (QObject*)(m_Controls->m_IndexParam2), SIGNAL(valueChanged(double)), this, SLOT(IndexParam2Changed(double)) ); connect( (QObject*)(m_Controls->m_ScalingCheckbox), SIGNAL(clicked()), this, SLOT(ScalingCheckbox()) ); connect( (QObject*)(m_Controls->m_OpacitySlider), SIGNAL(spanChanged(double,double)), this, SLOT(OpacityChanged(double,double)) ); connect((QObject*) m_Controls->m_Wire, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationWire())); connect((QObject*) m_Controls->m_Tube, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationTube())); connect((QObject*) m_Controls->m_Color, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationColor())); connect((QObject*) m_Controls->m_ResetColoring, SIGNAL(clicked()), (QObject*) this, SLOT(BundleRepresentationResetColoring())); connect((QObject*) m_Controls->m_Focus, SIGNAL(clicked()), (QObject*) this, SLOT(PlanarFigureFocus())); connect((QObject*) m_Controls->m_FiberFading2D, SIGNAL(clicked()), (QObject*) this, SLOT( Fiber2DfadingEFX() ) ); connect((QObject*) m_Controls->m_FiberThicknessSlider, SIGNAL(sliderReleased()), (QObject*) this, SLOT( FiberSlicingThickness2D() ) ); connect((QObject*) m_Controls->m_FiberThicknessSlider, SIGNAL(valueChanged(int)), (QObject*) this, SLOT( FiberSlicingUpdateLabel(int) )); connect((QObject*) m_Controls->m_Crosshair, SIGNAL(clicked()), (QObject*) this, SLOT(SetInteractor())); connect((QObject*) m_Controls->m_PFWidth, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(PFWidth(int))); connect((QObject*) m_Controls->m_PFColor, SIGNAL(clicked()), (QObject*) this, SLOT(PFColor())); connect((QObject*) m_Controls->m_TDI, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateTdi())); connect((QObject*) m_Controls->m_LineWidth, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(LineWidthChanged(int))); connect((QObject*) m_Controls->m_TubeRadius, SIGNAL(valueChanged(int)), (QObject*) this, SLOT(TubeRadiusChanged(int))); connect((QObject*) m_Controls->m_Welcome, SIGNAL(clicked()), (QObject*) this, SLOT(Welcome())); } } void QmitkControlVisualizationPropertiesView::Activated() { berry::ISelection::ConstPointer sel( this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); m_CurrentSelection = sel.Cast(); m_SelListener.Cast()->DoSelectionChanged(sel); QmitkFunctionality::Activated(); } void QmitkControlVisualizationPropertiesView::Deactivated() { QmitkFunctionality::Deactivated(); } int QmitkControlVisualizationPropertiesView::GetSizeFlags(bool width) { if(!width) { return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL; } else { return 0; } } int QmitkControlVisualizationPropertiesView::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { if(width==false) { return m_FoundSingleOdfImage ? 120 : 80; } else { return preferredResult; } } // set diffusion image channel to b0 volume void QmitkControlVisualizationPropertiesView::NodeAdded(const mitk::DataNode *node) { mitk::DataNode* notConst = const_cast(node); if (dynamic_cast*>(notConst->GetData())) { mitk::DiffusionImage::Pointer dimg = dynamic_cast*>(notConst->GetData()); notConst->SetIntProperty("DisplayChannel", dimg->GetB0Indices().front()); } } /* OnSelectionChanged is registered to SelectionService, therefore no need to implement SelectionService Listener explicitly */ void QmitkControlVisualizationPropertiesView::OnSelectionChanged( std::vector nodes ) { if ( !this->IsVisible() ) { // do nothing if nobody wants to see me :-( return; } // deactivate channel slider if no diffusion weighted image or tbss image is selected m_Controls->m_DisplayIndex->setVisible(false); m_Controls->label_channel->setVisible(false); for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if (node.IsNotNull() && (dynamic_cast(node->GetData()) || dynamic_cast*>(node->GetData()))) { m_Controls->m_DisplayIndex->setVisible(true); m_Controls->label_channel->setVisible(true); } } for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && (dynamic_cast(node->GetData()) || dynamic_cast(node->GetData())) ) { if(m_NodeUsedForOdfVisualization.IsNotNull()) { m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", false); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", false); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", false); } m_NodeUsedForOdfVisualization = node; m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", m_GlyIsOn_S); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", m_GlyIsOn_C); m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", m_GlyIsOn_T); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); m_Controls->m_TSMenu->setVisible(false); // deactivate mip etc. for tensor and q-ball images break; } else m_Controls->m_TSMenu->setVisible(true); } } mitk::DataStorage::SetOfObjects::Pointer QmitkControlVisualizationPropertiesView::ActiveSet(std::string classname) { if (m_CurrentSelection) { mitk::DataStorage::SetOfObjects::Pointer set = mitk::DataStorage::SetOfObjects::New(); int at = 0; for (IStructuredSelection::iterator i = m_CurrentSelection->Begin(); i != m_CurrentSelection->End(); ++i) { if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) { mitk::DataNode::Pointer node = nodeObj->GetDataNode(); if(QString(classname.c_str()).compare(node->GetData()->GetNameOfClass())==0) { set->InsertElement(at++, node); } } } return set; } return 0; } void QmitkControlVisualizationPropertiesView::SetBoolProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, bool value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetBoolProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetIntProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, int value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetIntProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetFloatProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, float value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetFloatProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetLevelWindowProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, mitk::LevelWindow value) { if(set.IsNotNull()) { mitk::LevelWindowProperty::Pointer prop = mitk::LevelWindowProperty::New(value); mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetProperty(name.c_str(), prop); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::SetEnumProp( mitk::DataStorage::SetOfObjects::Pointer set, std::string name, mitk::EnumerationProperty::Pointer value) { if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetProperty(name.c_str(), value); ++itemiter; } } } void QmitkControlVisualizationPropertiesView::DisplayIndexChanged(int dispIndex) { QString label = "Channel %1"; label = label.arg(dispIndex); m_Controls->label_channel->setText(label); std::vector sets; sets.push_back("DiffusionImage"); sets.push_back("TbssImage"); std::vector::iterator it = sets.begin(); while(it != sets.end()) { std::string s = *it; mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet(s); if(set.IsNotNull()) { mitk::DataStorage::SetOfObjects::const_iterator itemiter( set->begin() ); mitk::DataStorage::SetOfObjects::const_iterator itemiterend( set->end() ); while ( itemiter != itemiterend ) { (*itemiter)->SetIntProperty("DisplayChannel", dispIndex); ++itemiter; } //m_MultiWidget->RequestUpdate(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } it++; } } void QmitkControlVisualizationPropertiesView::Reinit() { if (m_CurrentSelection) { mitk::DataNodeObject::Pointer nodeObj = m_CurrentSelection->Begin()->Cast(); mitk::DataNode::Pointer node = nodeObj->GetDataNode(); mitk::BaseData::Pointer basedata = node->GetData(); if (basedata.IsNotNull()) { mitk::RenderingManager::GetInstance()->InitializeViews( basedata->GetTimeSlicedGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } void QmitkControlVisualizationPropertiesView::TextIntON() { if(m_TexIsOn) { m_Controls->m_TextureIntON->setIcon(*m_IconTexOFF); } else { m_Controls->m_TextureIntON->setIcon(*m_IconTexON); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("DiffusionImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("TensorImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("QBallImage"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); set = ActiveSet("Image"); SetBoolProp(set,"texture interpolation", !m_TexIsOn); m_TexIsOn = !m_TexIsOn; if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_S() { m_GlyIsOn_S = m_Controls->m_VisibleOdfsON_S->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_S", m_GlyIsOn_S); VisibleOdfsON(0); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_T() { m_GlyIsOn_T = m_Controls->m_VisibleOdfsON_T->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_T", m_GlyIsOn_T); VisibleOdfsON(1); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON_C() { m_GlyIsOn_C = m_Controls->m_VisibleOdfsON_C->isChecked(); if (m_NodeUsedForOdfVisualization.IsNull()) { MITK_WARN << "ODF visualization activated but m_NodeUsedForOdfVisualization is NULL"; return; } m_NodeUsedForOdfVisualization->SetBoolProperty("VisibleOdfs_C", m_GlyIsOn_C); VisibleOdfsON(2); } void QmitkControlVisualizationPropertiesView::VisibleOdfsON(int view) { if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::ShowMaxNumberChanged() { int maxNr = m_Controls->m_ShowMaxNumber->value(); if ( maxNr < 1 ) { m_Controls->m_ShowMaxNumber->setValue( 1 ); maxNr = 1; } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetIntProp(set,"ShowMaxNumber", maxNr); set = ActiveSet("TensorImage"); SetIntProp(set,"ShowMaxNumber", maxNr); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::NormalizationDropdownChanged(int normDropdown) { typedef mitk::OdfNormalizationMethodProperty PropType; PropType::Pointer normMeth = PropType::New(); switch(normDropdown) { case 0: normMeth->SetNormalizationToMinMax(); break; case 1: normMeth->SetNormalizationToMax(); break; case 2: normMeth->SetNormalizationToNone(); break; case 3: normMeth->SetNormalizationToGlobalMax(); break; default: normMeth->SetNormalizationToMinMax(); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetEnumProp(set,"Normalization", normMeth.GetPointer()); set = ActiveSet("TensorImage"); SetEnumProp(set,"Normalization", normMeth.GetPointer()); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::ScalingFactorChanged(double scalingFactor) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"Scaling", scalingFactor); set = ActiveSet("TensorImage"); SetFloatProp(set,"Scaling", scalingFactor); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::AdditionalScaling(int additionalScaling) { typedef mitk::OdfScaleByProperty PropType; PropType::Pointer scaleBy = PropType::New(); switch(additionalScaling) { case 0: scaleBy->SetScaleByNothing(); break; case 1: scaleBy->SetScaleByGFA(); //m_Controls->params_frame->setVisible(true); break; #ifdef DIFFUSION_IMAGING_EXTENDED case 2: scaleBy->SetScaleByPrincipalCurvature(); // commented in for SPIE paper, Principle curvature scaling //m_Controls->params_frame->setVisible(true); break; #endif default: scaleBy->SetScaleByNothing(); } mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetEnumProp(set,"ScaleBy", scaleBy.GetPointer()); set = ActiveSet("TensorImage"); SetEnumProp(set,"ScaleBy", scaleBy.GetPointer()); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::IndexParam1Changed(double param1) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"IndexParam1", param1); set = ActiveSet("TensorImage"); SetFloatProp(set,"IndexParam1", param1); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::IndexParam2Changed(double param2) { mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetFloatProp(set,"IndexParam2", param2); set = ActiveSet("TensorImage"); SetFloatProp(set,"IndexParam2", param2); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::OpacityChanged(double l, double u) { mitk::LevelWindow olw; olw.SetRangeMinMax(l*255, u*255); mitk::DataStorage::SetOfObjects::Pointer set = ActiveSet("QBallImage"); SetLevelWindowProp(set,"opaclevelwindow", olw); set = ActiveSet("TensorImage"); SetLevelWindowProp(set,"opaclevelwindow", olw); set = ActiveSet("Image"); SetLevelWindowProp(set,"opaclevelwindow", olw); m_Controls->m_OpacityMinFaLabel->setText(QString::number(l,'f',2) + " : " + QString::number(u,'f',2)); if(m_MultiWidget) m_MultiWidget->RequestUpdate(); } void QmitkControlVisualizationPropertiesView::ScalingCheckbox() { m_Controls->m_ScalingFrame->setVisible( m_Controls->m_ScalingCheckbox->isChecked()); if(!m_Controls->m_ScalingCheckbox->isChecked()) { m_Controls->m_AdditionalScaling->setCurrentIndex(0); m_Controls->m_ScalingFactor->setValue(1.0); } } void QmitkControlVisualizationPropertiesView::Fiber2DfadingEFX() { if (m_SelectedNode) { bool currentMode; m_SelectedNode->GetBoolProperty("Fiber2DfadeEFX", currentMode); m_SelectedNode->SetProperty("Fiber2DfadeEFX", mitk::BoolProperty::New(!currentMode)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::FiberSlicingThickness2D() { if (m_SelectedNode) { float fibThickness = m_Controls->m_FiberThicknessSlider->value() * 0.1; m_SelectedNode->SetProperty("Fiber2DSliceThickness", mitk::FloatProperty::New(fibThickness)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::FiberSlicingUpdateLabel(int value) { QString label = "Range %1"; label = label.arg(value * 0.1); m_Controls->label_range->setText(label); } void QmitkControlVisualizationPropertiesView::BundleRepresentationWire() { if(m_SelectedNode) { int width = m_Controls->m_LineWidth->value(); m_SelectedNode->SetProperty("LineWidth",mitk::IntProperty::New(width)); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(15)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(18)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(1)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(2)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(3)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(4)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::BundleRepresentationTube() { if(m_SelectedNode) { float radius = m_Controls->m_TubeRadius->value() / 100.0; m_SelectedNode->SetProperty("TubeRadius",mitk::FloatProperty::New(radius)); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(17)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(13)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(16)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::BundleRepresentationColor() { if(m_SelectedNode) { QColor color = QColorDialog::getColor(); if (!color.isValid()) return; m_Controls->m_Color->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_Controls->m_Color->setStyleSheet(styleSheet); m_SelectedNode->SetProperty("color",mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(14)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(3)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::BundleRepresentationResetColoring() { if(m_SelectedNode) { m_Controls->m_Color->setAutoFillBackground(true); QString styleSheet = "background-color:rgb(255,255,255)"; m_Controls->m_Color->setStyleSheet(styleSheet); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(4)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); m_SelectedNode->SetProperty("ColorCoding",mitk::IntProperty::New(0)); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } } void QmitkControlVisualizationPropertiesView::PlanarFigureFocus() { if(m_SelectedNode) { mitk::PlanarFigure* _PlanarFigure = 0; _PlanarFigure = dynamic_cast (m_SelectedNode->GetData()); if (_PlanarFigure) { QmitkRenderWindow* selectedRenderWindow = 0; bool PlanarFigureInitializedWindow = false; QmitkRenderWindow* RenderWindow1 = this->GetActiveStdMultiWidget()->GetRenderWindow1(); if (m_SelectedNode->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow1->GetRenderer())) { selectedRenderWindow = RenderWindow1; } QmitkRenderWindow* RenderWindow2 = this->GetActiveStdMultiWidget()->GetRenderWindow2(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow2->GetRenderer())) { selectedRenderWindow = RenderWindow2; } QmitkRenderWindow* RenderWindow3 = this->GetActiveStdMultiWidget()->GetRenderWindow3(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow3->GetRenderer())) { selectedRenderWindow = RenderWindow3; } QmitkRenderWindow* RenderWindow4 = this->GetActiveStdMultiWidget()->GetRenderWindow4(); if (!selectedRenderWindow && m_SelectedNode->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow4->GetRenderer())) { selectedRenderWindow = RenderWindow4; } const mitk::PlaneGeometry * _PlaneGeometry = dynamic_cast (_PlanarFigure->GetGeometry2D()); mitk::VnlVector normal = _PlaneGeometry->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry1 = RenderWindow1->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane1 = dynamic_cast( worldGeometry1.GetPointer() ); mitk::VnlVector normal1 = _Plane1->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry2 = RenderWindow2->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane2 = dynamic_cast( worldGeometry2.GetPointer() ); mitk::VnlVector normal2 = _Plane2->GetNormalVnl(); mitk::Geometry2D::ConstPointer worldGeometry3 = RenderWindow3->GetRenderer()->GetCurrentWorldGeometry2D(); mitk::PlaneGeometry::ConstPointer _Plane3 = dynamic_cast( worldGeometry3.GetPointer() ); mitk::VnlVector normal3 = _Plane3->GetNormalVnl(); normal[0] = fabs(normal[0]); normal[1] = fabs(normal[1]); normal[2] = fabs(normal[2]); normal1[0] = fabs(normal1[0]); normal1[1] = fabs(normal1[1]); normal1[2] = fabs(normal1[2]); normal2[0] = fabs(normal2[0]); normal2[1] = fabs(normal2[1]); normal2[2] = fabs(normal2[2]); normal3[0] = fabs(normal3[0]); normal3[1] = fabs(normal3[1]); normal3[2] = fabs(normal3[2]); double ang1 = angle(normal, normal1); double ang2 = angle(normal, normal2); double ang3 = angle(normal, normal3); if(ang1 < ang2 && ang1 < ang3) { selectedRenderWindow = RenderWindow1; } else { if(ang2 < ang3) { selectedRenderWindow = RenderWindow2; } else { selectedRenderWindow = RenderWindow3; } } // make node visible if (selectedRenderWindow) { mitk::Point3D centerP = _PlaneGeometry->GetOrigin(); selectedRenderWindow->GetSliceNavigationController()->ReorientSlices( centerP, _PlaneGeometry->GetNormal()); selectedRenderWindow->GetSliceNavigationController()->SelectSliceByPoint( centerP); } } // set interactor for new node (if not already set) mitk::PlanarFigureInteractor::Pointer figureInteractor = dynamic_cast(m_SelectedNode->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", m_SelectedNode); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); m_SelectedNode->SetProperty("planarfigure.iseditable",mitk::BoolProperty::New(true)); } } void QmitkControlVisualizationPropertiesView::SetInteractor() { typedef std::vector Container; Container _NodeSet = this->GetDataManagerSelection(); mitk::DataNode* node = 0; - mitk::FiberBundle* bundle = 0; + mitk::FiberBundleX* bundle = 0; mitk::FiberBundleInteractor::Pointer bundleInteractor = 0; // finally add all nodes to the model for(Container::const_iterator it=_NodeSet.begin(); it!=_NodeSet.end() ; it++) { node = const_cast(*it); - bundle = dynamic_cast(node->GetData()); + bundle = dynamic_cast(node->GetData()); if(bundle) { bundleInteractor = dynamic_cast(node->GetInteractor()); if(bundleInteractor.IsNotNull()) mitk::GlobalInteraction::GetInstance()->RemoveInteractor(bundleInteractor); if(!m_Controls->m_Crosshair->isChecked()) { m_Controls->m_Crosshair->setChecked(false); this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::ArrowCursor); m_CurrentPickingNode = 0; } else { m_Controls->m_Crosshair->setChecked(true); bundleInteractor = mitk::FiberBundleInteractor::New("FiberBundleInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(bundleInteractor); this->GetActiveStdMultiWidget()->GetRenderWindow4()->setCursor(Qt::CrossCursor); m_CurrentPickingNode = node; } } } } void QmitkControlVisualizationPropertiesView::PFWidth(int w) { double width = w/10.0; m_SelectedNode->SetProperty("planarfigure.line.width", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.outline.width", mitk::FloatProperty::New(width) ); m_SelectedNode->SetProperty("planarfigure.helperline.width", mitk::FloatProperty::New(width) ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); QString label = "Width %1"; label = label.arg(width); m_Controls->label_pfwidth->setText(label); } void QmitkControlVisualizationPropertiesView::PFColor() { QColor color = QColorDialog::getColor(); if (!color.isValid()) return; m_Controls->m_PFColor->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_Controls->m_PFColor->setStyleSheet(styleSheet); m_SelectedNode->SetProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.outline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.helperline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.markerline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.default.marker.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); m_SelectedNode->SetProperty( "planarfigure.hover.line.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "planarfigure.hover.outline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "planarfigure.hover.helperline.color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0) ); m_SelectedNode->SetProperty( "color", mitk::ColorProperty::New(color.red()/255.0, color.green()/255.0, color.blue()/255.0)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkControlVisualizationPropertiesView::GenerateTdi() { if(m_SelectedNode) { - mitk::FiberBundle* bundle = dynamic_cast(m_SelectedNode->GetData()); + mitk::FiberBundleX* bundle = dynamic_cast(m_SelectedNode->GetData()); if(!bundle) return; - /////////////////////////////// - // Generate unsigned char Image - typedef unsigned char OutPixType2; + typedef float OutPixType; + typedef itk::Image OutImageType; // run generator - typedef itk::Image< float, 3 > WMPImageType; - typedef itk::TractsToProbabilityImageFilter ImageGeneratorType2; - ImageGeneratorType2::Pointer generator = ImageGeneratorType2::New(); - //generator->SetInput(NULL); + itk::TractDensityImageFilter< OutImageType >::Pointer generator = itk::TractDensityImageFilter< OutImageType >::New(); generator->SetFiberBundle(bundle); - generator->SetInvertImage(false); generator->SetUpsamplingFactor(2); - generator->SetBinaryEnvelope(false); generator->Update(); // get result - typedef itk::Image OutType2; - OutType2::Pointer outImg = generator->GetOutput(); + OutImageType::Pointer outImg = generator->GetOutput(); - mitk::Image::Pointer img2 = mitk::Image::New(); - img2->InitializeByItk(outImg.GetPointer()); - img2->SetVolume(outImg->GetBufferPointer()); + mitk::Image::Pointer img = mitk::Image::New(); + img->InitializeByItk(outImg.GetPointer()); + img->SetVolume(outImg->GetBufferPointer()); // to datastorage mitk::DataNode::Pointer node = mitk::DataNode::New(); - node->SetData(img2); + node->SetData(img); QString name(m_SelectedNode->GetName().c_str()); name += "_TDI"; node->SetName(name.toStdString()); node->SetVisibility(true); GetDataStorage()->Add(node); } } void QmitkControlVisualizationPropertiesView::LineWidthChanged(int w) { QString label = "Width %1"; label = label.arg(w); m_Controls->label_linewidth->setText(label); BundleRepresentationWire(); } void QmitkControlVisualizationPropertiesView::TubeRadiusChanged(int r) { QString label = "Radius %1"; label = label.arg(r / 100.0); m_Controls->label_tuberadius->setText(label); this->BundleRepresentationTube(); } void QmitkControlVisualizationPropertiesView::Welcome() { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( GetSite()->GetWorkbenchWindow(), false); } diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.cpp b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.cpp index 61ce744238..118044c654 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.cpp +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.cpp @@ -1,1367 +1,1811 @@ /*========================================================================= - + Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ Version: $Revision: 21975 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ //=========FOR TESTING========== //random generation, number of points equal requested points // Blueberry application and interaction service #include #include // Qmitk #include "QmitkFiberBundleDeveloperView.h" #include // Qt #include // MITK +#include +#include +#include //===needed when timeSlicedGeometry is null to invoke rendering mechansims ==== #include #include // VTK #include //for randomized FiberStructure #include //for fiberStructure #include //for fiberStructure #include //for geometry //ITK #include //============================================== //======== W O R K E R S ____ S T A R T ======== //============================================== /*=================================================================================== * THIS METHOD IMPLEMENTS THE ACTIONS WHICH SHALL BE EXECUTED by the according THREAD * --generate FiberIDs--*/ + QmitkFiberIDWorker::QmitkFiberIDWorker(QThread* hostingThread, Package4WorkingThread itemPackage) -: m_itemPackage(itemPackage), -m_hostingThread(hostingThread) + : m_itemPackage(itemPackage), + m_hostingThread(hostingThread) { - + } void QmitkFiberIDWorker::run() { - if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) - m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); - - /* MEASUREMENTS AND FANCY GUI EFFECTS + if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) + m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); + + /* MEASUREMENTS AND FANCY GUI EFFECTS + * accurate time measurement using ITK timeProbe*/ + itk::TimeProbe clock; + clock.Start(); + //set GUI representation of timer to 0, is essential for correct timer incrementation + m_itemPackage.st_Controls->infoTimerGenerateFiberIds->setText(QString::number(0)); + m_itemPackage.st_FancyGUITimer1->start(); + + //do processing + m_itemPackage.st_FBX->DoGenerateFiberIds(); + + /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ + clock.Stop(); + m_itemPackage.st_FancyGUITimer1->stop(); + m_itemPackage.st_Controls->infoTimerGenerateFiberIds->setText( QString::number(clock.GetTotal()) ); + delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore + m_hostingThread->quit(); + +} + +/*=================================================================================== + * THIS METHOD IMPLEMENTS THE ACTIONS WHICH SHALL BE EXECUTED by the according THREAD + * -- extract fibers by given PlanarFigure --*/ +QmitkFiberExtractorWorker::QmitkFiberExtractorWorker(QThread* hostingThread, Package4WorkingThread itemPackage) + : m_itemPackage(itemPackage), + m_hostingThread(hostingThread) +{ + +} +void QmitkFiberExtractorWorker::run() +{ + if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) + m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); + + /* MEASUREMENTS AND FANCY GUI EFFECTS * accurate time measurement using ITK timeProbe*/ - itk::TimeProbe clock; - clock.Start(); - //set GUI representation of timer to 0, is essential for correct timer incrementation - m_itemPackage.st_Controls->infoTimerGenerateFiberIds->setText(QString::number(0)); - m_itemPackage.st_FancyGUITimer1->start(); - - //do processing - m_itemPackage.st_FBX->DoGenerateFiberIds(); - - /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ - clock.Stop(); - m_itemPackage.st_FancyGUITimer1->stop(); - m_itemPackage.st_Controls->infoTimerGenerateFiberIds->setText( QString::number(clock.GetTotal()) ); - delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore - m_hostingThread->quit(); - + itk::TimeProbe clock; + clock.Start(); + //set GUI representation of timer to 0, is essential for correct timer incrementation + m_itemPackage.st_Controls->infoTimerExtractFibers->setText(QString::number(0)); + m_itemPackage.st_FancyGUITimer1->start(); + + //do processing + std::vector fibIds = m_itemPackage.st_FBX->DoExtractFiberIds(m_itemPackage.st_PlanarFigure); + + //generate new fiberbundle by fiber iDs + vtkSmartPointer newFBPolyData = m_itemPackage.st_FBX->GenerateNewFiberBundleByIds(fibIds); + + // call function to convert fiberstructure into fiberbundleX and pass it to datastorage + (m_itemPackage.st_host->*m_itemPackage.st_pntr_to_Method_PutFibersToDataStorage)(newFBPolyData); + + + /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ + clock.Stop(); + m_itemPackage.st_FancyGUITimer1->stop(); + m_itemPackage.st_Controls->infoTimerExtractFibers->setText( QString::number(clock.GetTotal()) ); + delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore + m_hostingThread->quit(); + } /*=================================================================================== * THIS METHOD IMPLEMENTS THE ACTIONS WHICH SHALL BE EXECUTED by the according THREAD - * --do color coding--*/ + * --set FA values to fiberbundle--*/ QmitkFiberColoringWorker::QmitkFiberColoringWorker(QThread* hostingThread, Package4WorkingThread itemPackage) -: m_itemPackage(itemPackage) -, m_hostingThread(hostingThread) + : m_itemPackage(itemPackage) + , m_hostingThread(hostingThread) { - + } void QmitkFiberColoringWorker::run() { - if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) - m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); - - /* MEASUREMENTS AND FANCY GUI EFFECTS + if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) + m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); + + /* MEASUREMENTS AND FANCY GUI EFFECTS * accurate time measurement using ITK timeProbe*/ - itk::TimeProbe clock; - clock.Start(); - - //set GUI representation of timer to 0, is essential for correct timer incrementation - m_itemPackage.st_Controls->infoTimerColorCoding->setText(QString::number(0)); - m_itemPackage.st_FancyGUITimer1->start(); - - //do processing - m_itemPackage.st_FBX->DoColorCodingOrientationbased(); - - /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ - clock.Stop(); - m_itemPackage.st_FancyGUITimer1->stop(); - m_itemPackage.st_Controls->infoTimerColorCoding->setText( QString::number(clock.GetTotal()) ); - delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore - m_hostingThread->quit(); + itk::TimeProbe clock; + clock.Start(); + + //set GUI representation of timer to 0, is essential for correct timer incrementation + m_itemPackage.st_Controls->infoTimerColorCoding->setText(QString::number(0)); + m_itemPackage.st_FancyGUITimer1->start(); + + //do processing + if(m_itemPackage.st_Controls->radioButton_ColorOrient->isChecked()) { + m_itemPackage.st_FBX->DoColorCodingOrientationbased(); + + } else if(m_itemPackage.st_Controls->radioButton_ColorFA->isChecked()) { + m_itemPackage.st_FBX->DoColorCodingFAbased(); + + } else if(m_itemPackage.st_Controls->radioButton_OpacityFA->isChecked()) { + // m_itemPackage.st_FBX->SetColorCoding(""); + m_itemPackage.st_PassedDataNode->SetOpacity(0.999); + m_itemPackage.st_FBX->DoUseFAasColorOpacity(); + } else if(m_itemPackage.st_Controls->radioButton_ColorCustom->isChecked()){ + m_itemPackage.st_FBX->SetColorCoding(mitk::FiberBundleX::COLORCODING_CUSTOM); + } + + + /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ + clock.Stop(); + m_itemPackage.st_FancyGUITimer1->stop(); + m_itemPackage.st_Controls->infoTimerColorCoding->setText( QString::number(clock.GetTotal()) ); + delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore + m_hostingThread->quit(); } + +QmitkFiberFeederFAWorker::QmitkFiberFeederFAWorker(QThread* hostingThread, Package4WorkingThread itemPackage) + : m_itemPackage(itemPackage), + m_hostingThread(hostingThread) +{ + +} +void QmitkFiberFeederFAWorker::run() +{ + if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) + m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); + + /* MEASUREMENTS AND FANCY GUI EFFECTS + * accurate time measurement using ITK timeProbe */ + itk::TimeProbe clock; + clock.Start(); + //set GUI representation of timer to 0, is essential for correct timer incrementation + m_itemPackage.st_Controls->infoTimerSetFA->setText(QString::number(0)); + m_itemPackage.st_FancyGUITimer1->start(); + + //do processing + mitk::Image::Pointer FAImg = dynamic_cast(m_itemPackage.st_PassedDataNode->GetData()); + if(FAImg.IsNotNull()) + m_itemPackage.st_FBX->SetFAMap(FAImg); + + /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ + clock.Stop(); + m_itemPackage.st_FancyGUITimer1->stop(); + m_itemPackage.st_Controls->infoTimerSetFA->setText( QString::number(clock.GetTotal()) ); + + disconnect(m_itemPackage.st_FancyGUITimer1); + delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore + m_hostingThread->quit(); + +} + + /*=================================================================================== * THIS METHOD IMPLEMENTS THE ACTIONS WHICH SHALL BE EXECUTED by the according THREAD * --generate random fibers--*/ QmitkFiberGenerateRandomWorker::QmitkFiberGenerateRandomWorker(QThread* hostingThread, Package4WorkingThread itemPackage) -: m_itemPackage(itemPackage), -m_hostingThread(hostingThread) + : m_itemPackage(itemPackage), + m_hostingThread(hostingThread) { - + } void QmitkFiberGenerateRandomWorker::run() { - if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) - m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); - - /* MEASUREMENTS AND FANCY GUI EFFECTS */ - //MAKE SURE by yourself THAT NOTHING ELSE THAN A NUMBER IS SET IN THAT LABEL - m_itemPackage.st_Controls->infoTimerGenerateFiberBundle->setText(QString::number(0)); - m_itemPackage.st_FancyGUITimer1->start(); - - //do processing, generateRandomFibers - int numOfFibers = m_itemPackage.st_Controls->boxFiberNumbers->value(); - int distrRadius = m_itemPackage.st_Controls->boxDistributionRadius->value(); - int numOfPoints = numOfFibers * distrRadius; - - std::vector< std::vector > fiberStorage; - for (int i=0; i a; - fiberStorage.push_back( a ); - } - - /* Generate Point Cloud */ - vtkSmartPointer randomPoints = vtkSmartPointer::New(); - randomPoints->SetCenter(0.0, 0.0, 0.0); - randomPoints->SetNumberOfPoints(numOfPoints); - randomPoints->SetRadius(distrRadius); - randomPoints->Update(); - vtkPoints* pnts = randomPoints->GetOutput()->GetPoints(); - - /* ASSIGN EACH POINT TO A RANDOM FIBER */ - srand((unsigned)time(0)); // init randomizer - for (int i=0; iGetNumberOfPoints(); ++i) { - - //generate random number between 0 and numOfFibers-1 - int random_integer; - random_integer = (rand()%numOfFibers); - - //add current point to random fiber - fiberStorage.at(random_integer).push_back(i); - // MITK_INFO << "point" << i << " |" << pnts->GetPoint(random_integer)[0] << "|" << pnts->GetPoint(random_integer)[1]<< "|" << pnts->GetPoint(random_integer)[2] << "| into fiber" << random_integer; - } - - // initialize accurate time measurement - itk::TimeProbe clock; - clock.Start(); - - /* GENERATE VTK POLYLINES OUT OF FIBERSTORAGE */ - vtkSmartPointer linesCell = vtkSmartPointer::New(); // Host vtkPolyLines - linesCell->Allocate(pnts->GetNumberOfPoints()*2); //allocate for each cellindex also space for the pointId, e.g. [idx | pntID] - for (unsigned long i=0; i singleFiber = fiberStorage.at(i); - vtkSmartPointer fiber = vtkSmartPointer::New(); - fiber->GetPointIds()->SetNumberOfIds((int)singleFiber.size()); - - for (unsigned long si=0; siGetPointIds()->SetId( si, singleFiber.at(si) ); + if(m_itemPackage.st_Controls->checkBoxMonitorFiberThreads->isChecked()) + m_itemPackage.st_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_RUNNING); + + /* MEASUREMENTS AND FANCY GUI EFFECTS */ + //MAKE SURE by yourself THAT NOTHING ELSE THAN A NUMBER IS SET IN THAT LABEL + m_itemPackage.st_Controls->infoTimerGenerateFiberBundle->setText(QString::number(0)); + m_itemPackage.st_FancyGUITimer1->start(); + + //do processing, generateRandomFibers + int numOfFibers = m_itemPackage.st_Controls->boxFiberNumbers->value(); + int distrRadius = m_itemPackage.st_Controls->boxDistributionRadius->value(); + int numOfPoints = numOfFibers * distrRadius; + + std::vector< std::vector > fiberStorage; + for (int i=0; i a; + fiberStorage.push_back( a ); + } + + /* Generate Point Cloud */ + vtkSmartPointer randomPoints = vtkSmartPointer::New(); + randomPoints->SetCenter(0.0, 0.0, 0.0); + randomPoints->SetNumberOfPoints(numOfPoints); + randomPoints->SetRadius(distrRadius); + randomPoints->Update(); + vtkPoints* pnts = randomPoints->GetOutput()->GetPoints(); + + /* ASSIGN EACH POINT TO A RANDOM FIBER */ + srand((unsigned)time(0)); // init randomizer + for (int i=0; iGetNumberOfPoints(); ++i) { + + //generate random number between 0 and numOfFibers-1 + int random_integer; + random_integer = (rand()%numOfFibers); + + //add current point to random fiber + fiberStorage.at(random_integer).push_back(i); + // MITK_INFO << "point" << i << " |" << pnts->GetPoint(random_integer)[0] << "|" << pnts->GetPoint(random_integer)[1]<< "|" << pnts->GetPoint(random_integer)[2] << "| into fiber" << random_integer; + } + + // initialize accurate time measurement + itk::TimeProbe clock; + clock.Start(); + + /* GENERATE VTK POLYLINES OUT OF FIBERSTORAGE */ + vtkSmartPointer linesCell = vtkSmartPointer::New(); // Host vtkPolyLines + linesCell->Allocate(pnts->GetNumberOfPoints()*2); //allocate for each cellindex also space for the pointId, e.g. [idx | pntID] + for (long i=0; i singleFiber = fiberStorage.at(i); + vtkSmartPointer fiber = vtkSmartPointer::New(); + fiber->GetPointIds()->SetNumberOfIds((int)singleFiber.size()); + + for (long si=0; siGetPointIds()->SetId( si, singleFiber.at(si) ); + } + + linesCell->InsertNextCell(fiber); } - - linesCell->InsertNextCell(fiber); - } - - /* checkpoint for cellarray allocation */ - if ( (linesCell->GetSize()/pnts->GetNumberOfPoints()) != 2 ) //e.g. size: 12, number of points:6 .... each cell hosts point ids (6 ids) + cell index for each idPoint. 6 * 2 = 12 - { - MITK_INFO << "RANDOM FIBER ALLOCATION CAN NOT BE TRUSTED ANYMORE! Correct leak or remove command: linesCell->Allocate(pnts->GetNumberOfPoints()*2) but be aware of possible loss in performance."; - } - - /* HOSTING POLYDATA FOR RANDOM FIBERSTRUCTURE */ - vtkPolyData* PDRandom = vtkPolyData::New(); //no need to delete because data is needed in datastorage. - PDRandom->SetPoints(pnts); - PDRandom->SetLines(linesCell); - - // accurate timer measurement stop - clock.Stop(); - //MITK_INFO << "=====Assambling random Fibers to Polydata======\nMean: " << clock.GetMean() << " Total: " << clock.GetTotal() << std::endl; - - // call function to convert fiberstructure into fiberbundleX and pass it to datastorage - (m_itemPackage.st_host->*m_itemPackage.st_pntr_to_Method_PutFibersToDataStorage)(PDRandom); - - /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ - m_itemPackage.st_FancyGUITimer1->stop(); - m_itemPackage.st_Controls->infoTimerGenerateFiberBundle->setText( QString::number(clock.GetTotal()) ); - delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore - m_hostingThread->quit(); - + + /* checkpoint for cellarray allocation */ + if ( (linesCell->GetSize()/pnts->GetNumberOfPoints()) != 2 ) //e.g. size: 12, number of points:6 .... each cell hosts point ids (6 ids) + cell index for each idPoint. 6 * 2 = 12 + { + MITK_INFO << "RANDOM FIBER ALLOCATION CAN NOT BE TRUSTED ANYMORE! Correct leak or remove command: linesCell->Allocate(pnts->GetNumberOfPoints()*2) but be aware of possible loss in performance."; + } + + /* HOSTING POLYDATA FOR RANDOM FIBERSTRUCTURE */ + vtkSmartPointer PDRandom = vtkPolyData::New(); //could also be a standard pointer instead of smartpointer cuz ther is no need to delete because data is managed in datastorage. + PDRandom->SetPoints(pnts); + PDRandom->SetLines(linesCell); + + // accurate timer measurement stop + clock.Stop(); + //MITK_INFO << "=====Assambling random Fibers to Polydata======\nMean: " << clock.GetMean() << " Total: " << clock.GetTotal() << std::endl; + + // call function to convert fiberstructure into fiberbundleX and pass it to datastorage + (m_itemPackage.st_host->*m_itemPackage.st_pntr_to_Method_PutFibersToDataStorage)(PDRandom); + + /* MEASUREMENTS AND FANCY GUI EFFECTS CLEANUP */ + m_itemPackage.st_FancyGUITimer1->stop(); + m_itemPackage.st_Controls->infoTimerGenerateFiberBundle->setText( QString::number(clock.GetTotal()) ); + delete m_itemPackage.st_FancyGUITimer1; // fancy timer is not needed anymore + m_hostingThread->quit(); + } /*=================================================================================== * THIS METHOD IMPLEMENTS THE ACTIONS WHICH SHALL BE EXECUTED by the according THREAD * --update GUI elements of thread monitor-- * implementation not thread safe, not needed so far because * there exists only 1 thread for fiberprocessing * for threadsafety, you need to implement checking mechanisms in methods "::threadFor...." */ QmitkFiberThreadMonitorWorker::QmitkFiberThreadMonitorWorker( QThread* hostingThread, Package4WorkingThread itemPackage ) -: m_itemPackage(itemPackage) -, m_hostingThread(hostingThread) -, m_pixelstepper(10) //for next rendering call, move object 10px -, m_steppingDistance(220) //use only a multiple value of pixelstepper, x-axis border for fancy stuff -{ - - - //set timers - m_thtimer_initMonitor = new QTimer; - m_thtimer_initMonitor->setInterval(10); - - m_thtimer_initMonitorSetFinalPosition = new QTimer; - m_thtimer_initMonitorSetFinalPosition->setInterval(10); - - m_thtimer_initMonitorSetMasks = new QTimer; - m_thtimer_initMonitorSetFinalPosition->setInterval(10); - - - m_thtimer_threadStarted = new QTimer; - m_thtimer_threadStarted->setInterval(50); - - m_thtimer_threadFinished = new QTimer; - m_thtimer_threadFinished->setInterval(50); - - m_thtimer_threadTerminated = new QTimer; - m_thtimer_threadTerminated->setInterval(50); - - - - connect (m_thtimer_initMonitor, SIGNAL( timeout()), this, SLOT( fancyMonitorInitialization() ) ); - connect ( m_thtimer_initMonitorSetFinalPosition, SIGNAL( timeout() ), this, SLOT( fancyMonitorInitializationFinalPos() ) ); - connect ( m_thtimer_initMonitorSetMasks, SIGNAL( timeout() ), this, SLOT( fancyMonitorInitializationMask() ) ); - - connect (m_thtimer_threadStarted, SIGNAL( timeout()), this, SLOT( fancyTextFading_threadStarted() ) ); - connect (m_thtimer_threadFinished, SIGNAL( timeout()), this, SLOT( fancyTextFading_threadFinished() ) ); - connect (m_thtimer_threadTerminated, SIGNAL( timeout()), this, SLOT( fancyTextFading_threadTerminated() ) ); - - //first, the current text shall turn transparent - m_decreaseOpacity_threadStarted = true; - m_decreaseOpacity_threadFinished = true; - m_decreaseOpacity_threadTerminated = true; - - - - + : m_itemPackage(itemPackage) + , m_hostingThread(hostingThread) + , m_pixelstepper(10) //for next rendering call, move object 10px + , m_steppingDistance(220) //use only a multiple value of pixelstepper, x-axis border for fancy stuff +{ + + + //set timers + m_thtimer_initMonitor = new QTimer; + m_thtimer_initMonitor->setInterval(10); + + m_thtimer_initMonitorSetFinalPosition = new QTimer; + m_thtimer_initMonitorSetFinalPosition->setInterval(10); + + m_thtimer_initMonitorSetMasks = new QTimer; + m_thtimer_initMonitorSetFinalPosition->setInterval(10); + + + m_thtimer_threadStarted = new QTimer; + m_thtimer_threadStarted->setInterval(50); + + m_thtimer_threadFinished = new QTimer; + m_thtimer_threadFinished->setInterval(50); + + m_thtimer_threadTerminated = new QTimer; + m_thtimer_threadTerminated->setInterval(50); + + + + connect (m_thtimer_initMonitor, SIGNAL( timeout()), this, SLOT( fancyMonitorInitialization() ) ); + connect ( m_thtimer_initMonitorSetFinalPosition, SIGNAL( timeout() ), this, SLOT( fancyMonitorInitializationFinalPos() ) ); + connect ( m_thtimer_initMonitorSetMasks, SIGNAL( timeout() ), this, SLOT( fancyMonitorInitializationMask() ) ); + + connect (m_thtimer_threadStarted, SIGNAL( timeout()), this, SLOT( fancyTextFading_threadStarted() ) ); + connect (m_thtimer_threadFinished, SIGNAL( timeout()), this, SLOT( fancyTextFading_threadFinished() ) ); + connect (m_thtimer_threadTerminated, SIGNAL( timeout()), this, SLOT( fancyTextFading_threadTerminated() ) ); + + //first, the current text shall turn transparent + m_decreaseOpacity_threadStarted = true; + m_decreaseOpacity_threadFinished = true; + m_decreaseOpacity_threadTerminated = true; + + + + } void QmitkFiberThreadMonitorWorker::run() { - + } void QmitkFiberThreadMonitorWorker::initializeMonitor() { - //fancy configuration of animation start - mitk::Point2D pntOpen; - pntOpen[0] = 118; - pntOpen[1] = 10; - - mitk::Point2D headPos; - headPos[0] = 19; - headPos[1] = 10; - - mitk::Point2D statusPos; - statusPos[0] = 105; - statusPos[1] = 23; - - mitk::Point2D startedPos; - startedPos[0] = 68; - startedPos[1] = 10; - - mitk::Point2D finishedPos; - finishedPos[0] = 143; - finishedPos[1] = 10; - - mitk::Point2D terminatedPos; - terminatedPos[0] = 240; - terminatedPos[1] = 10; - - m_itemPackage.st_FBX_Monitor->setBracketClosePosition(pntOpen); - m_itemPackage.st_FBX_Monitor->setBracketOpenPosition(pntOpen); - m_itemPackage.st_FBX_Monitor->setHeadingPosition(headPos); - m_itemPackage.st_FBX_Monitor->setMaskPosition(headPos); - m_itemPackage.st_FBX_Monitor->setStatusPosition(statusPos); - m_itemPackage.st_FBX_Monitor->setStartedPosition(startedPos); - m_itemPackage.st_FBX_Monitor->setFinishedPosition(finishedPos); - m_itemPackage.st_FBX_Monitor->setTerminatedPosition(terminatedPos); - - - m_thtimer_initMonitor->start(); + //fancy configuration of animation start + mitk::Point2D pntOpen; + pntOpen[0] = 118; + pntOpen[1] = 10; + + mitk::Point2D headPos; + headPos[0] = 19; + headPos[1] = 10; + + mitk::Point2D statusPos; + statusPos[0] = 105; + statusPos[1] = 23; + + mitk::Point2D startedPos; + startedPos[0] = 68; + startedPos[1] = 10; + + mitk::Point2D finishedPos; + finishedPos[0] = 143; + finishedPos[1] = 10; + + mitk::Point2D terminatedPos; + terminatedPos[0] = 240; + terminatedPos[1] = 10; + + m_itemPackage.st_FBX_Monitor->setBracketClosePosition(pntOpen); + m_itemPackage.st_FBX_Monitor->setBracketOpenPosition(pntOpen); + m_itemPackage.st_FBX_Monitor->setHeadingPosition(headPos); + m_itemPackage.st_FBX_Monitor->setMaskPosition(headPos); + m_itemPackage.st_FBX_Monitor->setStatusPosition(statusPos); + m_itemPackage.st_FBX_Monitor->setStartedPosition(startedPos); + m_itemPackage.st_FBX_Monitor->setFinishedPosition(finishedPos); + m_itemPackage.st_FBX_Monitor->setTerminatedPosition(terminatedPos); + + + m_thtimer_initMonitor->start(); } void QmitkFiberThreadMonitorWorker::setThreadStatus(QString status) { - m_itemPackage.st_FBX_Monitor->setStatus(status); - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); + m_itemPackage.st_FBX_Monitor->setStatus(status); + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); } /* Methods to set status of running threads - * Following three methods are usually called - - before a thread starts and + * Following three methods are usually called + - before a thread starts and - a thread is finished or terminated */ void QmitkFiberThreadMonitorWorker::threadForFiberProcessingStarted() { - if(!m_thtimer_threadStarted->isActive()) { - m_thtimer_threadStarted->start(); - } else { - //fast change without fancy stuff, needed to keep threaddebugger info up to date - int counter = m_itemPackage.st_FBX_Monitor->getStarted(); - m_itemPackage.st_FBX_Monitor->setStarted(++counter); - - } - - + if(!m_thtimer_threadStarted->isActive()) { + m_thtimer_threadStarted->start(); + } else { + //fast change without fancy stuff, needed to keep threaddebugger info up to date + int counter = m_itemPackage.st_FBX_Monitor->getStarted(); + m_itemPackage.st_FBX_Monitor->setStarted(++counter); + + } + + } void QmitkFiberThreadMonitorWorker::threadForFiberProcessingFinished() { - if(!m_thtimer_threadFinished->isActive()) { - m_thtimer_threadFinished->start(); - } else { - //fast change without fancy stuff - int counter = m_itemPackage.st_FBX_Monitor->getFinished(); - m_itemPackage.st_FBX_Monitor->setFinished(++counter); - - } - + if(!m_thtimer_threadFinished->isActive()) { + m_thtimer_threadFinished->start(); + } else { + //fast change without fancy stuff + int counter = m_itemPackage.st_FBX_Monitor->getFinished(); + m_itemPackage.st_FBX_Monitor->setFinished(++counter); + + } + } void QmitkFiberThreadMonitorWorker::threadForFiberProcessingTerminated() { - if(!m_thtimer_threadTerminated->isActive()) { - m_thtimer_threadTerminated->start(); - } else { - //fast change without fancy stuff - int counter = m_itemPackage.st_FBX_Monitor->getTerminated(); - m_itemPackage.st_FBX_Monitor->setTerminated(++counter); - - } - + if(!m_thtimer_threadTerminated->isActive()) { + m_thtimer_threadTerminated->start(); + } else { + //fast change without fancy stuff + int counter = m_itemPackage.st_FBX_Monitor->getTerminated(); + m_itemPackage.st_FBX_Monitor->setTerminated(++counter); + + } + } /* Helper methods for fancy fading efx for thread monitor */ void QmitkFiberThreadMonitorWorker::fancyTextFading_threadStarted() { - - if (m_decreaseOpacity_threadStarted) { - int startedOpacity = m_itemPackage.st_FBX_Monitor->getStartedOpacity(); - m_itemPackage.st_FBX_Monitor->setStartedOpacity( --startedOpacity ); - - if (startedOpacity == 0) { - int counter = m_itemPackage.st_FBX_Monitor->getStarted(); - m_itemPackage.st_FBX_Monitor->setStarted(++counter); - m_decreaseOpacity_threadStarted = false; - } - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); - - } else { - - int startedOpacity = m_itemPackage.st_FBX_Monitor->getStartedOpacity(); - m_itemPackage.st_FBX_Monitor->setStartedOpacity( ++startedOpacity ); - - if (startedOpacity >= 10) { - m_thtimer_threadStarted->stop(); - m_decreaseOpacity_threadStarted = true; //set back to true, cuz next iteration shall decrease opacity as well + + if (m_decreaseOpacity_threadStarted) { + int startedOpacity = m_itemPackage.st_FBX_Monitor->getStartedOpacity(); + m_itemPackage.st_FBX_Monitor->setStartedOpacity( --startedOpacity ); + + if (startedOpacity == 0) { + int counter = m_itemPackage.st_FBX_Monitor->getStarted(); + m_itemPackage.st_FBX_Monitor->setStarted(++counter); + m_decreaseOpacity_threadStarted = false; + } + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); + + } else { + + int startedOpacity = m_itemPackage.st_FBX_Monitor->getStartedOpacity(); + m_itemPackage.st_FBX_Monitor->setStartedOpacity( ++startedOpacity ); + + if (startedOpacity >= 10) { + m_thtimer_threadStarted->stop(); + m_decreaseOpacity_threadStarted = true; //set back to true, cuz next iteration shall decrease opacity as well + } + + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); + } - - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); - } - - + } void QmitkFiberThreadMonitorWorker::fancyTextFading_threadFinished() { - if (m_decreaseOpacity_threadFinished) { - int finishedOpacity = m_itemPackage.st_FBX_Monitor->getFinishedOpacity(); - m_itemPackage.st_FBX_Monitor->setFinishedOpacity( --finishedOpacity ); - - if (finishedOpacity == 0) { - int counter = m_itemPackage.st_FBX_Monitor->getFinished(); - m_itemPackage.st_FBX_Monitor->setFinished(++counter); - m_decreaseOpacity_threadFinished = false; - } - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); - - } else { - - int finishedOpacity = m_itemPackage.st_FBX_Monitor->getFinishedOpacity(); - m_itemPackage.st_FBX_Monitor->setFinishedOpacity( ++finishedOpacity ); - - if (finishedOpacity >= 10) { - m_thtimer_threadFinished->stop(); - m_decreaseOpacity_threadFinished = true; //set back to true, cuz next iteration shall decrease opacity as well + if (m_decreaseOpacity_threadFinished) { + int finishedOpacity = m_itemPackage.st_FBX_Monitor->getFinishedOpacity(); + m_itemPackage.st_FBX_Monitor->setFinishedOpacity( --finishedOpacity ); + + if (finishedOpacity == 0) { + int counter = m_itemPackage.st_FBX_Monitor->getFinished(); + m_itemPackage.st_FBX_Monitor->setFinished(++counter); + m_decreaseOpacity_threadFinished = false; + } + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); + + } else { + + int finishedOpacity = m_itemPackage.st_FBX_Monitor->getFinishedOpacity(); + m_itemPackage.st_FBX_Monitor->setFinishedOpacity( ++finishedOpacity ); + + if (finishedOpacity >= 10) { + m_thtimer_threadFinished->stop(); + m_decreaseOpacity_threadFinished = true; //set back to true, cuz next iteration shall decrease opacity as well + } + + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); + } - - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); - - } } void QmitkFiberThreadMonitorWorker::fancyTextFading_threadTerminated() { - if (m_decreaseOpacity_threadTerminated) { - int terminatedOpacity = m_itemPackage.st_FBX_Monitor->getTerminatedOpacity(); - m_itemPackage.st_FBX_Monitor->setTerminatedOpacity( --terminatedOpacity ); - - if (terminatedOpacity == 0) { - int counter = m_itemPackage.st_FBX_Monitor->getTerminated(); - m_itemPackage.st_FBX_Monitor->setTerminated(++counter); - m_decreaseOpacity_threadTerminated = false; - } - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); - - } else { - - int terminatedOpacity = m_itemPackage.st_FBX_Monitor->getTerminatedOpacity(); - m_itemPackage.st_FBX_Monitor->setTerminatedOpacity( ++terminatedOpacity ); - - if (terminatedOpacity >= 10) { - m_thtimer_threadTerminated->stop(); - m_decreaseOpacity_threadTerminated = true; //set back to true, cuz next iteration shall decrease opacity as well + if (m_decreaseOpacity_threadTerminated) { + int terminatedOpacity = m_itemPackage.st_FBX_Monitor->getTerminatedOpacity(); + m_itemPackage.st_FBX_Monitor->setTerminatedOpacity( --terminatedOpacity ); + + if (terminatedOpacity == 0) { + int counter = m_itemPackage.st_FBX_Monitor->getTerminated(); + m_itemPackage.st_FBX_Monitor->setTerminated(++counter); + m_decreaseOpacity_threadTerminated = false; + } + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); + + } else { + + int terminatedOpacity = m_itemPackage.st_FBX_Monitor->getTerminatedOpacity(); + m_itemPackage.st_FBX_Monitor->setTerminatedOpacity( ++terminatedOpacity ); + + if (terminatedOpacity >= 10) { + m_thtimer_threadTerminated->stop(); + m_decreaseOpacity_threadTerminated = true; //set back to true, cuz next iteration shall decrease opacity as well + } + + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); + } - - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); - - } - - + + } void QmitkFiberThreadMonitorWorker::fancyMonitorInitialization() { - - mitk::Point2D pntClose = m_itemPackage.st_FBX_Monitor->getBracketClosePosition(); //possible bottleneck, set pntClose to member - mitk::Point2D pntOpen = m_itemPackage.st_FBX_Monitor->getBracketOpenPosition(); //possible bottleneck, set pntClose to member - - pntClose[0] += m_pixelstepper; - pntOpen[0] -= m_pixelstepper; - //MITK_INFO << pntClose[0] << " " << pntOpen[0]; - - m_itemPackage.st_FBX_Monitor->setBracketClosePosition(pntClose); - m_itemPackage.st_FBX_Monitor->setBracketOpenPosition(pntOpen); - - int opacity = m_itemPackage.st_FBX_Monitor->getHeadingOpacity() + 1; - if (opacity > 10) - opacity = 10; - m_itemPackage.st_FBX_Monitor->setHeadingOpacity(opacity); - - - if (pntClose[0] >= m_steppingDistance) - { - if (m_itemPackage.st_FBX_Monitor->getHeadingOpacity() != 10 ) + + mitk::Point2D pntClose = m_itemPackage.st_FBX_Monitor->getBracketClosePosition(); //possible bottleneck, set pntClose to member + mitk::Point2D pntOpen = m_itemPackage.st_FBX_Monitor->getBracketOpenPosition(); //possible bottleneck, set pntClose to member + + pntClose[0] += m_pixelstepper; + pntOpen[0] -= m_pixelstepper; + //MITK_INFO << pntClose[0] << " " << pntOpen[0]; + + m_itemPackage.st_FBX_Monitor->setBracketClosePosition(pntClose); + m_itemPackage.st_FBX_Monitor->setBracketOpenPosition(pntOpen); + + int opacity = m_itemPackage.st_FBX_Monitor->getHeadingOpacity() + 1; + if (opacity > 10) + opacity = 10; + m_itemPackage.st_FBX_Monitor->setHeadingOpacity(opacity); + + + if (pntClose[0] >= m_steppingDistance) { - m_itemPackage.st_FBX_Monitor->setHeadingOpacity(10); - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); + if (m_itemPackage.st_FBX_Monitor->getHeadingOpacity() != 10 ) + { + m_itemPackage.st_FBX_Monitor->setHeadingOpacity(10); + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); + } + + m_thtimer_initMonitor->stop(); + + //position them to obt y=25 + m_thtimer_initMonitorSetFinalPosition->start(); } - - m_thtimer_initMonitor->stop(); - - //position them to obt y=25 - m_thtimer_initMonitorSetFinalPosition->start(); - } - - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); - - + + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); + + } void QmitkFiberThreadMonitorWorker::fancyMonitorInitializationFinalPos() { - //get y pos of - mitk::Point2D pntClose = m_itemPackage.st_FBX_Monitor->getBracketClosePosition(); - mitk::Point2D pntOpen = m_itemPackage.st_FBX_Monitor->getBracketOpenPosition(); - mitk::Point2D pntHead = m_itemPackage.st_FBX_Monitor->getHeadingPosition(); - - pntClose[1] += 5; - pntOpen[1] += 5; - pntHead[1] += 5; - - m_itemPackage.st_FBX_Monitor->setBracketClosePosition(pntClose); - m_itemPackage.st_FBX_Monitor->setBracketOpenPosition(pntOpen); - m_itemPackage.st_FBX_Monitor->setHeadingPosition(pntHead); - - - if (pntClose[1] >= 35) { //35 = y position - m_thtimer_initMonitorSetFinalPosition->stop(); - //now init mask of labels - m_thtimer_initMonitorSetMasks->start(); - } - - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); - + //get y pos of + mitk::Point2D pntClose = m_itemPackage.st_FBX_Monitor->getBracketClosePosition(); + mitk::Point2D pntOpen = m_itemPackage.st_FBX_Monitor->getBracketOpenPosition(); + mitk::Point2D pntHead = m_itemPackage.st_FBX_Monitor->getHeadingPosition(); + + pntClose[1] += 5; + pntOpen[1] += 5; + pntHead[1] += 5; + + m_itemPackage.st_FBX_Monitor->setBracketClosePosition(pntClose); + m_itemPackage.st_FBX_Monitor->setBracketOpenPosition(pntOpen); + m_itemPackage.st_FBX_Monitor->setHeadingPosition(pntHead); + + + if (pntClose[1] >= 35) { //35 = y position + m_thtimer_initMonitorSetFinalPosition->stop(); + //now init mask of labels + m_thtimer_initMonitorSetMasks->start(); + } + + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); + } void QmitkFiberThreadMonitorWorker::fancyMonitorInitializationMask() { - //increase opacity - int opacity = m_itemPackage.st_FBX_Monitor->getMaskOpacity(); - opacity++; - m_itemPackage.st_FBX_Monitor->setMaskOpacity(opacity); - m_itemPackage.st_FBX_Monitor->setStartedOpacity(opacity); - m_itemPackage.st_FBX_Monitor->setFinishedOpacity(opacity); - m_itemPackage.st_FBX_Monitor->setTerminatedOpacity(opacity); - m_itemPackage.st_FBX_Monitor->setStatusOpacity(opacity); - - if (opacity >=10) { - m_thtimer_initMonitorSetMasks->stop(); - } - - m_itemPackage.st_ThreadMonitorDataNode->Modified(); - m_itemPackage.st_MultiWidget->RequestUpdate(); - + //increase opacity + int opacity = m_itemPackage.st_FBX_Monitor->getMaskOpacity(); + opacity++; + m_itemPackage.st_FBX_Monitor->setMaskOpacity(opacity); + m_itemPackage.st_FBX_Monitor->setStartedOpacity(opacity); + m_itemPackage.st_FBX_Monitor->setFinishedOpacity(opacity); + m_itemPackage.st_FBX_Monitor->setTerminatedOpacity(opacity); + m_itemPackage.st_FBX_Monitor->setStatusOpacity(opacity); + + if (opacity >=10) { + m_thtimer_initMonitorSetMasks->stop(); + } + + m_itemPackage.st_ThreadMonitorDataNode->Modified(); + m_itemPackage.st_MultiWidget->RequestUpdate(); + } + //============================================== //======== W O R K E R S ________ E N D ======== //============================================== +//========#########################===============###########################=====================######################### +//========#########################===============###########################=====================######################### +//========#########################===============###########################=====================######################### +//========#########################===============###########################=====================######################### +//========#########################===============###########################=====================######################### +// HERE STARTS THE ACTUAL FIBERBUNDLE DEVELOPER VIEW IMPLEMENTATION +//========#########################===============###########################=====================######################### +//========#########################===============###########################=====================######################### +//========#########################===============###########################=====================######################### +//========#########################===============###########################=====================######################### -// ========= HERE STARTS THE ACTUAL FIBERB2UNDLE DEVELOPER VIEW IMPLEMENTATION ====== const std::string QmitkFiberBundleDeveloperView::VIEW_ID = "org.mitk.views.fiberbundledeveloper"; const std::string id_DataManager = "org.mitk.views.datamanager"; using namespace berry; QmitkFiberBundleDeveloperView::QmitkFiberBundleDeveloperView() -: QmitkFunctionality() -, m_Controls( 0 ) -, m_MultiWidget( NULL ) -, m_FiberIDGenerator( NULL) -, m_GeneratorFibersRandom( NULL ) -, m_fiberMonitorIsOn( false ) + : QmitkFunctionality() + , m_Controls( 0 ) + , m_MultiWidget( NULL ) + , m_FiberIDGenerator( NULL) + , m_GeneratorFibersRandom( NULL ) + , m_FiberFeederFASlave( NULL ) + , m_FiberColoringSlave(NULL) + , m_FiberExtractor(NULL) + , m_fiberMonitorIsOn( false ) + , m_CircleCounter( 0 ) + , m_suppressSignal(false) { - m_hostThread = new QThread; - m_threadInProgress = false; - + m_hostThread = new QThread; + m_threadInProgress = false; + } // Destructor QmitkFiberBundleDeveloperView::~QmitkFiberBundleDeveloperView() { - //m_FiberBundleX->Delete(); using weakPointer, therefore no delete necessary - delete m_hostThread; - if (m_FiberIDGenerator != NULL) - delete m_FiberIDGenerator; - - if (m_GeneratorFibersRandom != NULL) - delete m_GeneratorFibersRandom; - + //m_FiberBundleX->Delete(); using weakPointer, therefore no delete necessary + delete m_hostThread; } void QmitkFiberBundleDeveloperView::CreateQtPartControl( QWidget *parent ) { - // build up qt view, unless already done in QtDesigner, etc. - if ( !m_Controls ) - { - // create GUI widgets from the Qt Designer's .ui file - m_Controls = new Ui::QmitkFiberBundleDeveloperViewControls; - m_Controls->setupUi( parent ); - - /*=========INITIALIZE BUTTON CONFIGURATION ================*/ - m_Controls->radioButton_directionX->setEnabled(false); - m_Controls->radioButton_directionY->setEnabled(false); - m_Controls->radioButton_directionZ->setEnabled(false); - m_Controls->buttonGenerateFiberIds->setEnabled(false); - m_Controls->buttonGenerateFibers->setEnabled(true); - m_Controls->buttonColorFibers->setEnabled(false); - - m_Controls->buttonSMFibers->setEnabled(false);//not yet implemented - m_Controls->buttonVtkDecimatePro->setEnabled(false);//not yet implemented - m_Controls->buttonVtkSmoothPD->setEnabled(false);//not yet implemented - m_Controls->buttonGenerateTubes->setEnabled(false);//not yet implemented - - - connect( m_Controls->buttonGenerateFibers, SIGNAL(clicked()), this, SLOT(DoGenerateFibers()) ); - connect( m_Controls->buttonGenerateFiberIds, SIGNAL(pressed()), this, SLOT(DoGenerateFiberIDs()) ); - - connect( m_Controls->radioButton_directionRandom, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); - connect( m_Controls->radioButton_directionX, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); - connect( m_Controls->radioButton_directionY, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); - connect( m_Controls->radioButton_directionZ, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); - connect( m_Controls->toolBox, SIGNAL(currentChanged ( int ) ), this, SLOT(SelectionChangedToolBox(int)) ); - connect( m_Controls->tabWidget, SIGNAL(currentChanged ( int ) ), this, SLOT(SelectionChangedToolBox(int)) ); //needed to update GUI elements when tab selection of fiberProcessing page changes - - connect( m_Controls->buttonColorFibers, SIGNAL(clicked()), this, SLOT(DoColorFibers()) ); - - connect( m_Controls->checkBoxMonitorFiberThreads, SIGNAL(stateChanged(int)), this, SLOT(DoMonitorFiberThreads(int)) ); - - - } - - // Checkpoint for fiber ORIENTATION - if ( m_DirectionRadios.empty() ) - { - m_DirectionRadios.insert(0, m_Controls->radioButton_directionRandom); - m_DirectionRadios.insert(1, m_Controls->radioButton_directionX); - m_DirectionRadios.insert(2, m_Controls->radioButton_directionY); - m_DirectionRadios.insert(3, m_Controls->radioButton_directionZ); - } - - // set GUI elements of FiberGenerator to according configuration - DoUpdateGenerateFibersWidget(); - - + // build up qt view, unless already done in QtDesigner, etc. + if ( !m_Controls ) + { + // create GUI widgets from the Qt Designer's .ui file + m_Controls = new Ui::QmitkFiberBundleDeveloperViewControls; + m_Controls->setupUi( parent ); + + /*=========INITIALIZE BUTTON CONFIGURATION ================*/ + m_Controls->radioButton_directionX->setEnabled(false); + m_Controls->radioButton_directionY->setEnabled(false); + m_Controls->radioButton_directionZ->setEnabled(false); + m_Controls->buttonGenerateFiberIds->setEnabled(false); + m_Controls->buttonGenerateFibers->setEnabled(true); + m_Controls->buttonColorFibers->setEnabled(false); + m_Controls->ddAvailableColorcodings->setEnabled(false); + m_Controls->buttonExtractFibers->setEnabled(false); + m_Controls->button_FAMap->setEnabled(true); + + m_Controls->buttonSMFibers->setEnabled(false);//not yet implemented + m_Controls->buttonVtkDecimatePro->setEnabled(false);//not yet implemented + m_Controls->buttonVtkSmoothPD->setEnabled(false);//not yet implemented + m_Controls->buttonGenerateTubes->setEnabled(false);//not yet implemented + + + connect( m_Controls->buttonGenerateFibers, SIGNAL(clicked()), this, SLOT(DoGenerateFibers()) ); + connect( m_Controls->buttonGenerateFiberIds, SIGNAL(clicked()), this, SLOT(DoGenerateFiberIDs()) ); + connect( m_Controls->button_FAMapExecute, SIGNAL(clicked()), this, SLOT(DoSetFAValues()) ); + connect( m_Controls->button_FAMap, SIGNAL(clicked()), this, SLOT(DoSetFAMap()) ); + connect( m_Controls->buttonExtractFibers, SIGNAL(clicked()), this, SLOT(DoExtractFibers()) ); + connect( m_Controls->radioButton_directionRandom, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); + connect( m_Controls->radioButton_directionX, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); + connect( m_Controls->radioButton_directionY, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); + connect( m_Controls->radioButton_directionZ, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) ); + connect( m_Controls->toolBox, SIGNAL(currentChanged ( int ) ), this, SLOT(SelectionChangedToolBox(int)) ); + + + connect( m_Controls->m_CircleButton, SIGNAL( clicked() ), this, SLOT( ActionDrawEllipseTriggered() ) ); + connect( m_Controls->buttonColorFibers, SIGNAL(clicked()), this, SLOT(DoColorFibers()) ); + // connect( m_Controls->ddAvailableColorcodings, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCurrentColorCoding(int) )); + connect( m_Controls->ddAvailableColorcodings, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCurrentColorCoding(int) )); + + connect( m_Controls->checkBoxMonitorFiberThreads, SIGNAL(stateChanged(int)), this, SLOT(DoMonitorFiberThreads(int)) ); + + + + } + + // Checkpoint for fiber ORIENTATION + if ( m_DirectionRadios.empty() ) + { + m_DirectionRadios.insert(0, m_Controls->radioButton_directionRandom); + m_DirectionRadios.insert(1, m_Controls->radioButton_directionX); + m_DirectionRadios.insert(2, m_Controls->radioButton_directionY); + m_DirectionRadios.insert(3, m_Controls->radioButton_directionZ); + } + + // set GUI elements of FiberGenerator to according configuration + DoUpdateGenerateFibersWidget(); + + } /* THIS METHOD UPDATES ALL GUI ELEMENTS OF QGroupBox DEPENDING ON CURRENTLY SELECTED - * RADIO BUTTONS + * RADIO BUTTONS */ void QmitkFiberBundleDeveloperView::DoUpdateGenerateFibersWidget() { - //get selected radioButton - QString fibDirection; //stores the object_name of selected radiobutton - QVector::const_iterator i; - for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) - { - QRadioButton* rdbtn = *i; - if (rdbtn->isChecked()) - fibDirection = rdbtn->objectName(); - } - - if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) { - // disable radiobuttons - if (m_Controls->boxFiberMinLength->isEnabled()) - m_Controls->boxFiberMinLength->setEnabled(false); - - if (m_Controls->labelFiberMinLength->isEnabled()) - m_Controls->labelFiberMinLength->setEnabled(false); - - if (m_Controls->boxFiberMaxLength->isEnabled()) - m_Controls->boxFiberMaxLength->setEnabled(false); - - if (m_Controls->labelFiberMaxLength->isEnabled()) - m_Controls->labelFiberMaxLength->setEnabled(false); - - //enable radiobuttons - if (!m_Controls->labelFibersTotal->isEnabled()) - m_Controls->labelFibersTotal->setEnabled(true); - - if (!m_Controls->boxFiberNumbers->isEnabled()) - m_Controls->boxFiberNumbers->setEnabled(true); - - if (!m_Controls->labelDistrRadius->isEnabled()) - m_Controls->labelDistrRadius->setEnabled(true); - - if (!m_Controls->boxDistributionRadius->isEnabled()) - m_Controls->boxDistributionRadius->setEnabled(true); - - - } else { - // disable radiobuttons - if (m_Controls->labelDistrRadius->isEnabled()) - m_Controls->labelDistrRadius->setEnabled(false); - - if (m_Controls->boxDistributionRadius->isEnabled()) - m_Controls->boxDistributionRadius->setEnabled(false); - - - //enable radiobuttons - if (!m_Controls->labelFibersTotal->isEnabled()) - m_Controls->labelFibersTotal->setEnabled(true); - - if (!m_Controls->boxFiberNumbers->isEnabled()) - m_Controls->boxFiberNumbers->setEnabled(true); - - if (!m_Controls->boxFiberMinLength->isEnabled()) - m_Controls->boxFiberMinLength->setEnabled(true); - - if (!m_Controls->labelFiberMinLength->isEnabled()) - m_Controls->labelFiberMinLength->setEnabled(true); - - if (!m_Controls->boxFiberMaxLength->isEnabled()) - m_Controls->boxFiberMaxLength->setEnabled(true); - - if (!m_Controls->labelFiberMaxLength->isEnabled()) - m_Controls->labelFiberMaxLength->setEnabled(true); - - } - + //get selected radioButton + QString fibDirection; //stores the object_name of selected radiobutton + QVector::const_iterator i; + for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) + { + QRadioButton* rdbtn = *i; + if (rdbtn->isChecked()) + fibDirection = rdbtn->objectName(); + } + + if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) { + // disable radiobuttons + if (m_Controls->boxFiberMinLength->isEnabled()) + m_Controls->boxFiberMinLength->setEnabled(false); + + if (m_Controls->labelFiberMinLength->isEnabled()) + m_Controls->labelFiberMinLength->setEnabled(false); + + if (m_Controls->boxFiberMaxLength->isEnabled()) + m_Controls->boxFiberMaxLength->setEnabled(false); + + if (m_Controls->labelFiberMaxLength->isEnabled()) + m_Controls->labelFiberMaxLength->setEnabled(false); + + //enable radiobuttons + if (!m_Controls->labelFibersTotal->isEnabled()) + m_Controls->labelFibersTotal->setEnabled(true); + + if (!m_Controls->boxFiberNumbers->isEnabled()) + m_Controls->boxFiberNumbers->setEnabled(true); + + if (!m_Controls->labelDistrRadius->isEnabled()) + m_Controls->labelDistrRadius->setEnabled(true); + + if (!m_Controls->boxDistributionRadius->isEnabled()) + m_Controls->boxDistributionRadius->setEnabled(true); + + + } else { + // disable radiobuttons + if (m_Controls->labelDistrRadius->isEnabled()) + m_Controls->labelDistrRadius->setEnabled(false); + + if (m_Controls->boxDistributionRadius->isEnabled()) + m_Controls->boxDistributionRadius->setEnabled(false); + + + //enable radiobuttons + if (!m_Controls->labelFibersTotal->isEnabled()) + m_Controls->labelFibersTotal->setEnabled(true); + + if (!m_Controls->boxFiberNumbers->isEnabled()) + m_Controls->boxFiberNumbers->setEnabled(true); + + if (!m_Controls->boxFiberMinLength->isEnabled()) + m_Controls->boxFiberMinLength->setEnabled(true); + + if (!m_Controls->labelFiberMinLength->isEnabled()) + m_Controls->labelFiberMinLength->setEnabled(true); + + if (!m_Controls->boxFiberMaxLength->isEnabled()) + m_Controls->boxFiberMaxLength->setEnabled(true); + + if (!m_Controls->labelFiberMaxLength->isEnabled()) + m_Controls->labelFiberMaxLength->setEnabled(true); + + } + } void QmitkFiberBundleDeveloperView::DoGenerateFibers() { - - // GET SELECTED FIBER DIRECTION - QString fibDirection; //stores the object_name of selected radiobutton - QVector::const_iterator i; - for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) - { - QRadioButton* rdbtn = *i; - if (rdbtn->isChecked()) - fibDirection = rdbtn->objectName(); - } - - // vtkPolyData* output; // FiberPD stores the generated PolyData... going to be generated in thread - if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) { - // build polydata with random lines and fibers - // output = - GenerateVtkFibersRandom(); - - } else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_X ) { - // build polydata with XDirection fibers - //output = GenerateVtkFibersDirectionX(); - - } else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Y ) { - // build polydata with YDirection fibers - // output = GenerateVtkFibersDirectionY(); - - } else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Z ) { - // build polydata with ZDirection fibers - // output = GenerateVtkFibersDirectionZ(); - - } - - + + // GET SELECTED FIBER DIRECTION + QString fibDirection; //stores the object_name of selected radiobutton + QVector::const_iterator i; + for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) + { + QRadioButton* rdbtn = *i; + if (rdbtn->isChecked()) + fibDirection = rdbtn->objectName(); + } + + // vtkPolyData* output; // FiberPD stores the generated PolyData... going to be generated in thread + if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) { + // build polydata with random lines and fibers + // output = + GenerateVtkFibersRandom(); + + } else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_X ) { + // build polydata with XDirection fibers + //output = GenerateVtkFibersDirectionX(); + + } else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Y ) { + // build polydata with YDirection fibers + // output = GenerateVtkFibersDirectionY(); + + } else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Z ) { + // build polydata with ZDirection fibers + // output = GenerateVtkFibersDirectionZ(); + + } + + } -void QmitkFiberBundleDeveloperView::PutFibersToDataStorage( vtkPolyData* threadOutput) -{ - - MITK_INFO << "lines: " << threadOutput->GetNumberOfLines() << "pnts: " << threadOutput->GetNumberOfPoints(); - //qthread mutex lock - mitk::FiberBundleX::Pointer FB = mitk::FiberBundleX::New(threadOutput); -// FB->SetFiberPolyData(); -// FB->SetGeometry(this->GenerateStandardGeometryForMITK()); - - mitk::DataNode::Pointer FBNode; - FBNode = mitk::DataNode::New(); - FBNode->SetName("FiberBundleX"); - FBNode->SetData(FB); - FBNode->SetVisibility(true); - - GetDataStorage()->Add(FBNode); - //output->Delete(); - - const mitk::PlaneGeometry * tsgeo = m_MultiWidget->GetTimeNavigationController()->GetCurrentPlaneGeometry(); - if (tsgeo == NULL) { - /* GetDataStorage()->Modified etc. have no effect, therefore proceed as followed below */ - // get all nodes that have not set "includeInBoundingBox" to false - mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" - , mitk::BoolProperty::New(false))); - mitk::DataStorage::SetOfObjects::ConstPointer rs = GetDataStorage()->GetSubset(pred); - // calculate bounding geometry of these nodes - mitk::TimeSlicedGeometry::Pointer bounds = GetDataStorage()->ComputeBoundingGeometry3D(rs); - // initialize the views to the bounding geometry - mitk::RenderingManager::GetInstance()->InitializeViews(bounds); - } else { - - GetDataStorage()->Modified(); - m_MultiWidget->RequestUpdate(); //necessary?? - } - - //qthread mutex unlock +void QmitkFiberBundleDeveloperView::DoExtractFibers() +{ + + /* ===== TIMER CONFIGURATIONS for visual effect ====== + * start and stop is called in Thread */ + QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough + localTimer->setInterval( 10 ); + connect( localTimer, SIGNAL(timeout()), this, SLOT( UpdateExtractFibersTimer()) ); + + struct Package4WorkingThread ItemPackageForExtractor; + ItemPackageForExtractor.st_FBX = m_FiberBundleX; + ItemPackageForExtractor.st_Controls = m_Controls; + ItemPackageForExtractor.st_FancyGUITimer1 = localTimer; + ItemPackageForExtractor.st_host = this; //needed to access method "PutFibersToDataStorage()" + ItemPackageForExtractor.st_pntr_to_Method_PutFibersToDataStorage = &QmitkFiberBundleDeveloperView::PutFibersToDataStorage; //actual functor calling method putFibersToDataStorage + ItemPackageForExtractor.st_PlanarFigure = m_PlanarFigure; + + //set element for thread monitoring + if (m_fiberMonitorIsOn) + ItemPackageForExtractor.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; + + + if (m_threadInProgress) + return; //maybe popup window saying, working thread still in progress...pls wait + + m_FiberExtractor = new QmitkFiberExtractorWorker(m_hostThread, ItemPackageForExtractor); + m_FiberExtractor->moveToThread(m_hostThread); + + //connections + connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_FiberExtraction() )); + connect(m_hostThread, SIGNAL(started()), m_FiberExtractor, SLOT( run() )); + connect(m_hostThread, SIGNAL(finished()), this, SLOT( AfterThread_FiberExtraction() )); + connect(m_hostThread, SIGNAL(terminated()), this, SLOT( AfterThread_FiberExtraction() )); + + m_hostThread->start(QThread::HighestPriority) ; +} + +void QmitkFiberBundleDeveloperView::UpdateExtractFibersTimer() +{ + // Make sure that thread has set according info-label to number! here we do not check if value is numeric! shall be done in beforeThreadstarted() + QString crntValue = m_Controls->infoTimerExtractFibers->text(); + int tmpVal = crntValue.toInt(); + m_Controls->infoTimerExtractFibers->setText(QString::number(++tmpVal)); + m_Controls->infoTimerExtractFibers->update(); +} + +void QmitkFiberBundleDeveloperView::BeforeThread_FiberExtraction() +{ + m_threadInProgress = true; + if (m_fiberMonitorIsOn){ + m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); + //m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_STARTED); + } +} + +void QmitkFiberBundleDeveloperView::AfterThread_FiberExtraction() +{ + m_threadInProgress = false; + if (m_fiberMonitorIsOn){ + m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); + m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); + } + // disconnect(m_hostThread, 0, 0, 0); + m_hostThread->disconnect(); + + // m_FiberExtractor->disconnect(); + delete m_FiberExtractor; + + m_FiberBundleNode->Modified(); + m_MultiWidget->RequestUpdate(); + +} + +void QmitkFiberBundleDeveloperView::PutFibersToDataStorage( vtkSmartPointer threadOutput) +{ + + MITK_INFO << "lines: " << threadOutput->GetNumberOfLines() << "pnts: " << threadOutput->GetNumberOfPoints(); + //qthread mutex lock + mitk::FiberBundleX::Pointer FB = mitk::FiberBundleX::New(threadOutput); + mitk::DataNode::Pointer FBNode; + FBNode = mitk::DataNode::New(); + FBNode->SetName("FiberBundleX"); + FBNode->SetData(FB); + FBNode->SetVisibility(true); + FBNode->SetOpacity(1.0); + + GetDataStorage()->Add(FBNode); + FBNode->Modified(); + + const mitk::PlaneGeometry * tsgeo = m_MultiWidget->GetTimeNavigationController()->GetCurrentPlaneGeometry(); + if (tsgeo == NULL) { + /* GetDataStorage()->Modified etc. have no effect, therefore proceed as followed below */ + // get all nodes that have not set "includeInBoundingBox" to false + mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox" + , mitk::BoolProperty::New(false))); + mitk::DataStorage::SetOfObjects::ConstPointer rs = GetDataStorage()->GetSubset(pred); + // calculate bounding geometry of these nodes + mitk::TimeSlicedGeometry::Pointer bounds = GetDataStorage()->ComputeBoundingGeometry3D(rs); + // initialize the views to the bounding geometry + mitk::RenderingManager::GetInstance()->InitializeViews(bounds); + + } else { + + GetDataStorage()->Modified(); + m_MultiWidget->RequestUpdate(); //necessary?? + } + + //qthread mutex unlock +} + +void QmitkFiberBundleDeveloperView::PutFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name) +{ + mitk::DataNode::Pointer newNode = mitk::DataNode::New(); + newNode->SetName(name.toStdString()); + newNode->SetData(figure); + + + + std::vector selectedNodes = GetDataManagerSelection(); + for(unsigned int i = 0; i < selectedNodes.size(); i++) + { + selectedNodes[i]->SetSelected(false); + } + + newNode->SetSelected(true); + + newNode->AddProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(1.0,0.0,0.0)); + newNode->AddProperty( "planarfigure.line.width", mitk::FloatProperty::New(2.0)); + newNode->AddProperty( "planarfigure.drawshadow", mitk::BoolProperty::New(true)); + + newNode->AddProperty( "selected", mitk::BoolProperty::New(true) ); + newNode->AddProperty( "planarfigure.ishovering", mitk::BoolProperty::New(true) ); + newNode->AddProperty( "planarfigure.drawoutline", mitk::BoolProperty::New(true) ); + newNode->AddProperty( "planarfigure.drawquantities", mitk::BoolProperty::New(false) ); + newNode->AddProperty( "planarfigure.drawshadow", mitk::BoolProperty::New(true) ); + + newNode->AddProperty( "planarfigure.line.width", mitk::FloatProperty::New(3.0) ); + newNode->AddProperty( "planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.outline.width", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.helperline.width", mitk::FloatProperty::New(2.0) ); + + newNode->AddProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(1.0,1.0,1.0) ); + newNode->AddProperty( "planarfigure.default.line.opacity", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.default.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.default.outline.opacity", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.default.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.default.helperline.opacity", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.default.markerline.color", mitk::ColorProperty::New(0.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.default.markerline.opacity", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.default.marker.color", mitk::ColorProperty::New(1.0,1.0,1.0) ); + newNode->AddProperty( "planarfigure.default.marker.opacity",mitk::FloatProperty::New(2.0) ); + + newNode->AddProperty( "planarfigure.hover.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.hover.line.opacity", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.hover.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.hover.outline.opacity", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.hover.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.hover.helperline.opacity", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.hover.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.hover.markerline.opacity", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.hover.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.hover.marker.opacity", mitk::FloatProperty::New(2.0) ); + + newNode->AddProperty( "planarfigure.selected.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.selected.line.opacity",mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.selected.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.selected.outline.opacity", mitk::FloatProperty::New(2.0)); + newNode->AddProperty( "planarfigure.selected.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.selected.helperline.opacity",mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.selected.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.selected.markerline.opacity", mitk::FloatProperty::New(2.0) ); + newNode->AddProperty( "planarfigure.selected.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); + newNode->AddProperty( "planarfigure.selected.marker.opacity",mitk::FloatProperty::New(2.0)); + + // figure drawn on the topmost layer / image + this->GetDataStorage()->Add(newNode); } /* * Generate polydata of random fibers */ void QmitkFiberBundleDeveloperView::GenerateVtkFibersRandom() { - - /* ===== TIMER CONFIGURATIONS for visual effect ====== + + /* ===== TIMER CONFIGURATIONS for visual effect ====== * start and stop is called in Thread */ - QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough - localTimer->setInterval( 10 ); - connect( localTimer, SIGNAL(timeout()), this, SLOT(UpdateGenerateRandomFibersTimer()) ); - - struct Package4WorkingThread ItemPackageForRandomGenerator; - ItemPackageForRandomGenerator.st_FBX = m_FiberBundleX; - ItemPackageForRandomGenerator.st_Controls = m_Controls; - ItemPackageForRandomGenerator.st_FancyGUITimer1 = localTimer; - ItemPackageForRandomGenerator.st_host = this; //needed to access method "PutFibersToDataStorage()" - ItemPackageForRandomGenerator.st_pntr_to_Method_PutFibersToDataStorage = &QmitkFiberBundleDeveloperView::PutFibersToDataStorage; //actual functor calling method putFibersToDataStorage - - //set element for thread monitoring - if (m_fiberMonitorIsOn) - ItemPackageForRandomGenerator.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; - - - if (m_threadInProgress) - return; //maybe popup window saying, working thread still in progress...pls wait - - m_GeneratorFibersRandom = new QmitkFiberGenerateRandomWorker(m_hostThread, ItemPackageForRandomGenerator); - m_GeneratorFibersRandom->moveToThread(m_hostThread); - - connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_GenerateFibersRandom()) ); - connect(m_hostThread, SIGNAL(started()), m_GeneratorFibersRandom, SLOT(run()) ); - connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_GenerateFibersRandom()) ); - connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_GenerateFibersRandom()) ); - - m_hostThread->start(QThread::LowestPriority); - + QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough + localTimer->setInterval( 10 ); + connect( localTimer, SIGNAL(timeout()), this, SLOT(UpdateGenerateRandomFibersTimer()) ); + + struct Package4WorkingThread ItemPackageForRandomGenerator; + ItemPackageForRandomGenerator.st_FBX = m_FiberBundleX; + ItemPackageForRandomGenerator.st_Controls = m_Controls; + ItemPackageForRandomGenerator.st_FancyGUITimer1 = localTimer; + ItemPackageForRandomGenerator.st_host = this; //needed to access method "PutFibersToDataStorage()" + ItemPackageForRandomGenerator.st_pntr_to_Method_PutFibersToDataStorage = &QmitkFiberBundleDeveloperView::PutFibersToDataStorage; //actual functor calling method putFibersToDataStorage + + //set element for thread monitoring + if (m_fiberMonitorIsOn) + ItemPackageForRandomGenerator.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; + + + if (m_threadInProgress) + return; //maybe popup window saying, working thread still in progress...pls wait + + m_GeneratorFibersRandom = new QmitkFiberGenerateRandomWorker(m_hostThread, ItemPackageForRandomGenerator); + m_GeneratorFibersRandom->moveToThread(m_hostThread); + + connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_GenerateFibersRandom()) ); + connect(m_hostThread, SIGNAL(started()), m_GeneratorFibersRandom, SLOT(run()) ); + connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_GenerateFibersRandom()) ); + connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_GenerateFibersRandom()) ); + + m_hostThread->start(QThread::LowestPriority); + } void QmitkFiberBundleDeveloperView::UpdateColorFibersTimer() { - // Make sure that thread has set according info-label to number! here we do not check if value is numeric! - QString crntValue = m_Controls->infoTimerColorCoding->text(); - int tmpVal = crntValue.toInt(); - m_Controls->infoTimerColorCoding->setText(QString::number(++tmpVal)); - m_Controls->infoTimerColorCoding->update(); + // Make sure that thread has set according info-label to number! here we do not check if value is numeric! + QString crntValue = m_Controls->infoTimerColorCoding->text(); + int tmpVal = crntValue.toInt(); + m_Controls->infoTimerColorCoding->setText(QString::number(++tmpVal)); + m_Controls->infoTimerColorCoding->update(); } void QmitkFiberBundleDeveloperView::UpdateGenerateRandomFibersTimer() { - // Make sure that thread has set according info-label to number! here we do not check if value is numeric! - QString crntValue = m_Controls->infoTimerGenerateFiberBundle->text(); - int tmpVal = crntValue.toInt(); - m_Controls->infoTimerGenerateFiberBundle->setText(QString::number(++tmpVal)); - m_Controls->infoTimerGenerateFiberBundle->update(); - + // Make sure that thread has set according info-label to number! here we do not check if value is numeric! + QString crntValue = m_Controls->infoTimerGenerateFiberBundle->text(); + int tmpVal = crntValue.toInt(); + m_Controls->infoTimerGenerateFiberBundle->setText(QString::number(++tmpVal)); + m_Controls->infoTimerGenerateFiberBundle->update(); + +} + +void QmitkFiberBundleDeveloperView::UpdateSetFAValuesTimer() +{ + // Make sure that thread has set according info-label to number! here we do not check if value is numeric! + QString crntValue = m_Controls->infoTimerSetFA->text(); + int tmpVal = crntValue.toInt(); + m_Controls->infoTimerSetFA->setText(QString::number(++tmpVal)); + m_Controls->infoTimerSetFA->update(); + } void QmitkFiberBundleDeveloperView::BeforeThread_GenerateFibersRandom() { - m_threadInProgress = true; - if (m_fiberMonitorIsOn){ - m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); - //m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_STARTED); - } + m_threadInProgress = true; + if (m_fiberMonitorIsOn){ + m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); + //m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_STARTED); + } } void QmitkFiberBundleDeveloperView::AfterThread_GenerateFibersRandom() { - m_threadInProgress = false; - if (m_fiberMonitorIsOn){ - m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); - m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); - } - disconnect(m_hostThread, 0, 0, 0); - m_hostThread->disconnect(); - - + m_threadInProgress = false; + if (m_fiberMonitorIsOn){ + m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); + m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); + } + // disconnect(m_hostThread, 0, 0, 0); + m_hostThread->disconnect(); + delete m_GeneratorFibersRandom; + + } vtkSmartPointer QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionX() { - int numOfFibers = m_Controls->boxFiberNumbers->value(); - vtkSmartPointer linesCell = vtkSmartPointer::New(); - vtkSmartPointer points = vtkSmartPointer::New(); - - //insert Origin point, this point has index 0 in point array - double originX = 0.0; - double originY = 0.0; - double originZ = 0.0; - - //after each iteration the origin of the new fiber increases - //here you set which direction is affected. - double increaseX = 0.0; - double increaseY = 1.0; - double increaseZ = 0.0; - - - //walk along X axis - //length of fibers increases in each iteration - for (int i=0; i newFiber = vtkSmartPointer::New(); - newFiber->GetPointIds()->SetNumberOfIds(i+2); - - //create starting point and add it to pointset - points->InsertNextPoint(originX + (double)i * increaseX , originY + (double)i * increaseY, originZ + (double)i * increaseZ); - - //add starting point to fiber - newFiber->GetPointIds()->SetId(0,points->GetNumberOfPoints()-1); - - //insert remaining points for fiber - for (int pj=0; pj<=i ; ++pj) - { //generate next point on X axis - points->InsertNextPoint( originX + (double)pj+1 , originY + (double)i * increaseY, originZ + (double)i * increaseZ ); - newFiber->GetPointIds()->SetId(pj+1,points->GetNumberOfPoints()-1); + int numOfFibers = m_Controls->boxFiberNumbers->value(); + vtkSmartPointer linesCell = vtkSmartPointer::New(); + vtkSmartPointer points = vtkSmartPointer::New(); + + //insert Origin point, this point has index 0 in point array + double originX = 0.0; + double originY = 0.0; + double originZ = 0.0; + + //after each iteration the origin of the new fiber increases + //here you set which direction is affected. + double increaseX = 0.0; + double increaseY = 1.0; + double increaseZ = 0.0; + + + //walk along X axis + //length of fibers increases in each iteration + for (int i=0; i newFiber = vtkSmartPointer::New(); + newFiber->GetPointIds()->SetNumberOfIds(i+2); + + //create starting point and add it to pointset + points->InsertNextPoint(originX + (double)i * increaseX , originY + (double)i * increaseY, originZ + (double)i * increaseZ); + + //add starting point to fiber + newFiber->GetPointIds()->SetId(0,points->GetNumberOfPoints()-1); + + //insert remaining points for fiber + for (int pj=0; pj<=i ; ++pj) + { //generate next point on X axis + points->InsertNextPoint( originX + (double)pj+1 , originY + (double)i * increaseY, originZ + (double)i * increaseZ ); + newFiber->GetPointIds()->SetId(pj+1,points->GetNumberOfPoints()-1); + } + + linesCell->InsertNextCell(newFiber); } - - linesCell->InsertNextCell(newFiber); - } - - vtkSmartPointer PDX = vtkSmartPointer::New(); - PDX->SetPoints(points); - PDX->SetLines(linesCell); - return PDX; + + vtkSmartPointer PDX = vtkSmartPointer::New(); + PDX->SetPoints(points); + PDX->SetLines(linesCell); + return PDX; } vtkSmartPointer QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionY() { - vtkSmartPointer PDY = vtkSmartPointer::New(); - //todo - - - - return PDY; -} + vtkSmartPointer PDY = vtkSmartPointer::New(); + //todo + + return PDY; +} + vtkSmartPointer QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionZ() { - vtkSmartPointer PDZ = vtkSmartPointer::New(); - //todo - - - - return PDZ; + vtkSmartPointer PDZ = vtkSmartPointer::New(); + //todo + + + + return PDZ; +} + +void QmitkFiberBundleDeveloperView::DoSetFAValues() +{ + + QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough + localTimer->setInterval( 10 ); + connect( localTimer, SIGNAL(timeout()), this, SLOT( UpdateSetFAValuesTimer() ) ); + + // pack items which are needed by thread processing + struct Package4WorkingThread ItemPackageToSetFAMap; + ItemPackageToSetFAMap.st_FBX = m_FiberBundleX; + ItemPackageToSetFAMap.st_FancyGUITimer1 = localTimer; + ItemPackageToSetFAMap.st_PassedDataNode = m_FANode; + ItemPackageToSetFAMap.st_Controls = m_Controls; + + if (m_fiberMonitorIsOn) + ItemPackageToSetFAMap.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; + + if (m_threadInProgress) + return; //maybe popup window saying, working thread still in progress...pls wait + + m_FiberFeederFASlave = new QmitkFiberFeederFAWorker(m_hostThread, ItemPackageToSetFAMap); + m_FiberFeederFASlave->moveToThread(m_hostThread); + + connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_FiberSetFA()) ); + connect(m_hostThread, SIGNAL(started()), m_FiberFeederFASlave, SLOT(run()) ); + connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_FiberSetFA())); + connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_FiberSetFA())); + m_hostThread->start(QThread::LowestPriority); +} + +void QmitkFiberBundleDeveloperView::DoSetFAMap() +{ + std::vector nodes = GetDataManagerSelection(); + if (nodes.empty()) + { + m_Controls->lineEdit_FAMap->setText("N/A"); + return; + } + + for( std::vector::iterator it = nodes.begin(); + it != nodes.end(); + ++it ) + { + mitk::DataNode::Pointer node = *it; + + if (node.IsNotNull() && dynamic_cast(node->GetData())) + { + // this node is what we want + m_FANode = node; + m_Controls->lineEdit_FAMap->setText(node->GetName().c_str()); + return; + } + } } +void QmitkFiberBundleDeveloperView::BeforeThread_FiberSetFA() +{ + m_threadInProgress = true; + if (m_fiberMonitorIsOn){ + m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); + } +} + +void QmitkFiberBundleDeveloperView::AfterThread_FiberSetFA() +{ + m_threadInProgress = false; + if (m_fiberMonitorIsOn){ + m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); + m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); + } + disconnect(m_hostThread, 0, 0, 0); + m_hostThread->disconnect(); + //update renderer + m_FiberBundleNode->Modified(); + m_MultiWidget->ForceImmediateUpdate(); + + //update QComboBox(dropDown menu) in view of available ColorCodings + this->DoGatherColorCodings(); + + delete m_FiberFeederFASlave; +} void QmitkFiberBundleDeveloperView::DoColorFibers() { - // - MITK_INFO << "call fibercoloring in fiberBundleX"; - QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough - localTimer->setInterval( 10 ); - connect( localTimer, SIGNAL(timeout()), this, SLOT( UpdateColorFibersTimer() ) ); - - // pack items which are needed by thread processing - struct Package4WorkingThread ItemPackageForFiberColoring; - ItemPackageForFiberColoring.st_FBX = m_FiberBundleX; - ItemPackageForFiberColoring.st_FancyGUITimer1 = localTimer; - ItemPackageForFiberColoring.st_Controls = m_Controls; //needed to catch up some selections and set options in GUI - - if (m_fiberMonitorIsOn) - ItemPackageForFiberColoring.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; - - if (m_threadInProgress) - return; //maybe popup window saying, working thread still in progress...pls wait - - m_FiberColoringSlave = new QmitkFiberColoringWorker(m_hostThread, ItemPackageForFiberColoring); - m_FiberColoringSlave->moveToThread(m_hostThread); + // + MITK_INFO << "call fibercoloring in fiberBundleX"; + QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough + localTimer->setInterval( 10 ); + connect( localTimer, SIGNAL(timeout()), this, SLOT( UpdateColorFibersTimer() ) ); + + // pack items which are needed by thread processing + struct Package4WorkingThread ItemPackageForFiberColoring; + ItemPackageForFiberColoring.st_FBX = m_FiberBundleX; + ItemPackageForFiberColoring.st_PassedDataNode = m_FiberBundleNode; + ItemPackageForFiberColoring.st_FancyGUITimer1 = localTimer; + ItemPackageForFiberColoring.st_Controls = m_Controls; //needed to catch up some selections and set options in GUI + + if (m_fiberMonitorIsOn) + ItemPackageForFiberColoring.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; + + if (m_threadInProgress) + return; //maybe popup window saying, working thread still in progress...pls wait + + m_FiberColoringSlave = new QmitkFiberColoringWorker(m_hostThread, ItemPackageForFiberColoring); + m_FiberColoringSlave->moveToThread(m_hostThread); connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_FiberColorCoding()) ); - connect(m_hostThread, SIGNAL(started()), m_FiberColoringSlave, SLOT(run()) ); - connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_FiberColorCoding())); - connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_FiberColorCoding())); - m_hostThread->start(QThread::LowestPriority); - + connect(m_hostThread, SIGNAL(started()), m_FiberColoringSlave, SLOT(run()) ); + connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_FiberColorCoding())); + connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_FiberColorCoding())); + m_hostThread->start(QThread::LowestPriority); + } void QmitkFiberBundleDeveloperView::BeforeThread_FiberColorCoding() { - m_threadInProgress = true; - if (m_fiberMonitorIsOn){ - m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); - } + m_threadInProgress = true; + if (m_fiberMonitorIsOn){ + m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); + } } void QmitkFiberBundleDeveloperView::AfterThread_FiberColorCoding() { - m_threadInProgress = false; - if (m_fiberMonitorIsOn){ - m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); - m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); - } - disconnect(m_hostThread, 0, 0, 0); - m_hostThread->disconnect(); + m_threadInProgress = false; + if (m_fiberMonitorIsOn){ + m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); + m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); + } + disconnect(m_hostThread, 0, 0, 0); + m_hostThread->disconnect(); + //update renderer + m_FiberBundleNode->Modified(); + m_MultiWidget->ForceImmediateUpdate(); + + + //update QComboBox(dropDown menu) in view of available ColorCodings + this->DoGatherColorCodings(); + + delete m_FiberColoringSlave; +} + + +void QmitkFiberBundleDeveloperView::DoGatherColorCodings() +{ + QStringList fbxColorCodings = m_FiberBundleX->GetAvailableColorCodings(); + + //update dropDown Menu + //remove all items from menu + m_suppressSignal = true; + int ddItems = m_Controls->ddAvailableColorcodings->count(); + for(int i=ddItems-1; i>=0; i--) + { //note, after each item remove, index in QComboBox is updated. sending signal: index changed + m_Controls->ddAvailableColorcodings->removeItem(i); + } + //fill new data into menu + m_Controls->ddAvailableColorcodings->addItems(fbxColorCodings); + m_Controls->ddAvailableColorcodings->addItem(m_FiberBundleX->COLORCODING_CUSTOM); + + //highlight current colorcoding + QString cc = m_FiberBundleX->GetCurrentColorCoding(); + MITK_INFO << cc.toStdString().c_str() << " is at idx: " << m_Controls->ddAvailableColorcodings->findText(cc); + m_Controls->ddAvailableColorcodings->setCurrentIndex( m_Controls->ddAvailableColorcodings->findText(cc) ); + m_Controls->ddAvailableColorcodings->update(); + m_suppressSignal = false; +} + + +void QmitkFiberBundleDeveloperView::SetCurrentColorCoding(int idx) +{ + if(!m_suppressSignal){ + QString selectedColorCoding = m_Controls->ddAvailableColorcodings->itemText(idx); + m_FiberBundleX->SetColorCoding(selectedColorCoding.toStdString().c_str() ); //QString to char + // update rendering + m_FiberBundleNode->Modified(); + m_MultiWidget->ForceImmediateUpdate(); + } } /* === OutSourcedMethod: THIS METHOD GENERATES ESSENTIAL GEOMETRY PARAMETERS FOR THE MITK FRAMEWORK === - * WITHOUT, the rendering mechanism will ignore objects without valid Geometry + * WITHOUT, the rendering mechanism will ignore objects without valid Geometry * for each object, MITK requires: ORIGIN, SPACING, TRANSFORM MATRIX, BOUNDING-BOX */ mitk::Geometry3D::Pointer QmitkFiberBundleDeveloperView::GenerateStandardGeometryForMITK() { - mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); - - // generate origin - mitk::Point3D origin; - origin[0] = 0; - origin[1] = 0; - origin[2] = 0; - geometry->SetOrigin(origin); - - // generate spacing - float spacing[3] = {1,1,1}; - geometry->SetSpacing(spacing); - - - // generate identity transform-matrix - vtkMatrix4x4* m = vtkMatrix4x4::New(); - geometry->SetIndexToWorldTransformByVtkMatrix(m); - - // generate boundingbox - // for an usable bounding-box use gui parameters to estimate the boundingbox - float bounds[] = {500, 500, 500, -500, -500, -500}; - - // GET SELECTED FIBER DIRECTION - QString fibDirection; //stores the object_name of selected radiobutton - QVector::const_iterator i; - for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) - { - QRadioButton* rdbtn = *i; - if (rdbtn->isChecked()) - fibDirection = rdbtn->objectName(); - } - - if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) { - // use information about distribution parameter to calculate bounding box - int distrRadius = m_Controls->boxDistributionRadius->value(); - bounds[0] = distrRadius; - bounds[1] = distrRadius; - bounds[2] = distrRadius; - bounds[3] = -distrRadius; - bounds[4] = -distrRadius; - bounds[5] = -distrRadius; - - } else { - // so far only X,Y,Z directions are available - MITK_INFO << "_______GEOMETRY ISSUE_____\n***BoundingBox for X, Y, Z fiber directions are not optimized yet!***"; - - int maxFibLength = m_Controls->boxFiberMaxLength->value(); - bounds[0] = maxFibLength; - bounds[1] = maxFibLength; - bounds[2] = maxFibLength; - bounds[3] = -maxFibLength; - bounds[4] = -maxFibLength; - bounds[5] = -maxFibLength; - } - - geometry->SetFloatBounds(bounds); - geometry->SetImageGeometry(true); //?? - - return geometry; - - + mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); + + // generate origin + mitk::Point3D origin; + origin[0] = 0; + origin[1] = 0; + origin[2] = 0; + geometry->SetOrigin(origin); + + // generate spacing + float spacing[3] = {1,1,1}; + geometry->SetSpacing(spacing); + + + // generate identity transform-matrix + vtkSmartPointer m = vtkMatrix4x4::New(); + geometry->SetIndexToWorldTransformByVtkMatrix(m); + + // generate boundingbox + // for an usable bounding-box use gui parameters to estimate the boundingbox + float bounds[] = {500, 500, 500, -500, -500, -500}; + + // GET SELECTED FIBER DIRECTION + QString fibDirection; //stores the object_name of selected radiobutton + QVector::const_iterator i; + for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i) + { + QRadioButton* rdbtn = *i; + if (rdbtn->isChecked()) + fibDirection = rdbtn->objectName(); + } + + if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) { + // use information about distribution parameter to calculate bounding box + int distrRadius = m_Controls->boxDistributionRadius->value(); + bounds[0] = distrRadius; + bounds[1] = distrRadius; + bounds[2] = distrRadius; + bounds[3] = -distrRadius; + bounds[4] = -distrRadius; + bounds[5] = -distrRadius; + + } else { + // so far only X,Y,Z directions are available + MITK_INFO << "_______GEOMETRY ISSUE_____\n***BoundingBox for X, Y, Z fiber directions are not optimized yet!***"; + + int maxFibLength = m_Controls->boxFiberMaxLength->value(); + bounds[0] = maxFibLength; + bounds[1] = maxFibLength; + bounds[2] = maxFibLength; + bounds[3] = -maxFibLength; + bounds[4] = -maxFibLength; + bounds[5] = -maxFibLength; + } + + geometry->SetFloatBounds(bounds); + geometry->SetImageGeometry(true); //?? + + return geometry; + + } void QmitkFiberBundleDeveloperView::UpdateFiberIDTimer() { - //MAKE SURE by yourself THAT NOTHING ELSE THAN A NUMBER IS SET IN THAT LABEL - QString crntValue = m_Controls->infoTimerGenerateFiberIds->text(); - int tmpVal = crntValue.toInt(); - m_Controls->infoTimerGenerateFiberIds->setText(QString::number(++tmpVal)); - m_Controls->infoTimerGenerateFiberIds->update(); - + //MAKE SURE by yourself THAT NOTHING ELSE THAN A NUMBER IS SET IN THAT LABEL + QString crntValue = m_Controls->infoTimerGenerateFiberIds->text(); + int tmpVal = crntValue.toInt(); + m_Controls->infoTimerGenerateFiberIds->setText(QString::number(++tmpVal)); + m_Controls->infoTimerGenerateFiberIds->update(); + } /* Initialie ID dataset in FiberBundleX */ void QmitkFiberBundleDeveloperView::DoGenerateFiberIDs() { - - /* ===== TIMER CONFIGURATIONS for visual effect ====== + + /* ===== TIMER CONFIGURATIONS for visual effect ====== * start and stop is called in Thread */ - QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough - localTimer->setInterval( 10 ); - connect( localTimer, SIGNAL(timeout()), this, SLOT(UpdateFiberIDTimer()) ); - - - // pack items which are needed by thread processing - struct Package4WorkingThread FiberIdPackage; - FiberIdPackage.st_FBX = m_FiberBundleX; - FiberIdPackage.st_FancyGUITimer1 = localTimer; - FiberIdPackage.st_Controls = m_Controls; - - //set element for thread monitoring - if (m_fiberMonitorIsOn) - FiberIdPackage.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; - - - if (m_threadInProgress) - return; //maybe popup window saying, working thread still in progress...pls wait - - // THREAD CONFIGURATION - m_FiberIDGenerator = new QmitkFiberIDWorker(m_hostThread, FiberIdPackage); - m_FiberIDGenerator->moveToThread(m_hostThread); - connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_IdGenerate()) ); - connect(m_hostThread, SIGNAL(started()), m_FiberIDGenerator, SLOT(run())); - connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_IdGenerate())); - connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_IdGenerate())); - m_hostThread->start(QThread::LowestPriority); - - - - // m_Controls->infoTimerGenerateFiberIds->setText(QString::number(clock.GetTotal())); - + QTimer *localTimer = new QTimer; // timer must be initialized here, otherwise timer is not fancy enough + localTimer->setInterval( 10 ); + connect( localTimer, SIGNAL(timeout()), this, SLOT(UpdateFiberIDTimer()) ); + + + // pack items which are needed by thread processing + struct Package4WorkingThread FiberIdPackage; + FiberIdPackage.st_FBX = m_FiberBundleX; + FiberIdPackage.st_FancyGUITimer1 = localTimer; + FiberIdPackage.st_Controls = m_Controls; + + //set element for thread monitoring + if (m_fiberMonitorIsOn) + FiberIdPackage.st_fiberThreadMonitorWorker = m_fiberThreadMonitorWorker; + + + if (m_threadInProgress) + return; //maybe popup window saying, working thread still in progress...pls wait + + // THREAD CONFIGURATION + m_FiberIDGenerator = new QmitkFiberIDWorker(m_hostThread, FiberIdPackage); + m_FiberIDGenerator->moveToThread(m_hostThread); + connect(m_hostThread, SIGNAL(started()), this, SLOT( BeforeThread_IdGenerate()) ); + connect(m_hostThread, SIGNAL(started()), m_FiberIDGenerator, SLOT(run())); + connect(m_hostThread, SIGNAL(finished()), this, SLOT(AfterThread_IdGenerate())); + connect(m_hostThread, SIGNAL(terminated()), this, SLOT(AfterThread_IdGenerate())); + m_hostThread->start(QThread::LowestPriority); + + + + // m_Controls->infoTimerGenerateFiberIds->setText(QString::number(clock.GetTotal())); + } void QmitkFiberBundleDeveloperView::BeforeThread_IdGenerate() { - m_threadInProgress = true; - if (m_fiberMonitorIsOn){ - m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); - m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_STARTED); - } + m_threadInProgress = true; + if (m_fiberMonitorIsOn){ + m_fiberThreadMonitorWorker->threadForFiberProcessingStarted(); + m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_STARTED); + } } void QmitkFiberBundleDeveloperView::AfterThread_IdGenerate() { - m_threadInProgress = false; - if (m_fiberMonitorIsOn){ - m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); - m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); - } - disconnect(m_hostThread, 0, 0, 0); - m_hostThread->disconnect(); - + m_threadInProgress = false; + if (m_fiberMonitorIsOn){ + m_fiberThreadMonitorWorker->threadForFiberProcessingFinished(); + m_fiberThreadMonitorWorker->setThreadStatus(FBX_STATUS_IDLE); + } + disconnect(m_hostThread, 0, 0, 0); + m_hostThread->disconnect(); + delete m_FiberIDGenerator; + } void QmitkFiberBundleDeveloperView::ResetFiberInfoWidget() { - if (m_Controls->infoAnalyseNumOfFibers->isEnabled()) { - m_Controls->infoAnalyseNumOfFibers->setText("-"); - m_Controls->infoAnalyseNumOfPoints->setText("-"); - m_Controls->infoAnalyseNumOfFibers->setEnabled(false); - } + if (m_Controls->infoAnalyseNumOfFibers->isEnabled()) { + m_Controls->infoAnalyseNumOfFibers->setText("-"); + m_Controls->infoAnalyseNumOfPoints->setText("-"); + m_Controls->infoAnalyseNumOfFibers->setEnabled(false); + } } void QmitkFiberBundleDeveloperView::FeedFiberInfoWidget() { - if (!m_Controls->infoAnalyseNumOfFibers->isEnabled()) - m_Controls->infoAnalyseNumOfFibers->setEnabled(true); - - QString numOfFibers; - numOfFibers.setNum( m_FiberBundleX->GetFiberPolyData()->GetNumberOfLines() ); - QString numOfPoints; - numOfPoints.setNum( m_FiberBundleX->GetFiberPolyData()->GetNumberOfPoints() ); - - m_Controls->infoAnalyseNumOfFibers->setText( numOfFibers ); - m_Controls->infoAnalyseNumOfPoints->setText( numOfPoints ); + if (!m_Controls->infoAnalyseNumOfFibers->isEnabled()) + m_Controls->infoAnalyseNumOfFibers->setEnabled(true); + + QString numOfFibers; + numOfFibers.setNum( m_FiberBundleX->GetFiberPolyData()->GetNumberOfLines() ); + QString numOfPoints; + numOfPoints.setNum( m_FiberBundleX->GetFiberPolyData()->GetNumberOfPoints() ); + + m_Controls->infoAnalyseNumOfFibers->setText( numOfFibers ); + m_Controls->infoAnalyseNumOfPoints->setText( numOfPoints ); } void QmitkFiberBundleDeveloperView::SelectionChangedToolBox(int idx) { - // show/reset items of selected toolbox page FiberInfo - if (m_Controls->page_FiberInfo->isVisible()) - { - if (m_FiberBundleX != NULL) { - FeedFiberInfoWidget(); - - } else { - //if infolables are disabled: return - //else set info back to - and set label and info to disabled - ResetFiberInfoWidget(); + // show/reset items of selected toolbox page FiberInfo + if (m_Controls->page_FiberInfo->isVisible()) + { + if (m_FiberBundleX != NULL) { + FeedFiberInfoWidget(); + + } else { + //if infolables are disabled: return + //else set info back to - and set label and info to disabled + ResetFiberInfoWidget(); + } } - } - - // show/reset items of selected toolbox page FiberProcessing - if (m_Controls->page_FiberProcessing->isVisible()) - { - if (m_FiberBundleX != NULL) - { - if (m_Controls->tabColoring->isVisible()){ - //show button colorCoding - m_Controls->buttonColorFibers->setEnabled(true); - MITK_INFO << "Color"; - - }else if(m_Controls->tabCutting->isVisible()){ -// m_Controls->buttonGenerateFiberIds->setEnabled(true); - - - }else if(m_Controls->tabShape->isVisible()){ -// m_Controls->buttonSMFibers->setEnabled(true); -// m_Controls->buttonVtkDecimatePro->setEnabled(true); -// m_Controls->buttonVtkSmoothPD->setEnabled(true); -// m_Controls->buttonGenerateTubes->setEnabled(true); - } - - - } else { - m_Controls->buttonColorFibers->setEnabled(false); - m_Controls->buttonGenerateFiberIds->setEnabled(false); - m_Controls->buttonSMFibers->setEnabled(false); - m_Controls->buttonVtkDecimatePro->setEnabled(false); - m_Controls->buttonVtkSmoothPD->setEnabled(false); - m_Controls->buttonGenerateTubes->setEnabled(true); - - } - } - + + // show/reset items of selected toolbox page FiberProcessing + if (m_Controls->page_FiberProcessing->isVisible()) + { + if (m_FiberBundleX.IsNotNull() && m_PlanarFigure.IsNotNull() ) + { + //show fiber extraction button + m_Controls->buttonExtractFibers->setEnabled(true); + + } else { + m_Controls->buttonExtractFibers->setEnabled(false); + } + + if (m_FiberBundleX.IsNotNull()) + { + //show button colorCoding + m_Controls->buttonColorFibers->setEnabled(true); + m_Controls->ddAvailableColorcodings->setEnabled(true); + m_Controls->buttonGenerateFiberIds->setEnabled(true); + + // m_Controls->buttonSMFibers->setEnabled(true); + // m_Controls->buttonVtkDecimatePro->setEnabled(true); + // m_Controls->buttonVtkSmoothPD->setEnabled(true); + // m_Controls->buttonGenerateTubes->setEnabled(true); + + } else { + m_Controls->buttonColorFibers->setEnabled(false); + m_Controls->ddAvailableColorcodings->setEnabled(false); + m_Controls->buttonGenerateFiberIds->setEnabled(false); + m_Controls->buttonSMFibers->setEnabled(false); + m_Controls->buttonVtkDecimatePro->setEnabled(false); + m_Controls->buttonVtkSmoothPD->setEnabled(false); + m_Controls->buttonGenerateTubes->setEnabled(true); + + } + + + } + } void QmitkFiberBundleDeveloperView::FBXDependendGUIElementsConfigurator() { - // ==== FIBER PROCESSING ELEMENTS and ALL ELEMENTS WHICH NEED A FBX DATANODE====== -// m_Controls->buttonGenerateFiberIds->setEnabled(isVisible); moved to selectionChangedToolBox - - SelectionChangedToolBox(-1); //set gui elements with respect to active tab, widget, etc. -1 has no effect - + // ==== FIBER PROCESSING ELEMENTS and ALL ELEMENTS WHICH NEED A FBX DATANODE====== + // m_Controls->buttonGenerateFiberIds->setEnabled(isVisible); moved to selectionChangedToolBox + + SelectionChangedToolBox(-1); //set gui elements with respect to active tab, widget, etc. -1 has no effect + } void QmitkFiberBundleDeveloperView::DoMonitorFiberThreads(int checkStatus) { - //check if in datanode exists already a node of type mitkFiberBundleXThreadMonitor - //if not then put node to datastorage - - //if checkStatus is 1 then start qtimer using fading in starting text in datanode - //if checkStatus is 0 then fade out dataNode using qtimer - - if (checkStatus) - { - m_fiberMonitorIsOn = true; - // Generate Node hosting thread information - mitk::FiberBundleXThreadMonitor::Pointer FBXThreadMonitor = mitk::FiberBundleXThreadMonitor::New(); - FBXThreadMonitor->SetGeometry(this->GenerateStandardGeometryForMITK()); - - m_MonitorNode = mitk::DataNode::New(); - m_MonitorNode->SetName("FBX_threadMonitor"); - m_MonitorNode->SetData(FBXThreadMonitor); - m_MonitorNode->SetVisibility(true); - m_MonitorNode->SetOpacity(1.0); - - GetDataStorage()->Add(m_MonitorNode); - - //following code is needed for rendering text in mitk! without geometry nothing is rendered - const mitk::PlaneGeometry * tsgeo = m_MultiWidget->GetTimeNavigationController()->GetCurrentPlaneGeometry(); - if (tsgeo == NULL) { - /* GetDataStorage()->Modified etc. have no effect, therefore proceed as followed below */ - // get all nodes that have not set "includeInBoundingBox" to false - mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New( "includeInBoundingBox" - , mitk::BoolProperty::New(false))); - mitk::DataStorage::SetOfObjects::ConstPointer rs = GetDataStorage()->GetSubset(pred); - // calculate bounding geometry of these nodes - mitk::TimeSlicedGeometry::Pointer bounds = GetDataStorage()->ComputeBoundingGeometry3D(rs); - // initialize the views to the bounding geometry - mitk::RenderingManager::GetInstance()->InitializeViews(bounds); + //check if in datanode exists already a node of type mitkFiberBundleXThreadMonitor + //if not then put node to datastorage + + //if checkStatus is 1 then start qtimer using fading in starting text in datanode + //if checkStatus is 0 then fade out dataNode using qtimer + + if (checkStatus) + { + m_fiberMonitorIsOn = true; + // Generate Node hosting thread information + mitk::FiberBundleXThreadMonitor::Pointer FBXThreadMonitor = mitk::FiberBundleXThreadMonitor::New(); + FBXThreadMonitor->SetGeometry(this->GenerateStandardGeometryForMITK()); + + m_MonitorNode = mitk::DataNode::New(); + m_MonitorNode->SetName("FBX_threadMonitor"); + m_MonitorNode->SetData(FBXThreadMonitor); + m_MonitorNode->SetVisibility(true); + m_MonitorNode->SetOpacity(1.0); + + GetDataStorage()->Add(m_MonitorNode); + + //following code is needed for rendering text in mitk! without geometry nothing is rendered + const mitk::PlaneGeometry * tsgeo = m_MultiWidget->GetTimeNavigationController()->GetCurrentPlaneGeometry(); + if (tsgeo == NULL) { + /* GetDataStorage()->Modified etc. have no effect, therefore proceed as followed below */ + // get all nodes that have not set "includeInBoundingBox" to false + mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New( "includeInBoundingBox" + , mitk::BoolProperty::New(false))); + mitk::DataStorage::SetOfObjects::ConstPointer rs = GetDataStorage()->GetSubset(pred); + // calculate bounding geometry of these nodes + mitk::TimeSlicedGeometry::Pointer bounds = GetDataStorage()->ComputeBoundingGeometry3D(rs); + // initialize the views to the bounding geometry + mitk::RenderingManager::GetInstance()->InitializeViews(bounds); + } else { + + GetDataStorage()->Modified(); + m_MultiWidget->RequestUpdate(); //necessary?? + } + //__GEOMETRY FOR THREADMONITOR GENERATED + + /* ====== initialize thread for managing fiberThread information ========= */ + m_monitorThread = new QThread; + // the package needs datastorage, MonitorDatanode, standardmultiwidget, + struct Package4WorkingThread ItemPackageForThreadMonitor; + ItemPackageForThreadMonitor.st_DataStorage = GetDataStorage(); + ItemPackageForThreadMonitor.st_ThreadMonitorDataNode = m_MonitorNode; + ItemPackageForThreadMonitor.st_MultiWidget = m_MultiWidget; + ItemPackageForThreadMonitor.st_FBX_Monitor = FBXThreadMonitor; + + m_fiberThreadMonitorWorker = new QmitkFiberThreadMonitorWorker(m_monitorThread, ItemPackageForThreadMonitor); + + m_fiberThreadMonitorWorker->moveToThread(m_monitorThread); + connect ( m_monitorThread, SIGNAL( started() ), m_fiberThreadMonitorWorker, SLOT( run() ) ); + m_monitorThread->start(QThread::LowestPriority); + m_fiberThreadMonitorWorker->initializeMonitor();//do some init animation ;-) + + } else { - - GetDataStorage()->Modified(); - m_MultiWidget->RequestUpdate(); //necessary?? + m_fiberMonitorIsOn = false; + + m_monitorThread->quit(); + //think about outsourcing following lines to quit / terminate slot of thread + GetDataStorage()->Remove(m_MonitorNode); + GetDataStorage()->Modified(); + m_MultiWidget->RequestUpdate(); //necessary?? } - //__GEOMETRY FOR THREADMONITOR GENERATED - - /* ====== initialize thread for managing fiberThread information ========= */ - m_monitorThread = new QThread; - // the package needs datastorage, MonitorDatanode, standardmultiwidget, - struct Package4WorkingThread ItemPackageForThreadMonitor; - ItemPackageForThreadMonitor.st_DataStorage = GetDataStorage(); - ItemPackageForThreadMonitor.st_ThreadMonitorDataNode = m_MonitorNode; - ItemPackageForThreadMonitor.st_MultiWidget = m_MultiWidget; - ItemPackageForThreadMonitor.st_FBX_Monitor = FBXThreadMonitor; - - m_fiberThreadMonitorWorker = new QmitkFiberThreadMonitorWorker(m_monitorThread, ItemPackageForThreadMonitor); - - m_fiberThreadMonitorWorker->moveToThread(m_monitorThread); - connect ( m_monitorThread, SIGNAL( started() ), m_fiberThreadMonitorWorker, SLOT( run() ) ); - m_monitorThread->start(QThread::LowestPriority); - m_fiberThreadMonitorWorker->initializeMonitor();//do some init animation ;-) - - - } else { - m_fiberMonitorIsOn = false; - - m_monitorThread->quit(); - //think about outsourcing following lines to quit / terminate slot of thread - GetDataStorage()->Remove(m_MonitorNode); - GetDataStorage()->Modified(); - m_MultiWidget->RequestUpdate(); //necessary?? - } - - - + + + } void QmitkFiberBundleDeveloperView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { - m_MultiWidget = &stdMultiWidget; + m_MultiWidget = &stdMultiWidget; } void QmitkFiberBundleDeveloperView::StdMultiWidgetNotAvailable() { - m_MultiWidget = NULL; + m_MultiWidget = NULL; } /* OnSelectionChanged is registered to SelectionService, therefore no need to implement SelectionService Listener explicitly */ void QmitkFiberBundleDeveloperView::OnSelectionChanged( std::vector nodes ) { - - /* ==== reset everyhing related to FiberBundleX ====== + + if (nodes.empty()) + return; + /* ==== reset everyhing related to FiberBundleX ====== * - variable m_FiberBundleX * - visualization of analysed fiberbundle */ - m_FiberBundleX = NULL; //reset pointer, so that member does not point to depricated locations - ResetFiberInfoWidget(); - FBXDependendGUIElementsConfigurator(); //every gui element which needs a FBX for processing is disabled - - //timer reset only when no thread is in progress - if (!m_threadInProgress) { - m_Controls->infoTimerGenerateFiberIds->setText("-"); //set GUI representation of timer to - - m_Controls->infoTimerGenerateFiberBundle->setText( "-" ); - m_Controls->infoTimerColorCoding->setText( "-" ); - } - //==================================================== - - - if (nodes.empty()) - return; - - - for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) - { - mitk::DataNode::Pointer node = *it; - - /* CHECKPOINT: FIBERBUNDLE*/ - if( node.IsNotNull() && dynamic_cast(node->GetData()) ) + m_FiberBundleNode = NULL; + m_FiberBundleX = NULL; //reset pointer, so that member does not point to depricated locations + m_PlanarFigure = NULL; + ResetFiberInfoWidget(); + + + //timer reset only when no thread is in progress + if (!m_threadInProgress) { + m_Controls->infoTimerGenerateFiberIds->setText("-"); //set GUI representation of timer to - + m_Controls->infoTimerGenerateFiberBundle->setText( "-" ); + m_Controls->infoTimerColorCoding->setText( "-" ); + } + //==================================================== + + + + + for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { - m_FiberBundleX = dynamic_cast(node->GetData()); - if (m_FiberBundleX == NULL) - MITK_INFO << "========ATTENTION=========\n unable to load selected FiberBundleX to FiberBundleDeveloper-plugin \n"; - - // ==== FIBERBUNDLE_INFO ELEMENTS ==== - if ( m_Controls->page_FiberInfo->isVisible() ) - FeedFiberInfoWidget(); - - - // enable FiberBundleX related Gui Elements, such as buttons etc. - FBXDependendGUIElementsConfigurator(); - + mitk::DataNode::Pointer node = *it; + + /* CHECKPOINT: FIBERBUNDLE*/ + if( node.IsNotNull() && dynamic_cast(node->GetData()) ) + { + m_FiberBundleNode = node; + m_FiberBundleX = dynamic_cast(node->GetData()); + if (m_FiberBundleX.IsNull()){ + MITK_INFO << "========ATTENTION=========\n unable to load selected FiberBundleX to FiberBundleDeveloper-plugin \n"; + m_FiberBundleNode = NULL; + } + // ==== FIBERBUNDLE_INFO ELEMENTS ==== + if ( m_Controls->page_FiberInfo->isVisible() ) + FeedFiberInfoWidget(); + + // enable FiberBundleX related Gui Elements, such as buttons etc. + this->FBXDependendGUIElementsConfigurator(); + this->DoGatherColorCodings(); + + } + /* CHECKPOINT: PLANARFIGURE */ + else if ( node.IsNotNull() && dynamic_cast(node->GetData()) ) + { + m_PlanarFigure = dynamic_cast(node->GetData()); + MITK_INFO << "PF selected"; + + if (m_PlanarFigure.IsNull()) + MITK_INFO << "========ATTENTION=========\n unable to load selected Planarfigure to FiberBundleDeveloper-plugin \n"; + + } + } - - - - - } + //update gui elements depending on given nodes + + FBXDependendGUIElementsConfigurator(); //every gui element which needs a FBX for processing is disabled +} + + +void QmitkFiberBundleDeveloperView::ActionDrawEllipseTriggered() +{ + // bool checked = m_Controls->m_CircleButton->isChecked(); + mitk::PlanarCircle::Pointer figure = mitk::PlanarCircle::New(); + this->PutFigureToDataStorage(figure, QString("Circle%1").arg(++m_CircleCounter)); + + MITK_INFO << "PlanarCircle created ..."; + + mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDefaultDataStorage()->GetAll(); + mitk::DataNode* node = 0; + mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; + mitk::PlanarFigure* figureP = 0; + + for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() + ; it++) + { + node = const_cast(it->Value().GetPointer()); + figureP = dynamic_cast(node->GetData()); + + if(figureP) + { + figureInteractor = dynamic_cast(node->GetInteractor()); + + if(figureInteractor.IsNull()) + figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", node); + + mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); + } + } + } void QmitkFiberBundleDeveloperView::Activated() { - - MITK_INFO << "FB DevelopersV ACTIVATED()"; - - + + MITK_INFO << "FB DevelopersV ACTIVATED()"; + + } diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.h b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.h index f106c16c8f..4f3492e822 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.h +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperView.h @@ -1,316 +1,383 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ Version: $Revision: 21975 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef QmitkFiberBundleDeveloperView_h #define QmitkFiberBundleDeveloperView_h #include #include #include #include "ui_QmitkFiberBundleDeveloperViewControls.h" #include #include #include #include // Qt #include #include #include // VTK #include #include #include #include #include #include class QmitkFiberThreadMonitorWorker; //include needed for struct element class QmitkFiberBundleDeveloperView; //this include is needed for the struct element, especially for functors to QmitkFiberBundleDeveloperView /* ==== THIS STRUCT CONTAINS ALL NECESSARY VARIABLES * TO EXECUTE AND UPDATE GUI ELEMENTS DURING PROCESSING OF A THREAD * why? either you add tons of friendclasses (e.g. FiberWorker objects), or you create a package containing all items needed. Otherwise you have to set all members etc. to public! */ struct Package4WorkingThread { mitk::FiberBundleX* st_FBX; QTimer* st_FancyGUITimer1; Ui::QmitkFiberBundleDeveloperViewControls* st_Controls; //functors to outdoor methods QmitkFiberBundleDeveloperView* st_host; - void (QmitkFiberBundleDeveloperView::*st_pntr_to_Method_PutFibersToDataStorage) (vtkPolyData*); + void (QmitkFiberBundleDeveloperView::*st_pntr_to_Method_PutFibersToDataStorage) (vtkSmartPointer); - //==DO NOT TOUCH THIS SECTION=== + //==DO NOT TOUCH THIS SECTION=== you might extend this section, but do NOT shorten it! hai capito! //host MITK I/O elements, especially needed for thread monitoring QmitkFiberThreadMonitorWorker *st_fiberThreadMonitorWorker; mitk::FiberBundleXThreadMonitor::Pointer st_FBX_Monitor; //needed for direct access do animation/fancy methods mitk::DataNode::Pointer st_ThreadMonitorDataNode; //needed for renderer to recognize node modifications + mitk::DataNode::Pointer st_PassedDataNode; //put an extra node if needed mitk::DataStorage::Pointer st_DataStorage; //well that is discussable if needed ;-) probably not QmitkStdMultiWidget* st_MultiWidget; //needed for rendering update + mitk::PlanarFigure::Pointer st_PlanarFigure; //needed for fiberextraction }; // ==================================================================== // ============= WORKER WHICH IS PASSED TO THREAD ===================== // ==================================================================== //## Documentation //## This class does the actual work for generating fiber ids. class QmitkFiberIDWorker : public QObject { Q_OBJECT public: QmitkFiberIDWorker( QThread*, Package4WorkingThread ); public slots: void run(); private: Package4WorkingThread m_itemPackage; QThread* m_hostingThread; }; // ==================================================================== // ============= WORKER WHICH IS PASSED TO THREAD ===================== // ==================================================================== //## Documentation //## This class does the actual work for colorcoding fibers. class QmitkFiberColoringWorker : public QObject { Q_OBJECT public: QmitkFiberColoringWorker( QThread*, Package4WorkingThread ); public slots: void run(); private: Package4WorkingThread m_itemPackage; QThread* m_hostingThread; }; // ==================================================================== // ============= WORKER WHICH IS PASSED TO THREAD ===================== // ==================================================================== class QmitkFiberGenerateRandomWorker : public QObject { Q_OBJECT public: QmitkFiberGenerateRandomWorker( QThread*, Package4WorkingThread ); public slots: void run(); private: Package4WorkingThread m_itemPackage; QThread* m_hostingThread; }; +// ==================================================================== +// ============= WORKER WHICH IS PASSED TO THREAD ===================== +// ==================================================================== +class QmitkFiberFeederFAWorker : public QObject +{ + Q_OBJECT + +public: + QmitkFiberFeederFAWorker( QThread*, Package4WorkingThread ); + + public slots: + void run(); + +private: + Package4WorkingThread m_itemPackage; + QThread* m_hostingThread; + + +}; + +// ==================================================================== +// ============= WORKER WHICH IS PASSED TO THREAD ===================== +// ==================================================================== +class QmitkFiberExtractorWorker : public QObject +{ + Q_OBJECT + +public: + QmitkFiberExtractorWorker( QThread*, Package4WorkingThread ); + +public slots: + void run(); + +private: + Package4WorkingThread m_itemPackage; + QThread* m_hostingThread; + +}; + +// ==================================================================== +// ============= WORKER WHICH IS PASSED TO THREAD ===================== +// ==================================================================== class QmitkFiberThreadMonitorWorker : public QObject { Q_OBJECT public: QmitkFiberThreadMonitorWorker( QThread*, Package4WorkingThread ); void initializeMonitor(); void threadForFiberProcessingStarted(); void threadForFiberProcessingFinished(); void threadForFiberProcessingTerminated(); void setThreadStatus(QString); public slots: void run(); void fancyMonitorInitialization(); void fancyMonitorInitializationFinalPos(); void fancyMonitorInitializationMask(); void fancyTextFading_threadStarted(); void fancyTextFading_threadFinished(); void fancyTextFading_threadTerminated(); private: Package4WorkingThread m_itemPackage; QThread* m_hostingThread; QTimer* m_thtimer_initMonitor; QTimer* m_thtimer_initMonitorSetFinalPosition; QTimer* m_thtimer_initMonitorSetMasks; QTimer* m_thtimer_threadStarted; QTimer* m_thtimer_threadFinished; QTimer* m_thtimer_threadTerminated; // flags for fancy fading bool m_decreaseOpacity_threadStarted; bool m_decreaseOpacity_threadFinished; bool m_decreaseOpacity_threadTerminated; // members for fancy animation int m_pixelstepper; int m_steppingDistance; }; // strings to display fiber_thread monitor const QString FBX_STATUS_IDLE = "idle"; const QString FBX_STATUS_STARTED = "starting"; const QString FBX_STATUS_RUNNING = "running"; // ========= HERE STARTS THE ACTUAL FIBERBUNDLE DEVELOPER VIEW ======= const QString FIB_RADIOBUTTON_DIRECTION_RANDOM = "radioButton_directionRandom"; const QString FIB_RADIOBUTTON_DIRECTION_X = "radioButton_directionX"; const QString FIB_RADIOBUTTON_DIRECTION_Y = "radioButton_directionY"; const QString FIB_RADIOBUTTON_DIRECTION_Z = "radioButton_directionZ"; /*! \brief QmitkFiberBundleView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkFiberBundleDeveloperView : 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; QmitkFiberBundleDeveloperView(); virtual ~QmitkFiberBundleDeveloperView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); virtual void Activated(); protected slots: void DoGenerateFibers(); void DoGenerateFiberIDs(); + void DoExtractFibers(); void DoUpdateGenerateFibersWidget(); void SelectionChangedToolBox(int); void DoMonitorFiberThreads(int); + void DoSetFAValues(); + void DoSetFAMap(); void DoColorFibers(); + void DoGatherColorCodings(); + void SetCurrentColorCoding(int); + void ActionDrawEllipseTriggered(); //SLOTS FOR THREADS void BeforeThread_IdGenerate(); void AfterThread_IdGenerate(); void BeforeThread_GenerateFibersRandom(); void AfterThread_GenerateFibersRandom(); + void BeforeThread_FiberSetFA(); + void AfterThread_FiberSetFA(); void BeforeThread_FiberColorCoding(); void AfterThread_FiberColorCoding(); + void BeforeThread_FiberExtraction(); + void AfterThread_FiberExtraction(); //SLOTS FOR TIMERS void UpdateFiberIDTimer(); void UpdateGenerateRandomFibersTimer(); void UpdateColorFibersTimer(); + void UpdateExtractFibersTimer(); + void UpdateSetFAValuesTimer(); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkFiberBundleDeveloperViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; private: /* METHODS GENERATING FIBERSTRUCTURES */ void GenerateVtkFibersRandom(); vtkSmartPointer GenerateVtkFibersDirectionX(); vtkSmartPointer GenerateVtkFibersDirectionY(); vtkSmartPointer GenerateVtkFibersDirectionZ(); - void PutFibersToDataStorage( vtkPolyData* ); - + void PutFibersToDataStorage( vtkSmartPointer ); + void PutFigureToDataStorage(mitk::PlanarFigure* , const QString& ); /* METHODS FOR FIBER PROCESSING OR PREPROCESSING */ /* HELPERMETHODS */ mitk::Geometry3D::Pointer GenerateStandardGeometryForMITK(); void ResetFiberInfoWidget(); void FeedFiberInfoWidget(); void FBXDependendGUIElementsConfigurator(); - + void SetGeneratedFBX(); - //contains the selected FiberBundle - //mitk::FiberBundleX* m_FiberBundleX; + //contains the selected FiberBundle, PlanarFigure + mitk::DataNode::Pointer m_FiberBundleNode; mitk::WeakPointer m_FiberBundleX; + mitk::PlanarFigure::Pointer m_PlanarFigure; // radiobutton groups QVector< QRadioButton* > m_DirectionRadios; QVector< QRadioButton* > m_FARadios; QVector< QRadioButton* > m_GARadios; // Thread based Workers which do some processing of fibers QmitkFiberIDWorker* m_FiberIDGenerator; QmitkFiberGenerateRandomWorker* m_GeneratorFibersRandom; + QmitkFiberFeederFAWorker* m_FiberFeederFASlave; QmitkFiberColoringWorker* m_FiberColoringSlave; + QmitkFiberExtractorWorker* m_FiberExtractor; QThread* m_hostThread; QThread* m_monitorThread; bool m_threadInProgress; mitk::DataNode::Pointer m_MonitorNode; QmitkFiberThreadMonitorWorker *m_fiberThreadMonitorWorker; bool m_fiberMonitorIsOn; + + // counters for ROI nodes + int m_CircleCounter; + + mitk::DataNode::Pointer m_FANode; + + // flag to bypass signal from qcombobox "index changed(int)" + bool m_suppressSignal; }; #endif // _QMITKFIBERTRACKINGVIEW_H_INCLUDED diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperViewControls.ui b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperViewControls.ui index 1aca09bed3..0bbd9df097 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperViewControls.ui +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberBundleDeveloperViewControls.ui @@ -1,927 +1,1258 @@ QmitkFiberBundleDeveloperViewControls 0 0 - 539 - 966 + 467 + 570 Form 12 50 false 1 0 0 - 500 - 449 + 428 + 540 Fiber Generator 0 Fiber Bundles Generate Fiberbundle Fiber Parameters 11 Total number of Fibers 10 999999999 100 - - - - Qt::Horizontal - - - - 40 - 20 - - - - 11 Distribution Radius 10 9999 100 11 Fiber Length Max (points) 10 50 11 Fiber Length Min (points) 10 10 + + + + Qt::Horizontal + + + + 40 + 20 + + + + - labelFibersTotal - boxFiberNumbers - horizontalSpacer_3 - labelDistrRadius - boxDistributionRadius - labelFiberMaxLength - boxFiberMaxLength - labelFiberMinLength - boxFiberMinLength 11 Fiber Orientation along Z Axis along X Axis random true along Y Axis Qt::Horizontal 40 20 Qt::Vertical 20 40 QFrame::StyledPanel QFrame::Raised 10 Time: 10 - DWI Values GA Values no values true nothing yet implemented 11 FA Values const value false 10 1.000000000000000 0.100000000000000 1.000000000000000 random range false 10 1.000000000000000 0.100000000000000 no values true false 10 1.000000000000000 0.100000000000000 Qt::Vertical 20 40 Page Select a FiberBundle in Datamanager Qt::Vertical 20 40 0 0 - 500 - 403 + 445 + 409 Fiber Processor - + - 0 + 1 + + + Feeder + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Add FA Values to FiberBundle + + + + QFormLayout::FieldsStayAtSizeHint + + + + + FA Map + + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + 0 + + + + + => + + + + + + + N/A + + + + + + + execute + + + + + + + + + + - + + + + + + + Timer: + + + + + + + + Colors - Fiber Coloring + Generate Fiber Coloring QFrame::StyledPanel QFrame::Raised Orientation based true - FA based + FA as Color + + + + + + + FA as Opacity + + + + + + + Custom Colorcode Fibers QFrame::StyledPanel QFrame::Raised QFormLayout::FieldsStayAtSizeHint 10 Timer: 10 - Qt::Horizontal 40 20 - + Qt::Vertical 20 40 + + + + Fiber Color Information + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Shape Qt::Vertical 20 40 Fiber Smoothing Smooth Fibers QFrame::StyledPanel QFrame::Raised static value relative in% false 10 none true false 10 9999 Qt::Horizontal 40 20 vtkFilters Tubes vtkDecimatePro vtkSmoothPolyDataFilter Cutting - - - - Step1: Generate Fibers IDs in FBX - - - - + Qt::Vertical 20 40 - - - - QFrame::StyledPanel - - - QFrame::Raised + + + + Step 3 - - - QFormLayout::FieldsStayAtSizeHint - + - - - - 10 - + + + Extract Fibers by ROI + + + + - Timer: + Extract Fibers - - - - - 10 - + + + + QFrame::StyledPanel - - - + + QFrame::Raised + + + + + + 10 + + + + Timer: + + + + + + + + 10 + + + + - + + + + - - - Execute Step1 + + + Step 1 + + + + + + Generate Fibers IDs in FBX + + + + + + + Generate Fiber Ids + + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + QFormLayout::FieldsStayAtSizeHint + + + + + + 10 + + + + Timer: + + + + + + + + 10 + + + + - + + + + + + + + + + + + + Step 2 + + + + + Define ROI + + + + + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + + + 30 + 30 + + + + Draw circular ROI + + + + + + + :/QmitkDiffusionImaging/circle.png:/QmitkDiffusionImaging/circle.png + + + + 32 + 32 + + + + false + + + true + + + + + + + + 30 + 30 + + + + Draw polygonal ROI + + + + + + + :/QmitkDiffusionImaging/polygon.png:/QmitkDiffusionImaging/polygon.png + + + + 32 + 32 + + + + true + + + true + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + 0 0 - 515 - 348 + 443 + 156 FiberInfo General Information Number of Fibers: - Number of Points: - Qt::Vertical 20 40 Qt::Horizontal Monitor Fiber Threading in mitkRenderWindow4 Qt::Vertical 20 40 diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.cpp b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.cpp index 6077e49677..42c2c925ae 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.cpp +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.cpp @@ -1,1853 +1,1720 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ Version: $Revision: 21975 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Blueberry #include #include - - // Qmitk #include "QmitkFiberProcessingView.h" -#include "QmitkStdMultiWidget.h" +#include // Qt #include -//MITK -#include "mitkNodePredicateProperty.h" -//#include "mitkNodePredicateAND.h" -#include "mitkImageCast.h" - -#include "mitkPointSet.h" - - -#include "mitkPlanarCircle.h" -#include "mitkPlanarPolygon.h" +// MITK +#include +#include +#include +#include +#include #include -#include "mitkPlanarFigureInteractor.h" -#include "mitkGlobalInteraction.h" +#include +#include #include +#include +#include +#include + +// ITK #include #include #include #include -#include -#include -#include +#include #include +#include const std::string QmitkFiberProcessingView::VIEW_ID = "org.mitk.views.fiberprocessing"; const std::string id_DataManager = "org.mitk.views.datamanager"; -using namespace berry; using namespace mitk; -struct FboSelListener : ISelectionListener -{ - - berryObjectMacro(FboSelListener); - - FboSelListener(QmitkFiberProcessingView* view) - { - m_View = view; - } - - void DoSelectionChanged(ISelection::ConstPointer selection) - { - // save current selection in member variable - m_View->m_CurrentSelection = selection.Cast(); - - // do something with the selected items - if(m_View->m_CurrentSelection) - { - bool foundFiberBundle = false; - std::string classname = "FiberBundle"; - - // iterate selection - for (IStructuredSelection::iterator i = m_View->m_CurrentSelection->Begin(); - i != m_View->m_CurrentSelection->End(); ++i) - { - - // extract datatree node - if (mitk::DataNodeObject::Pointer nodeObj = i->Cast()) - { - mitk::DataNode::Pointer node = nodeObj->GetDataNode(); - std::string fname = node->GetData()->GetNameOfClass(); - if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) - { - foundFiberBundle = true; - } - } - } - - if(foundFiberBundle) - { - m_View->m_Controls->m_CircleButton->setEnabled(true); - m_View->m_Controls->m_PolygonButton->setEnabled(true); - m_View->m_Controls->m_RectangleButton->setEnabled(true); - } - else{ - m_View->m_Controls->m_CircleButton->setEnabled(false); - m_View->m_Controls->m_PolygonButton->setEnabled(false); - m_View->m_Controls->m_RectangleButton->setEnabled(false); - } - } - } - - void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) - { - // check, if selection comes from datamanager - if (part) - { - QString partname(part->GetPartName().c_str()); - if(partname.compare("Datamanager")==0) - { - - // apply selection - DoSelectionChanged(selection); - - } - } - } - - QmitkFiberProcessingView* m_View; -}; - - - QmitkFiberProcessingView::QmitkFiberProcessingView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_EllipseCounter(0) , m_PolygonCounter(0) -//, m_SelectedFBNodes( NULL ) -//, m_SelectedPFNodes(0) , m_UpsamplingFactor(5) { } // Destructor QmitkFiberProcessingView::~QmitkFiberProcessingView() { } - void QmitkFiberProcessingView::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::QmitkFiberProcessingViewControls; m_Controls->setupUi( parent ); m_Controls->doExtractFibersButton->setDisabled(true); m_Controls->PFCompoANDButton->setDisabled(true); m_Controls->PFCompoORButton->setDisabled(true); m_Controls->PFCompoNOTButton->setDisabled(true); m_Controls->m_CircleButton->setEnabled(false); m_Controls->m_PolygonButton->setEnabled(false); m_Controls->m_RectangleButton->setEnabled(false); m_Controls->m_RectangleButton->setVisible(false); connect( m_Controls->doExtractFibersButton, SIGNAL(clicked()), this, SLOT(DoFiberExtraction()) ); - //connect( m_Controls->comboBox_fiberAlgo, SIGNAL(selected()), this, SLOT(handleAlgoSelection() ); connect( m_Controls->m_CircleButton, SIGNAL( clicked() ), this, SLOT( ActionDrawEllipseTriggered() ) ); connect( m_Controls->m_PolygonButton, SIGNAL( clicked() ), this, SLOT( ActionDrawPolygonTriggered() ) ); connect(m_Controls->PFCompoANDButton, SIGNAL(clicked()), this, SLOT(GenerateAndComposite()) ); connect(m_Controls->PFCompoORButton, SIGNAL(clicked()), this, SLOT(GenerateOrComposite()) ); connect(m_Controls->PFCompoNOTButton, SIGNAL(clicked()), this, SLOT(GenerateNotComposite()) ); connect(m_Controls->m_JoinBundles, SIGNAL(clicked()), this, SLOT(JoinBundles()) ); connect(m_Controls->m_SubstractBundles, SIGNAL(clicked()), this, SLOT(SubstractBundles()) ); - connect(m_Controls->m_GenerateROIImage, SIGNAL(clicked()), this, SLOT(GenerateROIImage()) ); + connect(m_Controls->m_GenerateRoiImage, SIGNAL(clicked()), this, SLOT(GenerateRoiImage()) ); - connect( m_Controls->m_GenerationStartButton, SIGNAL(clicked()), this, SLOT(GenerationStart()) ); + connect(m_Controls->m_Extract3dButton, SIGNAL(clicked()), this, SLOT(Extract3d())); + connect( m_Controls->m_ProcessFiberBundleButton, SIGNAL(clicked()), this, SLOT(ProcessSelectedBundles()) ); } - - m_SelListener = berry::ISelectionListener::Pointer(new FboSelListener(this)); - this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddPostSelectionListener(/*"org.mitk.views.datamanager",*/ m_SelListener); - berry::ISelection::ConstPointer sel( - this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection("org.mitk.views.datamanager")); - m_CurrentSelection = sel.Cast(); - m_SelListener.Cast()->DoSelectionChanged(sel); } -void QmitkFiberProcessingView::GenerateROIImage(){ +void QmitkFiberProcessingView::Extract3d() +{ + std::vector nodes = this->GetDataManagerSelection(); + if (nodes.empty()) + return; - if (m_Image.IsNull() || m_SelectedPF.empty()) + mitk::FiberBundleX::Pointer fib = mitk::FiberBundleX::New(); + mitk::Surface::Pointer roi = mitk::Surface::New(); + bool fibB = false; + bool roiB = false; + for (int i=0; i(nodes.at(i)->GetData())) + { + fib = dynamic_cast(nodes.at(i)->GetData()); + fibB = true; + } + else if (dynamic_cast(nodes.at(i)->GetData())) + { + roi = dynamic_cast(nodes.at(i)->GetData()); + roiB = true; + } + } + if (!fibB) return; + if (!roiB) + return; + + vtkSmartPointer polyRoi = roi->GetVtkPolyData(); + vtkSmartPointer polyFib = fib->GetFiberPolyData(); + + vtkSmartPointer selectEnclosedPoints = vtkSmartPointer::New(); + selectEnclosedPoints->SetInput(polyFib); + selectEnclosedPoints->SetSurface(polyRoi); + selectEnclosedPoints->Update(); - mitk::Image* image = const_cast(m_Image.GetPointer()); + vtkSmartPointer newPoly = vtkSmartPointer::New(); + vtkSmartPointer newCellArray = vtkSmartPointer::New(); + vtkSmartPointer newPoints = vtkSmartPointer::New(); - MaskImage3DType::Pointer temp = MaskImage3DType::New(); - mitk::CastToItkImage(m_Image, temp); + vtkSmartPointer newPolyComplement = vtkSmartPointer::New(); + vtkSmartPointer newCellArrayComplement = vtkSmartPointer::New(); + vtkSmartPointer newPointsComplement = vtkSmartPointer::New(); - m_PlanarFigureImage = MaskImage3DType::New(); + vtkSmartPointer vLines = polyFib->GetLines(); + + vLines->InitTraversal(); + int numberOfLines = vLines->GetNumberOfCells(); + // each line + for (int j=0; jGetNextCell ( numPoints, points ); + bool isPassing = false; + + // each point of this line + for (int k=0; kIsInside(points[k])) + { + isPassing = true; + // fill new polydata + vtkSmartPointer container = vtkSmartPointer::New(); + for (int k=0; kGetPoint(points[k]); + vtkIdType pointId = newPoints->InsertNextPoint(point); + container->GetPointIds()->InsertNextId(pointId); + } + newCellArray->InsertNextCell(container); + break; + } + } + if (!isPassing) + { + vtkSmartPointer container = vtkSmartPointer::New(); + for (int k=0; kGetPoint(points[k]); + vtkIdType pointId = newPointsComplement->InsertNextPoint(point); + container->GetPointIds()->InsertNextId(pointId); + } + newCellArrayComplement->InsertNextCell(container); + } + } + + newPoly->SetPoints(newPoints); + newPoly->SetLines(newCellArray); + mitk::FiberBundleX::Pointer fb = mitk::FiberBundleX::New(newPoly); + DataNode::Pointer newNode = DataNode::New(); + newNode->SetData(fb); + newNode->SetName("passing surface"); + GetDefaultDataStorage()->Add(newNode); + + newPolyComplement->SetPoints(newPointsComplement); + newPolyComplement->SetLines(newCellArrayComplement); + mitk::FiberBundleX::Pointer fbComplement = mitk::FiberBundleX::New(newPolyComplement); + DataNode::Pointer newNodeComplement = DataNode::New(); + newNodeComplement->SetData(fbComplement); + newNodeComplement->SetName("not passing surface"); + GetDefaultDataStorage()->Add(newNodeComplement); +} +void QmitkFiberProcessingView::GenerateRoiImage(){ + + if (m_SelectedImage.IsNull() || m_SelectedPF.empty()) + return; + + mitk::Image* image = const_cast(m_SelectedImage.GetPointer()); + + UCharImageType::Pointer temp = UCharImageType::New(); + mitk::CastToItkImage(m_SelectedImage, temp); + + m_PlanarFigureImage = UCharImageType::New(); m_PlanarFigureImage->SetSpacing( temp->GetSpacing() ); // Set the image spacing m_PlanarFigureImage->SetOrigin( temp->GetOrigin() ); // Set the image origin m_PlanarFigureImage->SetDirection( temp->GetDirection() ); // Set the image direction m_PlanarFigureImage->SetRegions( temp->GetLargestPossibleRegion() ); m_PlanarFigureImage->Allocate(); m_PlanarFigureImage->FillBuffer( 0 ); - for (int i=0; iInitializeByItk(m_PlanarFigureImage.GetPointer()); tmpImage->SetVolume(m_PlanarFigureImage->GetBufferPointer()); node->SetData(tmpImage); node->SetName("ROI Image"); this->GetDefaultDataStorage()->Add(node); } void QmitkFiberProcessingView::CompositeExtraction(mitk::DataNode::Pointer node, mitk::Image* image) { if (dynamic_cast(node.GetPointer()->GetData()) && !dynamic_cast(node.GetPointer()->GetData())) { m_PlanarFigure = dynamic_cast(node.GetPointer()->GetData()); AccessFixedDimensionByItk_2( image, InternalReorientImagePlane, 3, m_PlanarFigure->GetGeometry(), -1); // itk::Image< unsigned char, 3 >::Pointer outimage = itk::Image< unsigned char, 3 >::New(); // outimage->SetSpacing( m_PlanarFigure->GetGeometry()->GetSpacing()/m_UpsamplingFactor ); // Set the image spacing // mitk::Point3D origin = m_PlanarFigure->GetGeometry()->GetOrigin(); // mitk::Point3D indexOrigin; // m_PlanarFigure->GetGeometry()->WorldToIndex(origin, indexOrigin); // indexOrigin[0] = indexOrigin[0] - .5 * (1.0-1.0/m_UpsamplingFactor); // indexOrigin[1] = indexOrigin[1] - .5 * (1.0-1.0/m_UpsamplingFactor); // indexOrigin[2] = indexOrigin[2] - .5 * (1.0-1.0/m_UpsamplingFactor); // mitk::Point3D newOrigin; // m_PlanarFigure->GetGeometry()->IndexToWorld(indexOrigin, newOrigin); // outimage->SetOrigin( newOrigin ); // Set the image origin // itk::Matrix matrix; // for (int i=0; i<3; i++) // for (int j=0; j<3; j++) // matrix[j][i] = m_PlanarFigure->GetGeometry()->GetMatrixColumn(i)[j]/m_PlanarFigure->GetGeometry()->GetSpacing().GetElement(i); // outimage->SetDirection( matrix ); // Set the image direction // itk::ImageRegion<3> upsampledRegion; // upsampledRegion.SetSize(0, m_PlanarFigure->GetGeometry()->GetParametricExtentInMM(0)/m_PlanarFigure->GetGeometry()->GetSpacing()[0]); // upsampledRegion.SetSize(1, m_PlanarFigure->GetGeometry()->GetParametricExtentInMM(1)/m_PlanarFigure->GetGeometry()->GetSpacing()[1]); // upsampledRegion.SetSize(2, 1); // typename itk::Image< unsigned char, 3 >::RegionType::SizeType upsampledSize = upsampledRegion.GetSize(); // for (unsigned int n = 0; n < 2; n++) // { // upsampledSize[n] = upsampledSize[n] * m_UpsamplingFactor; // } // upsampledRegion.SetSize( upsampledSize ); // outimage->SetRegions( upsampledRegion ); // outimage->Allocate(); // this->m_InternalImage = mitk::Image::New(); // this->m_InternalImage->InitializeByItk( outimage.GetPointer() ); // this->m_InternalImage->SetVolume( outimage->GetBufferPointer() ); AccessFixedDimensionByItk_2( m_InternalImage, InternalCalculateMaskFromPlanarFigure, 3, 2, node->GetName() ); } } template < typename TPixel, unsigned int VImageDimension > void QmitkFiberProcessingView::InternalReorientImagePlane( const itk::Image< TPixel, VImageDimension > *image, mitk::Geometry3D* planegeo3D, int additionalIndex ) { MITK_INFO << "InternalReorientImagePlane() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::Image< float, VImageDimension > FloatImageType; typedef itk::ResampleImageFilter ResamplerType; typename ResamplerType::Pointer resampler = ResamplerType::New(); mitk::PlaneGeometry* planegeo = dynamic_cast(planegeo3D); float upsamp = m_UpsamplingFactor; float gausssigma = 0.5; // Spacing typename ResamplerType::SpacingType spacing = planegeo->GetSpacing(); spacing[0] = image->GetSpacing()[0] / upsamp; spacing[1] = image->GetSpacing()[1] / upsamp; spacing[2] = image->GetSpacing()[2]; resampler->SetOutputSpacing( spacing ); // Size typename ResamplerType::SizeType size; size[0] = planegeo->GetParametricExtentInMM(0) / spacing[0]; size[1] = planegeo->GetParametricExtentInMM(1) / spacing[1]; size[2] = 1; resampler->SetSize( size ); // Origin typename mitk::Point3D orig = planegeo->GetOrigin(); typename mitk::Point3D corrorig; planegeo3D->WorldToIndex(orig,corrorig); corrorig[0] += 0.5/upsamp; corrorig[1] += 0.5/upsamp; corrorig[2] += 0; planegeo3D->IndexToWorld(corrorig,corrorig); resampler->SetOutputOrigin(corrorig ); // Direction typename ResamplerType::DirectionType direction; typename mitk::AffineTransform3D::MatrixType matrix = planegeo->GetIndexToWorldTransform()->GetMatrix(); for(int c=0; cSetOutputDirection( direction ); // Gaussian interpolation if(gausssigma != 0) { double sigma[3]; for( unsigned int d = 0; d < 3; d++ ) { sigma[d] = gausssigma * image->GetSpacing()[d]; } double alpha = 2.0; typedef itk::GaussianInterpolateImageFunction GaussianInterpolatorType; typename GaussianInterpolatorType::Pointer interpolator = GaussianInterpolatorType::New(); interpolator->SetInputImage( image ); interpolator->SetParameters( sigma, alpha ); resampler->SetInterpolator( interpolator ); } else { // typedef typename itk::BSplineInterpolateImageFunction // InterpolatorType; typedef typename itk::LinearInterpolateImageFunction InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage( image ); resampler->SetInterpolator( interpolator ); } // Other resampling options resampler->SetInput( image ); resampler->SetDefaultPixelValue(0); MITK_INFO << "Resampling requested image plane ... "; resampler->Update(); MITK_INFO << " ... done"; if(additionalIndex < 0) { this->m_InternalImage = mitk::Image::New(); this->m_InternalImage->InitializeByItk( resampler->GetOutput() ); this->m_InternalImage->SetVolume( resampler->GetOutput()->GetBufferPointer() ); } } template < typename TPixel, unsigned int VImageDimension > void QmitkFiberProcessingView::InternalCalculateMaskFromPlanarFigure( itk::Image< TPixel, VImageDimension > *image, unsigned int axis, std::string nodeName ) { MITK_INFO << "InternalCalculateMaskFromPlanarFigure() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; - typedef itk::CastImageFilter< ImageType, MaskImage3DType > CastFilterType; + typedef itk::CastImageFilter< ImageType, UCharImageType > CastFilterType; // Generate mask image as new image with same header as input image and // initialize with "1". - MaskImage3DType::Pointer newMaskImage = MaskImage3DType::New(); + UCharImageType::Pointer newMaskImage = UCharImageType::New(); newMaskImage->SetSpacing( image->GetSpacing() ); // Set the image spacing newMaskImage->SetOrigin( image->GetOrigin() ); // Set the image origin newMaskImage->SetDirection( image->GetDirection() ); // Set the image direction newMaskImage->SetRegions( image->GetLargestPossibleRegion() ); newMaskImage->Allocate(); newMaskImage->FillBuffer( 1 ); // Generate VTK polygon from (closed) PlanarFigure polyline // (The polyline points are shifted by -0.5 in z-direction to make sure // that the extrusion filter, which afterwards elevates all points by +0.5 // in z-direction, creates a 3D object which is cut by the the plane z=0) const Geometry2D *planarFigureGeometry2D = m_PlanarFigure->GetGeometry2D(); const PlanarFigure::PolyLineType planarFigurePolyline = m_PlanarFigure->GetPolyLine( 0 ); const Geometry3D *imageGeometry3D = m_InternalImage->GetGeometry( 0 ); vtkPolyData *polyline = vtkPolyData::New(); polyline->Allocate( 1, 1 ); // Determine x- and y-dimensions depending on principal axis int i0, i1; switch ( axis ) { case 0: i0 = 1; i1 = 2; break; case 1: i0 = 0; i1 = 2; break; case 2: default: i0 = 0; i1 = 1; break; } // Create VTK polydata object of polyline contour vtkPoints *points = vtkPoints::New(); PlanarFigure::PolyLineType::const_iterator it; std::vector indices; unsigned int numberOfPoints = 0; for ( it = planarFigurePolyline.begin(); it != planarFigurePolyline.end(); ++it ) { Point3D point3D; // Convert 2D point back to the local index coordinates of the selected // image Point2D point2D = it->Point; planarFigureGeometry2D->WorldToIndex(point2D, point2D); point2D[0] -= 0.5/m_UpsamplingFactor; point2D[1] -= 0.5/m_UpsamplingFactor; planarFigureGeometry2D->IndexToWorld(point2D, point2D); planarFigureGeometry2D->Map( point2D, point3D ); // Polygons (partially) outside of the image bounds can not be processed // further due to a bug in vtkPolyDataToImageStencil if ( !imageGeometry3D->IsInside( point3D ) ) { float bounds[2] = {0,0}; bounds[0] = this->m_InternalImage->GetLargestPossibleRegion().GetSize().GetElement(i0); bounds[1] = this->m_InternalImage->GetLargestPossibleRegion().GetSize().GetElement(i1); imageGeometry3D->WorldToIndex( point3D, point3D ); // if (point3D[i0]<0) // point3D[i0] = 0.5; // else if (point3D[i0]>bounds[0]) // point3D[i0] = bounds[0]-0.5; // if (point3D[i1]<0) // point3D[i1] = 0.5; // else if (point3D[i1]>bounds[1]) // point3D[i1] = bounds[1]-0.5; if (point3D[i0]<0) point3D[i0] = 0.0; else if (point3D[i0]>bounds[0]) point3D[i0] = bounds[0]-0.001; if (point3D[i1]<0) point3D[i1] = 0.0; else if (point3D[i1]>bounds[1]) point3D[i1] = bounds[1]-0.001; points->InsertNextPoint( point3D[i0], point3D[i1], -0.5 ); numberOfPoints++; } else { imageGeometry3D->WorldToIndex( point3D, point3D ); // Add point to polyline array points->InsertNextPoint( point3D[i0], point3D[i1], -0.5 ); numberOfPoints++; } } polyline->SetPoints( points ); points->Delete(); vtkIdType *ptIds = new vtkIdType[numberOfPoints]; for ( vtkIdType i = 0; i < numberOfPoints; ++i ) { ptIds[i] = i; } polyline->InsertNextCell( VTK_POLY_LINE, numberOfPoints, ptIds ); // Extrude the generated contour polygon vtkLinearExtrusionFilter *extrudeFilter = vtkLinearExtrusionFilter::New(); extrudeFilter->SetInput( polyline ); extrudeFilter->SetScaleFactor( 1 ); extrudeFilter->SetExtrusionTypeToNormalExtrusion(); extrudeFilter->SetVector( 0.0, 0.0, 1.0 ); // Make a stencil from the extruded polygon vtkPolyDataToImageStencil *polyDataToImageStencil = vtkPolyDataToImageStencil::New(); polyDataToImageStencil->SetInput( extrudeFilter->GetOutput() ); // Export from ITK to VTK (to use a VTK filter) - typedef itk::VTKImageImport< MaskImage3DType > ImageImportType; - typedef itk::VTKImageExport< MaskImage3DType > ImageExportType; + typedef itk::VTKImageImport< UCharImageType > ImageImportType; + typedef itk::VTKImageExport< UCharImageType > ImageExportType; typename ImageExportType::Pointer itkExporter = ImageExportType::New(); itkExporter->SetInput( newMaskImage ); vtkImageImport *vtkImporter = vtkImageImport::New(); this->ConnectPipelines( itkExporter, vtkImporter ); vtkImporter->Update(); // Apply the generated image stencil to the input image vtkImageStencil *imageStencilFilter = vtkImageStencil::New(); imageStencilFilter->SetInputConnection( vtkImporter->GetOutputPort() ); imageStencilFilter->SetStencil( polyDataToImageStencil->GetOutput() ); imageStencilFilter->ReverseStencilOff(); imageStencilFilter->SetBackgroundValue( 0 ); imageStencilFilter->Update(); // Export from VTK back to ITK vtkImageExport *vtkExporter = vtkImageExport::New(); vtkExporter->SetInputConnection( imageStencilFilter->GetOutputPort() ); vtkExporter->Update(); typename ImageImportType::Pointer itkImporter = ImageImportType::New(); this->ConnectPipelines( vtkExporter, itkImporter ); itkImporter->Update(); // calculate cropping bounding box m_InternalImageMask3D = itkImporter->GetOutput(); m_InternalImageMask3D->SetDirection(image->GetDirection()); - itk::ImageRegionConstIterator + itk::ImageRegionConstIterator itmask(m_InternalImageMask3D, m_InternalImageMask3D->GetLargestPossibleRegion()); itk::ImageRegionIterator itimage(image, image->GetLargestPossibleRegion()); itmask = itmask.Begin(); itimage = itimage.Begin(); typename ImageType::SizeType lowersize = {{9999999999,9999999999,9999999999}}; typename ImageType::SizeType uppersize = {{0,0,0}}; while( !itmask.IsAtEnd() ) { if(itmask.Get() == 0) { itimage.Set(0); } else { typename ImageType::IndexType index = itimage.GetIndex(); typename ImageType::SizeType signedindex; signedindex[0] = index[0]; signedindex[1] = index[1]; signedindex[2] = index[2]; lowersize[0] = signedindex[0] < lowersize[0] ? signedindex[0] : lowersize[0]; lowersize[1] = signedindex[1] < lowersize[1] ? signedindex[1] : lowersize[1]; lowersize[2] = signedindex[2] < lowersize[2] ? signedindex[2] : lowersize[2]; uppersize[0] = signedindex[0] > uppersize[0] ? signedindex[0] : uppersize[0]; uppersize[1] = signedindex[1] > uppersize[1] ? signedindex[1] : uppersize[1]; uppersize[2] = signedindex[2] > uppersize[2] ? signedindex[2] : uppersize[2]; } ++itmask; ++itimage; } typename ImageType::IndexType index; index[0] = lowersize[0]; index[1] = lowersize[1]; index[2] = lowersize[2]; typename ImageType::SizeType size; size[0] = uppersize[0] - lowersize[0] + 1; size[1] = uppersize[1] - lowersize[1] + 1; size[2] = uppersize[2] - lowersize[2] + 1; itk::ImageRegion<3> cropRegion = itk::ImageRegion<3>(index, size); // crop internal mask - typedef itk::RegionOfInterestImageFilter< MaskImage3DType, MaskImage3DType > ROIMaskFilterType; + typedef itk::RegionOfInterestImageFilter< UCharImageType, UCharImageType > ROIMaskFilterType; typename ROIMaskFilterType::Pointer roi2 = ROIMaskFilterType::New(); roi2->SetRegionOfInterest(cropRegion); roi2->SetInput(m_InternalImageMask3D); roi2->Update(); m_InternalImageMask3D = roi2->GetOutput(); Image::Pointer tmpImage = Image::New(); tmpImage->InitializeByItk(m_InternalImageMask3D.GetPointer()); tmpImage->SetVolume(m_InternalImageMask3D->GetBufferPointer()); Image::Pointer tmpImage2 = Image::New(); tmpImage2->InitializeByItk(m_PlanarFigureImage.GetPointer()); const Geometry3D *pfImageGeometry3D = tmpImage2->GetGeometry( 0 ); const Geometry3D *intImageGeometry3D = tmpImage->GetGeometry( 0 ); - typedef itk::ImageRegionIteratorWithIndex IteratorType; + typedef itk::ImageRegionIteratorWithIndex IteratorType; IteratorType imageIterator (m_InternalImageMask3D, m_InternalImageMask3D->GetRequestedRegion()); imageIterator.GoToBegin(); while ( !imageIterator.IsAtEnd() ) { unsigned char val = imageIterator.Value(); if (val>0) { itk::Index<3> index = imageIterator.GetIndex(); Point3D point; point[0] = index[0]; point[1] = index[1]; point[2] = index[2]; intImageGeometry3D->IndexToWorld(point, point); pfImageGeometry3D->WorldToIndex(point, point); point[i0] += 0.5; point[i1] += 0.5; index[0] = point[0]; index[1] = point[1]; index[2] = point[2]; m_PlanarFigureImage->SetPixel(index, 1); } ++imageIterator; } // Clean up VTK objects polyline->Delete(); extrudeFilter->Delete(); polyDataToImageStencil->Delete(); vtkImporter->Delete(); imageStencilFilter->Delete(); //vtkExporter->Delete(); // TODO: crashes when outcommented; memory leak?? delete[] ptIds; } void QmitkFiberProcessingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkFiberProcessingView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } /* OnSelectionChanged is registered to SelectionService, therefore no need to implement SelectionService Listener explicitly */ -void QmitkFiberProcessingView::OnSelectionChanged( std::vector nodes ) +void QmitkFiberProcessingView::UpdateGui() { - if ( !this->IsVisible() ) - return; - - if (nodes.empty()) + // are fiber bundles selected? + if ( m_SelectedFB.empty() ) { - m_Controls->doExtractFibersButton->setDisabled(true); - m_Controls->PFCompoANDButton->setDisabled(true); - m_Controls->PFCompoORButton->setDisabled(true); - m_Controls->PFCompoNOTButton->setDisabled(true); m_Controls->m_JoinBundles->setEnabled(false); m_Controls->m_SubstractBundles->setEnabled(false); - m_Controls->m_GenerationStartButton->setEnabled(false); + m_Controls->m_ProcessFiberBundleButton->setEnabled(false); + m_Controls->doExtractFibersButton->setEnabled(false); } + else + { + m_Controls->m_ProcessFiberBundleButton->setEnabled(true); - //reset existing Vectors containing FiberBundles and PlanarFigures from a previous selection - m_SelectedFB.clear(); - m_SelectedPF.clear(); - m_Image = NULL; + // one bundle and one planar figure needed to extract fibers + if (!m_SelectedPF.empty()) + m_Controls->doExtractFibersButton->setEnabled(true); - for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) - { - mitk::DataNode::Pointer node = *it; - if ( dynamic_cast(node->GetData()) ) + // more than two bundles needed to join/subtract + if (m_SelectedFB.size() > 1) { - m_SelectedFB.push_back(node); + m_Controls->m_JoinBundles->setEnabled(true); + m_Controls->m_SubstractBundles->setEnabled(true); + } + else + { + m_Controls->m_JoinBundles->setEnabled(false); + m_Controls->m_SubstractBundles->setEnabled(false); } - else if (dynamic_cast(node->GetData())) - m_SelectedPF.push_back(node); - else if (dynamic_cast(node->GetData())) - m_Image = dynamic_cast(node->GetData()); } - if (!m_SelectedPF.empty() && m_Image.IsNotNull()) - m_Controls->m_GenerateROIImage->setEnabled(true); - else - m_Controls->m_GenerateROIImage->setEnabled(false); - - if (m_SelectedPF.size() == 1) + // are planar figures selected? + if ( m_SelectedPF.empty() ) { - m_Controls->PFCompoANDButton->setDisabled(true); - m_Controls->PFCompoORButton->setDisabled(true); - m_Controls->PFCompoNOTButton->setEnabled(true); + m_Controls->doExtractFibersButton->setEnabled(false); + m_Controls->PFCompoANDButton->setEnabled(false); + m_Controls->PFCompoORButton->setEnabled(false); + m_Controls->PFCompoNOTButton->setEnabled(false); + m_Controls->m_GenerateRoiImage->setEnabled(false); } - else if (m_SelectedPF.size() > 1) + else { - m_Controls->PFCompoANDButton->setEnabled(true); - m_Controls->PFCompoORButton->setEnabled(true); - m_Controls->PFCompoNOTButton->setDisabled(true); - } - - // one bundle and one planar figure needed to extract fibers - if (m_SelectedFB.size() == 1 && m_SelectedPF.size() == 1) - m_Controls->doExtractFibersButton->setEnabled(true); + if ( m_SelectedImage.IsNotNull() ) + m_Controls->m_GenerateRoiImage->setEnabled(true); + else + m_Controls->m_GenerateRoiImage->setEnabled(false); - // two bundles needed to subtract - if (m_SelectedFB.size() == 2) - m_Controls->m_SubstractBundles->setEnabled(true); - else - m_Controls->m_SubstractBundles->setEnabled(false); + if (m_SelectedPF.size() > 1) + { + m_Controls->PFCompoANDButton->setEnabled(true); + m_Controls->PFCompoORButton->setEnabled(true); + m_Controls->PFCompoNOTButton->setEnabled(false); + } + else + { + m_Controls->PFCompoANDButton->setEnabled(false); + m_Controls->PFCompoORButton->setEnabled(false); + m_Controls->PFCompoNOTButton->setEnabled(true); + } + } +} - // more than two bundles needed to join - if (m_SelectedFB.size() > 1) - m_Controls->m_JoinBundles->setEnabled(true); - else - m_Controls->m_JoinBundles->setEnabled(false); +void QmitkFiberProcessingView::OnSelectionChanged( std::vector nodes ) +{ + if ( !this->IsVisible() ) + return; - // at least one bundle needed to generate image - if (!m_SelectedFB.empty()) - m_Controls->m_GenerationStartButton->setEnabled(true); - else - m_Controls->m_GenerationStartButton->setEnabled(false); + //reset existing Vectors containing FiberBundles and PlanarFigures from a previous selection + m_SelectedFB.clear(); + m_SelectedPF.clear(); + m_SelectedImage = NULL; + for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) + { + mitk::DataNode::Pointer node = *it; + if ( dynamic_cast(node->GetData()) ) + m_SelectedFB.push_back(node); + else if (dynamic_cast(node->GetData())) + m_SelectedPF.push_back(node); + else if (dynamic_cast(node->GetData())) + m_SelectedImage = dynamic_cast(node->GetData()); + } + UpdateGui(); GenerateStats(); } - void QmitkFiberProcessingView::ActionDrawPolygonTriggered() { // bool checked = m_Controls->m_PolygonButton->isChecked(); // if(!this->AssertDrawingIsPossible(checked)) // return; mitk::PlanarPolygon::Pointer figure = mitk::PlanarPolygon::New(); figure->ClosedOn(); this->AddFigureToDataStorage(figure, QString("Polygon%1").arg(++m_PolygonCounter)); MITK_INFO << "PlanarPolygon created ..."; mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDefaultDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; mitk::PlanarFigure* figureP = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figureP = dynamic_cast(node->GetData()); if(figureP) { figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); } } } void QmitkFiberProcessingView::ActionDrawEllipseTriggered() { //bool checked = m_Controls->m_CircleButton->isChecked(); //if(!this->AssertDrawingIsPossible(checked)) // return; mitk::PlanarCircle::Pointer figure = mitk::PlanarCircle::New(); this->AddFigureToDataStorage(figure, QString("Circle%1").arg(++m_EllipseCounter)); this->GetDataStorage()->Modified(); MITK_INFO << "PlanarCircle created ..."; //call mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDefaultDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; mitk::PlanarFigure* figureP = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figureP = dynamic_cast(node->GetData()); if(figureP) { figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); } } } void QmitkFiberProcessingView::Activated() { MITK_INFO << "FB OPerations ACTIVATED()"; /* mitk::DataStorage::SetOfObjects::ConstPointer _NodeSet = this->GetDefaultDataStorage()->GetAll(); mitk::DataNode* node = 0; mitk::PlanarFigureInteractor::Pointer figureInteractor = 0; mitk::PlanarFigure* figure = 0; for(mitk::DataStorage::SetOfObjects::ConstIterator it=_NodeSet->Begin(); it!=_NodeSet->End() ; it++) { node = const_cast(it->Value().GetPointer()); figure = dynamic_cast(node->GetData()); if(figure) { figureInteractor = dynamic_cast(node->GetInteractor()); if(figureInteractor.IsNull()) figureInteractor = mitk::PlanarFigureInteractor::New("PlanarFigureInteractor", node); mitk::GlobalInteraction::GetInstance()->AddInteractor(figureInteractor); } } */ } void QmitkFiberProcessingView::AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name, const char *propertyKey, mitk::BaseProperty *property ) { // initialize figure's geometry with empty geometry mitk::PlaneGeometry::Pointer emptygeometry = mitk::PlaneGeometry::New(); figure->SetGeometry2D( emptygeometry ); //set desired data to DataNode where Planarfigure is stored mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetName(name.toStdString()); newNode->SetData(figure); newNode->AddProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(1.0,0.0,0.0)); newNode->AddProperty( "planarfigure.line.width", mitk::FloatProperty::New(2.0)); newNode->AddProperty( "planarfigure.drawshadow", mitk::BoolProperty::New(true)); - - - - newNode->AddProperty( "selected", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.ishovering", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.drawoutline", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.drawquantities", mitk::BoolProperty::New(false) ); newNode->AddProperty( "planarfigure.drawshadow", mitk::BoolProperty::New(true) ); newNode->AddProperty( "planarfigure.line.width", mitk::FloatProperty::New(3.0) ); newNode->AddProperty( "planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.outline.width", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.helperline.width", mitk::FloatProperty::New(2.0) ); // PlanarFigureControlPointStyleProperty::Pointer styleProperty = // dynamic_cast< PlanarFigureControlPointStyleProperty* >( node->GetProperty( "planarfigure.controlpointshape" ) ); // if ( styleProperty.IsNotNull() ) // { // m_ControlPointShape = styleProperty->GetShape(); // } newNode->AddProperty( "planarfigure.default.line.color", mitk::ColorProperty::New(1.0,1.0,1.0) ); newNode->AddProperty( "planarfigure.default.line.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.outline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.helperline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.markerline.color", mitk::ColorProperty::New(0.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.default.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.default.marker.color", mitk::ColorProperty::New(1.0,1.0,1.0) ); newNode->AddProperty( "planarfigure.default.marker.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.line.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.outline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.helperline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.hover.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.hover.marker.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.line.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.line.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.outline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.outline.opacity", mitk::FloatProperty::New(2.0)); newNode->AddProperty( "planarfigure.selected.helperline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.helperline.opacity",mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.markerline.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.markerline.opacity", mitk::FloatProperty::New(2.0) ); newNode->AddProperty( "planarfigure.selected.marker.color", mitk::ColorProperty::New(1.0,0.0,0.0) ); newNode->AddProperty( "planarfigure.selected.marker.opacity",mitk::FloatProperty::New(2.0)); // Add custom property, if available //if ( (propertyKey != NULL) && (property != NULL) ) //{ // newNode->AddProperty( propertyKey, property ); //} //get current selected DataNode -which should be a FiberBundle- and set PlanarFigure as child //this->GetDataStorage()->GetNodes() // mitk::FiberBundle::Pointer selectedFBNode = m_SelectedFBNodes.at(0); // figure drawn on the topmost layer / image this->GetDataStorage()->Add(newNode ); std::vector selectedNodes = GetDataManagerSelection(); for(unsigned int i = 0; i < selectedNodes.size(); i++) { selectedNodes[i]->SetSelected(false); } //selectedNodes = m_SelectedPlanarFigureNodes->GetNodes(); /*for(unsigned int i = 0; i < selectedNodes.size(); i++) { selectedNodes[i]->SetSelected(false); } */ newNode->SetSelected(true); //Select(newNode); } void QmitkFiberProcessingView::DoFiberExtraction() { - mitk::FiberBundle::Pointer selFB = dynamic_cast(m_SelectedFB.at(0)->GetData()); - mitk::PlanarFigure::Pointer selPF = dynamic_cast (m_SelectedPF.at(0)->GetData()); - - - std::vector extFBset = selFB->extractFibersByPF(selPF); - - - //MITK_INFO << "returned vector in FBOperationsView: " << extFBset.size(); - // for(std::vector::iterator dispIt = extFBset.begin(); dispIt != extFBset.end(); dispIt++) - // { - // MITK_INFO << "vector DTI ID: " << *dispIt; - // - // } - - - mitk::FiberBundle::Pointer extFB = selFB->extractFibersById(extFBset); - MITK_INFO << " Number Of Tracts in sourceFiberBundle: " << selFB->GetNumTracts(); - MITK_INFO << " Number Of Tracts in extractedFiberBundle: " << extFB->GetNumTracts(); - - mitk::DataNode::Pointer fbNode; - fbNode = mitk::DataNode::New(); - fbNode->SetData(extFB); - fbNode->SetName("extGroupFinberBundle"); - fbNode->SetVisibility(true); - GetDataStorage()->Add(fbNode); - - + if ( m_SelectedFB.empty() ){ + QMessageBox::information( NULL, "Warning", "No fibe bundle selected!"); + MITK_WARN("QmitkFiberProcessingView") << "no fibe bundle selected"; + return; + } + for (int i=0; i(m_SelectedFB.at(i)->GetData()); + mitk::PlanarFigure::Pointer roi = dynamic_cast (m_SelectedPF.at(0)->GetData()); + +// std::vector extFBset = fib->extractFibersByPF(roi); +// mitk::FiberBundleX::Pointer extFB = fib->extractFibersById(extFBset); + + mitk::DataNode::Pointer node; + node = mitk::DataNode::New(); + //fbNode->SetData(extFB); + QString name(m_SelectedFB.at(0)->GetName().c_str()); + name += "_extracted"; + node->SetName(name.toStdString()); + GetDataStorage()->Add(node); + } } void QmitkFiberProcessingView::GenerateAndComposite() { mitk::PlanarFigureComposite::Pointer PFCAnd = mitk::PlanarFigureComposite::New(); mitk::PlaneGeometry* currentGeometry2D = dynamic_cast( const_cast(GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D())); PFCAnd->SetGeometry2D(currentGeometry2D); - PFCAnd->setOperationType(mitk::PFCOMPOSITION_AND_OPERATION); - for( std::vector::iterator it = m_SelectedPF.begin(); it != m_SelectedPF.end(); ++it ) { - mitk::DataNode::Pointer nodePF = *it; mitk::PlanarFigure::Pointer tmpPF = dynamic_cast( nodePF->GetData() ); PFCAnd->addPlanarFigure( tmpPF ); PFCAnd->addDataNode( nodePF ); PFCAnd->setDisplayName("AND_COMPO"); - // MITK_INFO << "PFCAND(): added to AND PF" << nodePF->GetName(); - - } - - debugPFComposition(PFCAnd, 0); - - - this->AddCompositeToDatastorage(PFCAnd, NULL /*parent*/); - -} - - -void QmitkFiberProcessingView::debugPFComposition(mitk::PlanarFigureComposite::Pointer pfc, int itLevelStatus) -{ - int myLevel = itLevelStatus; - if (myLevel == 0) - { - MITK_INFO << "############################################## " ; - MITK_INFO << "######### DEBUG START ############## " ; - MITK_INFO << "############################################## " ; - } - MITK_INFO << "############################################## " ; - MITK_INFO << "Name: " << pfc->getDisplayName(); - MITK_INFO << "iterationLevel: " << myLevel; - MITK_INFO << "CompositionType: " << pfc->getOperationType(); - MITK_INFO << "Number of children: " << pfc->getNumberOfChildren(); - - - //iterate through pfcs children - for(int i=0; igetNumberOfChildren(); ++i) - { - - mitk::PlanarFigure::Pointer tmpPFchild = pfc->getChildAt(i); - mitk::DataNode::Pointer savedPFchildNode = pfc->getDataNodeAt(i); - - if (tmpPFchild == savedPFchildNode->GetData()) - { - MITK_INFO << "[OK] Pointers point to same Data..."; - - }else{ - MITK_INFO << "Pointers differ in equation"; - } - - MITK_INFO << "Level: " << myLevel << " ChildNr.: " << i ; - - mitk::PlanarFigureComposite::Pointer pfcompcastNode= dynamic_cast(savedPFchildNode->GetData()); - mitk::PlanarFigureComposite::Pointer pfcompcast= dynamic_cast(tmpPFchild.GetPointer()); - if( !pfcompcast.IsNull() ) - { // we have a composite as child - - if ( pfcompcastNode.IsNull() ) - { - MITK_INFO << "************** NODE DIFFER FROM PFC...ERROR! ***************"; - } else { - MITK_INFO << "[OK]...node contains right type "; - } - - - - itLevelStatus++; - MITK_INFO << "child is PFC...debug this PFC"; - debugPFComposition(pfcompcast, itLevelStatus); - - } else { - - - // we have a planarFigure as child - // figure out which type - mitk::PlanarCircle::Pointer circleName = mitk::PlanarCircle::New(); - mitk::PlanarRectangle::Pointer rectName = mitk::PlanarRectangle::New(); - mitk::PlanarPolygon::Pointer polyName = mitk::PlanarPolygon::New(); - - - if (tmpPFchild->GetNameOfClass() == circleName->GetNameOfClass() ) - { - MITK_INFO << "a circle child of " << pfc->getDisplayName() ; - - } else if (tmpPFchild->GetNameOfClass() == rectName->GetNameOfClass() ){ - - MITK_INFO << "a rectangle child of " << pfc->getDisplayName() ; - - } else if (tmpPFchild->GetNameOfClass() == polyName->GetNameOfClass() ) { - - MITK_INFO << "a polygon child of " << pfc->getDisplayName() ; - } - - MITK_INFO << "....................................................... " ; - - - - - } - - } //end for - if (myLevel == 0) - { - MITK_INFO << "############################################## " ; - MITK_INFO << "######### DEBUG END ############## " ; - MITK_INFO << "############################################## " ; } - - + AddCompositeToDatastorage(PFCAnd, NULL); } void QmitkFiberProcessingView::GenerateOrComposite() { mitk::PlanarFigureComposite::Pointer PFCOr = mitk::PlanarFigureComposite::New(); mitk::PlaneGeometry* currentGeometry2D = dynamic_cast( const_cast(GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D())); PFCOr->SetGeometry2D(currentGeometry2D); PFCOr->setOperationType(mitk::PFCOMPOSITION_OR_OPERATION); - for( std::vector::iterator it = m_SelectedPF.begin(); it != m_SelectedPF.end(); ++it ) { - mitk::DataNode::Pointer nodePF = *it; mitk::PlanarFigure::Pointer tmpPF = dynamic_cast( nodePF->GetData() ); PFCOr->addPlanarFigure( tmpPF ); PFCOr->addDataNode( nodePF ); PFCOr->setDisplayName("OR_COMPO"); - // MITK_INFO << "PFCAND(): added to AND PF" << nodePF->GetName(); - } - debugPFComposition(PFCOr, 0); - - - this->AddCompositeToDatastorage(PFCOr, NULL /*parent*/); - + AddCompositeToDatastorage(PFCOr, NULL); } void QmitkFiberProcessingView::GenerateNotComposite() { mitk::PlanarFigureComposite::Pointer PFCNot = mitk::PlanarFigureComposite::New(); mitk::PlaneGeometry* currentGeometry2D = dynamic_cast( const_cast(GetActiveStdMultiWidget()->GetRenderWindow1()->GetRenderer()->GetCurrentWorldGeometry2D())); PFCNot->SetGeometry2D(currentGeometry2D); PFCNot->setOperationType(mitk::PFCOMPOSITION_NOT_OPERATION); - for( std::vector::iterator it = m_SelectedPF.begin(); it != m_SelectedPF.end(); ++it ) { - mitk::DataNode::Pointer nodePF = *it; mitk::PlanarFigure::Pointer tmpPF = dynamic_cast( nodePF->GetData() ); PFCNot->addPlanarFigure( tmpPF ); PFCNot->addDataNode( nodePF ); PFCNot->setDisplayName("NOT_COMPO"); - // MITK_INFO << "PFCAND(): added to AND PF" << nodePF->GetName(); - } - debugPFComposition(PFCNot, 0); - - - this->AddCompositeToDatastorage(PFCNot, NULL /*parent*/); - + AddCompositeToDatastorage(PFCNot, NULL); } +/* CLEANUP NEEDED */ void QmitkFiberProcessingView::AddCompositeToDatastorage(mitk::PlanarFigureComposite::Pointer pfcomp, mitk::DataNode::Pointer parentDataNode ) { - //a new planarFigureComposition arrived - //convert it into a dataNode mitk::DataNode::Pointer newPFCNode; newPFCNode = mitk::DataNode::New(); newPFCNode->SetName( pfcomp->getDisplayName() ); newPFCNode->SetData(pfcomp); newPFCNode->SetVisibility(true); switch (pfcomp->getOperationType()) { case 0: { if (!parentDataNode.IsNull()) { GetDataStorage()->Add(newPFCNode, parentDataNode); } else { GetDataStorage()->Add(newPFCNode); } //iterate through its childs for(int i=0; igetNumberOfChildren(); ++i) { mitk::PlanarFigure::Pointer tmpPFchild = pfcomp->getChildAt(i); mitk::DataNode::Pointer savedPFchildNode = pfcomp->getDataNodeAt(i); mitk::PlanarFigureComposite::Pointer pfcompcast= dynamic_cast(tmpPFchild.GetPointer()); if ( !pfcompcast.IsNull() ) - { // child is of type planar Figure composite + { + // child is of type planar Figure composite // make new node of the child, cuz later the child has to be removed of its old position in datamanager // feed new dataNode with information of the savedDataNode, which is gonna be removed soon mitk::DataNode::Pointer newChildPFCNode; newChildPFCNode = mitk::DataNode::New(); newChildPFCNode->SetData(tmpPFchild); newChildPFCNode->SetName( savedPFchildNode->GetName() ); pfcompcast->setDisplayName( savedPFchildNode->GetName() ); //name might be changed in DataManager by user //update inside vector the dataNodePointer pfcomp->replaceDataNodeAt(i, newChildPFCNode); AddCompositeToDatastorage(pfcompcast, newPFCNode); //the current PFCNode becomes the childs parent // remove savedNode here, cuz otherwise its children will change their position in the dataNodeManager // without having its parent anymore //GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); - } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } - - } else { + } + else + { // child is not of type PlanarFigureComposite, so its one of the planarFigures // create new dataNode containing the data of the old dataNode, but position in dataManager will be // modified cuz we re setting a (new) parent. mitk::DataNode::Pointer newPFchildNode = mitk::DataNode::New(); newPFchildNode->SetName(savedPFchildNode->GetName() ); newPFchildNode->SetData(tmpPFchild); newPFchildNode->SetVisibility(true); // replace the dataNode in PFComp DataNodeVector pfcomp->replaceDataNodeAt(i, newPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; - }else{ + } + else + { MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); - } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); - - if ( GetDataStorage()->Exists(savedPFchildNode)) { + if ( GetDataStorage()->Exists(savedPFchildNode)) + { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } MITK_INFO << "adding " << newPFchildNode->GetName() << " to " << newPFCNode->GetName(); //add new child to datamanager with its new position as child of newPFCNode parent GetDataStorage()->Add(newPFchildNode, newPFCNode); - } - - - - } GetDataStorage()->Modified(); - - // AND PLANARFIGURECOMPOSITE - // newPFCNode->SetName("AND_PFCombo"); - - - break; } case 1: { - // AND PLANARFIGURECOMPOSITE - // newPFCNode->SetName("AND_PFCombo"); - if (!parentDataNode.IsNull()) { MITK_INFO << "adding " << newPFCNode->GetName() << " to " << parentDataNode->GetName() ; GetDataStorage()->Add(newPFCNode, parentDataNode); } else { MITK_INFO << "adding " << newPFCNode->GetName(); GetDataStorage()->Add(newPFCNode); } - - //iterate through its childs - for(int i=0; igetNumberOfChildren(); ++i) { mitk::PlanarFigure::Pointer tmpPFchild = pfcomp->getChildAt(i); mitk::DataNode::Pointer savedPFchildNode = pfcomp->getDataNodeAt(i); mitk::PlanarFigureComposite::Pointer pfcompcast= dynamic_cast(tmpPFchild.GetPointer()); if ( !pfcompcast.IsNull() ) { // child is of type planar Figure composite // make new node of the child, cuz later the child has to be removed of its old position in datamanager // feed new dataNode with information of the savedDataNode, which is gonna be removed soon mitk::DataNode::Pointer newChildPFCNode; newChildPFCNode = mitk::DataNode::New(); newChildPFCNode->SetData(tmpPFchild); newChildPFCNode->SetName( savedPFchildNode->GetName() ); pfcompcast->setDisplayName( savedPFchildNode->GetName() ); //name might be changed in DataManager by user //update inside vector the dataNodePointer pfcomp->replaceDataNodeAt(i, newChildPFCNode); AddCompositeToDatastorage(pfcompcast, newPFCNode); //the current PFCNode becomes the childs parent // remove savedNode here, cuz otherwise its children will change their position in the dataNodeManager // without having its parent anymore //GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } - - } else { // child is not of type PlanarFigureComposite, so its one of the planarFigures // create new dataNode containing the data of the old dataNode, but position in dataManager will be // modified cuz we re setting a (new) parent. mitk::DataNode::Pointer newPFchildNode = mitk::DataNode::New(); newPFchildNode->SetName(savedPFchildNode->GetName() ); newPFchildNode->SetData(tmpPFchild); newPFchildNode->SetVisibility(true); // replace the dataNode in PFComp DataNodeVector pfcomp->replaceDataNodeAt(i, newPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } MITK_INFO << "adding " << newPFchildNode->GetName() << " to " << newPFCNode->GetName(); //add new child to datamanager with its new position as child of newPFCNode parent GetDataStorage()->Add(newPFchildNode, newPFCNode); - } - - - - } GetDataStorage()->Modified(); - - - - break; - } case 2: { if (!parentDataNode.IsNull()) { MITK_INFO << "adding " << newPFCNode->GetName() << " to " << parentDataNode->GetName() ; GetDataStorage()->Add(newPFCNode, parentDataNode); - - } else { + } + else + { MITK_INFO << "adding " << newPFCNode->GetName(); GetDataStorage()->Add(newPFCNode); - } //iterate through its childs for(int i=0; igetNumberOfChildren(); ++i) { mitk::PlanarFigure::Pointer tmpPFchild = pfcomp->getChildAt(i); mitk::DataNode::Pointer savedPFchildNode = pfcomp->getDataNodeAt(i); mitk::PlanarFigureComposite::Pointer pfcompcast= dynamic_cast(tmpPFchild.GetPointer()); if ( !pfcompcast.IsNull() ) { // child is of type planar Figure composite // makeRemoveBundle new node of the child, cuz later the child has to be removed of its old position in datamanager // feed new dataNode with information of the savedDataNode, which is gonna be removed soon mitk::DataNode::Pointer newChildPFCNode; newChildPFCNode = mitk::DataNode::New(); newChildPFCNode->SetData(tmpPFchild); newChildPFCNode->SetName( savedPFchildNode->GetName() ); pfcompcast->setDisplayName( savedPFchildNode->GetName() ); //name might be changed in DataManager by user //update inside vector the dataNodePointer pfcomp->replaceDataNodeAt(i, newChildPFCNode); AddCompositeToDatastorage(pfcompcast, newPFCNode); //the current PFCNode becomes the childs parent // remove savedNode here, cuz otherwise its children will change their position in the dataNodeManager // without having its parent anymore //GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } } else { // child is not of type PlanarFigureComposite, so its one of the planarFigures // create new dataNode containing the data of the old dataNode, but position in dataManager will be // modified cuz we re setting a (new) parent. mitk::DataNode::Pointer newPFchildNode = mitk::DataNode::New(); newPFchildNode->SetName(savedPFchildNode->GetName() ); newPFchildNode->SetData(tmpPFchild); newPFchildNode->SetVisibility(true); // replace the dataNode in PFComp DataNodeVector pfcomp->replaceDataNodeAt(i, newPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " exists in DS...trying to remove it"; }else{ MITK_INFO << "[ERROR] does NOT exist, but can I read its Name? " << savedPFchildNode->GetName(); } // remove old child position in dataStorage GetDataStorage()->Remove(savedPFchildNode); if ( GetDataStorage()->Exists(savedPFchildNode)) { MITK_INFO << savedPFchildNode->GetName() << " still exists"; } MITK_INFO << "adding " << newPFchildNode->GetName() << " to " << newPFCNode->GetName(); //add new child to datamanager with its new position as child of newPFCNode parent GetDataStorage()->Add(newPFchildNode, newPFCNode); } } GetDataStorage()->Modified(); break; } default: MITK_INFO << "we have an UNDEFINED composition... ERROR" ; break; } } void QmitkFiberProcessingView::JoinBundles() { - mitk::FiberBundle::Pointer newBundle = mitk::FiberBundle::New(); - std::vector::const_iterator it; - for (it = m_SelectedFB.begin(); it!=m_SelectedFB.end(); ++it) + if ( m_SelectedFB.size()<2 ){ + QMessageBox::information( NULL, "Warning", "Select at least two fiber bundles!"); + MITK_WARN("QmitkFiberProcessingView") << "Select at least two fiber bundles!"; + return; + } + + std::vector::const_iterator it = m_SelectedFB.begin(); + mitk::FiberBundleX::Pointer newBundle = dynamic_cast((*it)->GetData()); + QString name(""); + name += QString((*it)->GetName().c_str()); + ++it; + for (it; it!=m_SelectedFB.end(); ++it) { - newBundle = newBundle->JoinBundle(dynamic_cast((*it)->GetData())); + newBundle = *newBundle+dynamic_cast((*it)->GetData()); + name += "+"+QString((*it)->GetName().c_str()); } mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(newBundle); - fbNode->SetName("JoinedBundle"); + fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); GetDataStorage()->Add(fbNode); } void QmitkFiberProcessingView::SubstractBundles() { - mitk::FiberBundle::Pointer bundle1 = dynamic_cast(m_SelectedFB.at(0)->GetData()); - mitk::FiberBundle::Pointer bundle2 = dynamic_cast(m_SelectedFB.at(1)->GetData()); + if ( m_SelectedFB.size()<2 ){ + QMessageBox::information( NULL, "Warning", "Select at least two fiber bundles!"); + MITK_WARN("QmitkFiberProcessingView") << "Select at least two fiber bundles!"; + return; + } + + std::vector::const_iterator it = m_SelectedFB.begin(); + mitk::FiberBundleX::Pointer newBundle = dynamic_cast((*it)->GetData()); + QString name(""); + name += QString((*it)->GetName().c_str()); + ++it; + for (it; it!=m_SelectedFB.end(); ++it) + { + newBundle = *newBundle-dynamic_cast((*it)->GetData()); + name += "-"+QString((*it)->GetName().c_str()); + } - mitk::FiberBundle::Pointer newBundle = bundle1->SubstractBundle(bundle2); mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); fbNode->SetData(newBundle); - fbNode->SetName(m_SelectedFB.at(0)->GetName()+"-"+m_SelectedFB.at(1)->GetName()); + fbNode->SetName(name.toStdString()); fbNode->SetVisibility(true); GetDataStorage()->Add(fbNode); } void QmitkFiberProcessingView::GenerateStats() { - std::vector nodes = GetDataManagerSelection(); - if (nodes.empty()) + if ( m_SelectedFB.empty() ) return; QString stats(""); - for( int i=0; i(node->GetData())) + mitk::DataNode::Pointer node = m_SelectedFB[i]; + if (node.IsNotNull() && dynamic_cast(node->GetData())) { if (i>0) stats += "\n-----------------------------\n"; stats += QString(node->GetName().c_str()) + "\n"; - mitk::FiberBundle::Pointer fib = dynamic_cast(node->GetData()); - stats += "Number of fibers: "+ QString::number(fib->GetNumTracts()) + "\n"; + mitk::FiberBundleX::Pointer fib = dynamic_cast(node->GetData()); + vtkSmartPointer fiberPolyData = fib->GetFiberPolyData(); + vtkSmartPointer vLines = fiberPolyData->GetLines(); + vLines->InitTraversal(); + int numberOfLines = vLines->GetNumberOfCells(); + + stats += "Number of fibers: "+ QString::number(numberOfLines) + "\n"; float length = 0; std::vector lengths; - for (int i=0; iGetNumTracts(); i++) + for (int i=0; iGetTract(i); - if (tract.IsNull()) - continue; + vtkIdType numPoints(0); + vtkIdType* points(NULL); + vLines->GetNextCell ( numPoints, points ); + float l=0; - for (unsigned int j=0; jSize(); j++) + for (unsigned int j=0; jGetElementIfIndexExists(j, &p1) && tract->GetElementIfIndexExists(j+1, &p2)) - { - float dist = std::abs(p1.EuclideanDistanceTo(p2)); - length += dist; - l += dist; - } + double p1[3] = {0,0,0}; + fiberPolyData->GetPoint(points[j], p1); + double p2[3] = {0,0,0}; + fiberPolyData->GetPoint(points[j+1], p2); + + float a = p1[0]-p2[0]; + float b = p1[1]-p2[1]; + float c = p1[2]-p2[2]; + + float dist = std::sqrt(a*a+b*b+c*c); + length += dist; + l += dist; } lengths.push_back(l); } std::sort(lengths.begin(), lengths.end()); - if (fib->GetNumTracts()>0) - length /= fib->GetNumTracts(); + if (numberOfLines>0) + length /= numberOfLines; float dev=0; int count = 0; - for (int i=0; iGetNumTracts(); i++) + vLines->InitTraversal(); + for (int i=0; iGetTract(i); - if (tract.IsNull()) - continue; + vtkIdType numPoints(0); + vtkIdType* points(NULL); + vLines->GetNextCell ( numPoints, points ); + float l=0; - for (unsigned int j=0; jSize(); j++) + for (unsigned int j=0; jGetElementIfIndexExists(j, &p1) && tract->GetElementIfIndexExists(j+1, &p2)) - { - l += std::abs(p1.EuclideanDistanceTo(p2)); - } + double p1[3] = {0,0,0}; + fiberPolyData->GetPoint(points[j], p1); + double p2[3] = {0,0,0}; + fiberPolyData->GetPoint(points[j+1], p2); + + float a = p1[0]-p2[0]; + float b = p1[1]-p2[1]; + float c = p1[2]-p2[2]; + + float dist = std::sqrt(a*a+b*b+c*c); + l += dist; } dev += (length-l)*(length-l); count++; } - if (fib->GetNumTracts()>0) - { - dev /= fib->GetNumTracts(); - dev = std::sqrt(dev); - } + if (numberOfLines>0) + dev /= numberOfLines; stats += "Mean fiber length: "+ QString::number(length/10) + "cm\n"; stats += "Median fiber length: "+ QString::number(lengths.at(lengths.size()/2)/10) + "cm\n"; stats += "Standard deviation: "+ QString::number(dev/10) + "cm\n"; } } this->m_Controls->m_StatsTextEdit->setText(stats); } -void QmitkFiberProcessingView::GenerationStart() +void QmitkFiberProcessingView::ProcessSelectedBundles() { - int generationMethod = m_Controls->m_GenerationBox->currentIndex(); - - std::vector nodes = GetDataManagerSelection(); - if (nodes.empty()){ - QMessageBox::information( NULL, "Warning", "No data object selected!"); - MITK_WARN("QmitkFiberProcessingView") << "no data object selected"; + if ( m_SelectedFB.empty() ){ + QMessageBox::information( NULL, "Warning", "No fibe bundle selected!"); + MITK_WARN("QmitkFiberProcessingView") << "no fibe bundle selected"; return; } - for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) - { - mitk::DataNode::Pointer node = *it; + int generationMethod = m_Controls->m_GenerationBox->currentIndex(); - if (node.IsNotNull() && dynamic_cast(node->GetData())) + for( int i=0; i(node->GetData())) { - m_FiberBundle = dynamic_cast(node->GetData()); - m_FiberBundleNode = node; + mitk::FiberBundleX::Pointer fib = dynamic_cast(node->GetData()); + QString name(node->GetName().c_str()); + DataNode::Pointer newNode = NULL; switch(generationMethod){ case 0: - GenerateTractDensityImage(false); + newNode = GenerateTractDensityImage(fib, false); + name += "_TDI"; break; case 1: - GenerateTractDensityImage(true); + newNode = GenerateTractDensityImage(fib, true); + name += "_envelope"; break; case 2: - GenerateColorHeatmap(); + newNode = GenerateColorHeatmap(fib); break; case 3: - GenerateFiberEndingsImage(); + newNode = GenerateFiberEndingsImage(fib); + name += "_fiber_endings"; break; case 4: - GenerateFiberEndingsPointSet(); + newNode = GenerateFiberEndingsPointSet(fib); + name += "_fiber_endings"; break; } + if (newNode.IsNotNull()) + { + newNode->SetName(name.toStdString()); + GetDataStorage()->Add(newNode); + } } } } // generate pointset displaying the fiber endings -void QmitkFiberProcessingView::GenerateFiberEndingsPointSet() +mitk::DataNode::Pointer QmitkFiberProcessingView::GenerateFiberEndingsPointSet(mitk::FiberBundleX::Pointer fib) { - if(m_FiberBundle.IsNull()){ - QMessageBox::information( NULL, "Warning", "No fiber bundle selected!"); - MITK_WARN("QmitkGlobalFiberTrackingView") << "no fiber bundle selected"; - return; - } - - mitk::Geometry3D::Pointer geometry = m_FiberBundle->GetGeometry(); - mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); + vtkSmartPointer fiberPolyData = fib->GetFiberPolyData(); + vtkSmartPointer vLines = fiberPolyData->GetLines(); + vLines->InitTraversal(); - int numTracts = m_FiberBundle->GetNumTracts(); int count = 0; - for( int i=0; iGetNumFibers(); + for( int i=0; iGetNumPoints(i); - itk::Point start = m_FiberBundle->GetPoint(i,0); - itk::Point world1; - geometry->IndexToWorld(start, world1); - pointSet->InsertPoint(count, world1); - count++; - // get fiber end point - if(numVertices>1) + vtkIdType numPoints(0); + vtkIdType* points(NULL); + vLines->GetNextCell ( numPoints, points ); + + if (numPoints>0) { - itk::Point end = m_FiberBundle->GetPoint(i,numVertices-1); - itk::Point world; - geometry->IndexToWorld(end, world); - pointSet->InsertPoint(count, world); + double* point = fiberPolyData->GetPoint(points[0]); + itk::Point itkPoint; + itkPoint[0] = point[0]; + itkPoint[1] = point[1]; + itkPoint[2] = point[2]; + pointSet->InsertPoint(count, itkPoint); + count++; + } + if (numPoints>2) + { + double* point = fiberPolyData->GetPoint(points[numPoints-1]); + itk::Point itkPoint; + itkPoint[0] = point[0]; + itkPoint[1] = point[1]; + itkPoint[2] = point[2]; + pointSet->InsertPoint(count, itkPoint); count++; } } - mitk::DataNode::Pointer pointSetNode = mitk::DataNode::New(); - pointSetNode->SetData( pointSet ); - QString name(m_FiberBundleNode->GetName().c_str()); - name += "_fiber_endings"; - pointSetNode->SetName(name.toStdString()); - pointSetNode->SetProperty( "opacity", mitk::FloatProperty::New( 1 ) ); - pointSetNode->SetProperty( "pointsize", mitk::FloatProperty::New( 0.1*m_Controls->m_UpsamplingSpinBox->value()) ); - pointSetNode->SetColor( 1.0, 1.0, 1.0 ); - - GetDefaultDataStorage()->Add(pointSetNode); + mitk::DataNode::Pointer node = mitk::DataNode::New(); + node->SetData( pointSet ); + return node; } // generate image displaying the fiber endings -void QmitkFiberProcessingView::GenerateFiberEndingsImage() +mitk::DataNode::Pointer QmitkFiberProcessingView::GenerateFiberEndingsImage(mitk::FiberBundleX::Pointer fib) { - if(m_FiberBundle.IsNull()){ - QMessageBox::information( NULL, "Warning", "No fiber bundle selected!"); - MITK_WARN("QmitkGlobalFiberTrackingView") << "no fiber bundle selected"; - return; - } - typedef unsigned char OutPixType; + typedef itk::Image OutImageType; - // run generator - typedef itk::TractsToFiberEndingsImageFilter ImageGeneratorType; + typedef itk::TractsToFiberEndingsImageFilter< OutImageType > ImageGeneratorType; ImageGeneratorType::Pointer generator = ImageGeneratorType::New(); - generator->SetFiberBundle(m_FiberBundle); - + generator->SetFiberBundle(fib); + generator->SetInvertImage(m_Controls->m_InvertCheckbox->isChecked()); generator->SetUpsamplingFactor(m_Controls->m_UpsamplingSpinBox->value()); + if (m_SelectedImage.IsNotNull()) + { + OutImageType::Pointer itkImage = OutImageType::New(); + CastToItkImage(m_SelectedImage, itkImage); + generator->SetInputImage(itkImage); + generator->SetUseImageGeometry(true); + } generator->Update(); - // get result - typedef itk::Image OutType; - OutType::Pointer outImg = generator->GetOutput(); - + // get output image + OutImageType::Pointer outImg = generator->GetOutput(); mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); - // to datastorage + // init data node mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img); - QString name(m_FiberBundleNode->GetName().c_str()); - name += "_fiber_endings"; - node->SetName(name.toStdString()); - node->SetVisibility(true); - - GetDataStorage()->Add(node); + return node; } // generate rgba heatmap from fiber bundle -void QmitkFiberProcessingView::GenerateColorHeatmap() +mitk::DataNode::Pointer QmitkFiberProcessingView::GenerateColorHeatmap(mitk::FiberBundleX::Pointer fib) { - if(m_FiberBundle.IsNull() || m_FiberBundleNode.IsNull()) - { - QMessageBox::information( NULL, "Warning", "No fiber bundle selected!"); - MITK_WARN("QmitkGlobalFiberTrackingView") << "no fiber bundle selected"; - return; - } - typedef itk::RGBAPixel OutPixType; - - // run generator - typedef itk::TractsToProbabilityImageFilter - ImageGeneratorType; + typedef itk::Image OutImageType; + typedef itk::TractsToRgbaImageFilter< OutImageType > ImageGeneratorType; ImageGeneratorType::Pointer generator = ImageGeneratorType::New(); - //generator->SetInput(NULL); - generator->SetFiberBundle(m_FiberBundle); - + generator->SetFiberBundle(fib); generator->SetUpsamplingFactor(m_Controls->m_UpsamplingSpinBox->value()); + if (m_SelectedImage.IsNotNull()) + { + itk::Image::Pointer itkImage = itk::Image::New(); + CastToItkImage(m_SelectedImage, itkImage); + generator->SetInputImage(itkImage); + generator->SetUseImageGeometry(true); + } generator->Update(); - // get result + // get output image typedef itk::Image OutType; OutType::Pointer outImg = generator->GetOutput(); - mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); - // to datastorage + // init data node mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img); - QString name(m_FiberBundleNode->GetName().c_str()); - node->SetName(name.toStdString()); - node->SetVisibility(true); - - mitk::LevelWindow opaclevwin; - opaclevwin.SetRangeMinMax(0,255); - opaclevwin.SetWindowBounds(0,0); - mitk::LevelWindowProperty::Pointer prop = - mitk::LevelWindowProperty::New(opaclevwin); - node->AddProperty( "opaclevelwindow", prop ); - - GetDataStorage()->Add(node); + return node; } -// generate greyscale heatmap from fiber bundle -void QmitkFiberProcessingView::GenerateTractDensityImage(bool binary) +// generate tract density image from fiber bundle +mitk::DataNode::Pointer QmitkFiberProcessingView::GenerateTractDensityImage(mitk::FiberBundleX::Pointer fib, bool binary) { - if(m_FiberBundle.IsNull() || m_FiberBundleNode.IsNull()) - { - QMessageBox::information( NULL, "Warning", "No fiber bundle selected!"); - MITK_WARN("QmitkGlobalFiberTrackingView") << "no fiber bundle selected"; - return; - } + typedef float OutPixType; + typedef itk::Image OutImageType; - typedef unsigned char OutPixType; - - // run generator - typedef itk::TractsToProbabilityImageFilter ImageGeneratorType; - ImageGeneratorType::Pointer generator = ImageGeneratorType::New(); - generator->SetFiberBundle(m_FiberBundle); + itk::TractDensityImageFilter< OutImageType >::Pointer generator = itk::TractDensityImageFilter< OutImageType >::New(); + generator->SetFiberBundle(fib); + generator->SetBinaryOutput(binary); generator->SetInvertImage(m_Controls->m_InvertCheckbox->isChecked()); generator->SetUpsamplingFactor(m_Controls->m_UpsamplingSpinBox->value()); - if (binary) - generator->SetBinaryEnvelope(true); - else - generator->SetBinaryEnvelope(false); + if (m_SelectedImage.IsNotNull()) + { + OutImageType::Pointer itkImage = OutImageType::New(); + CastToItkImage(m_SelectedImage, itkImage); + generator->SetInputImage(itkImage); + generator->SetUseImageGeometry(true); + } generator->Update(); - // get result + // get output image typedef itk::Image OutType; OutType::Pointer outImg = generator->GetOutput(); - mitk::Image::Pointer img = mitk::Image::New(); img->InitializeByItk(outImg.GetPointer()); img->SetVolume(outImg->GetBufferPointer()); - // to datastorage + // init data node mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(img); - QString name(m_FiberBundleNode->GetName().c_str()); - if(binary) - name += "_envelope"; - else - name += "_TDI"; - node->SetName(name.toStdString()); - node->SetVisibility(true); - - mitk::LevelWindow opaclevwin2; - opaclevwin2.SetRangeMinMax(0,255); - opaclevwin2.SetWindowBounds(0,0); - mitk::LevelWindowProperty::Pointer prop2 = - mitk::LevelWindowProperty::New(opaclevwin2); - node->AddProperty( "opaclevelwindow", prop2 ); - - GetDataStorage()->Add(node); + return node; } diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.h b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.h index 957db9a636..9a94ae525a 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.h +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingView.h @@ -1,204 +1,195 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ Version: $Revision: 21975 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef QmitkFiberProcessingView_h #define QmitkFiberProcessingView_h -#include -#include - #include #include "ui_QmitkFiberProcessingViewControls.h" -#include "mitkDataStorage.h" -#include "mitkDataStorageSelection.h" +#include +#include +#include +#include +#include +#include -#include "mitkPlanarFigure.h" -#include "mitkFiberBundle.h" -#include "mitkPlanarFigureComposite.h" #include #include +#include +#include +#include + #include #include +#include #include #include -#include -#include #include -#include #include +#include +#include +#include +#include +#include +#include -#include -#include - -struct FboSelListener; +#include /*! -\brief QmitkFiberBundleView +\brief QmitkFiberProcessingView -\warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. +\warning View to process fiber bundles. Supplies methods to extract fibers from the bundle, join and subtract bundles, generate images from the selected bundle and much more. \sa QmitkFunctionality \ingroup Functionalities */ class QmitkFiberProcessingView : public QmitkFunctionality { - - - friend struct FboSelListener; - // 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: - typedef itk::Image< unsigned char, 3 > MaskImage3DType; + typedef itk::Image< unsigned char, 3 > UCharImageType; typedef itk::Image< float, 3 > FloatImageType; - typedef mitk::FiberBundle::ContainerPointType ContainerPointType; - typedef mitk::FiberBundle::ContainerTractType ContainerTractType; - typedef mitk::FiberBundle::ContainerType ContainerType; - static const std::string VIEW_ID; QmitkFiberProcessingView(); virtual ~QmitkFiberProcessingView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); virtual void Activated(); protected slots: - /// \brief Called when the user clicks the GUI button void ActionDrawEllipseTriggered(); void ActionDrawPolygonTriggered(); void DoFiberExtraction(); void GenerateAndComposite(); void GenerateOrComposite(); void GenerateNotComposite(); void JoinBundles(); void SubstractBundles(); - void GenerateROIImage(); - void GenerationStart(); + void GenerateRoiImage(); + void ProcessSelectedBundles(); + + void Extract3d(); virtual void AddFigureToDataStorage(mitk::PlanarFigure* figure, const QString& name, const char *propertyKey = NULL, mitk::BaseProperty *property = NULL ); protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); Ui::QmitkFiberProcessingViewControls* m_Controls; - QmitkStdMultiWidget* m_MultiWidget; - //void Select( mitk::DataNode::Pointer node, bool clearMaskOnFirstArgNULL=false, bool clearImageOnFirstArgNULL=false ); - /** Connection from VTK to ITK */ template void ConnectPipelines(VTK_Exporter* exporter, ITK_Importer importer) { importer->SetUpdateInformationCallback(exporter->GetUpdateInformationCallback()); importer->SetPipelineModifiedCallback(exporter->GetPipelineModifiedCallback()); importer->SetWholeExtentCallback(exporter->GetWholeExtentCallback()); importer->SetSpacingCallback(exporter->GetSpacingCallback()); importer->SetOriginCallback(exporter->GetOriginCallback()); importer->SetScalarTypeCallback(exporter->GetScalarTypeCallback()); importer->SetNumberOfComponentsCallback(exporter->GetNumberOfComponentsCallback()); importer->SetPropagateUpdateExtentCallback(exporter->GetPropagateUpdateExtentCallback()); importer->SetUpdateDataCallback(exporter->GetUpdateDataCallback()); importer->SetDataExtentCallback(exporter->GetDataExtentCallback()); importer->SetBufferPointerCallback(exporter->GetBufferPointerCallback()); importer->SetCallbackUserData(exporter->GetCallbackUserData()); } template void ConnectPipelines(ITK_Exporter exporter, VTK_Importer* importer) { importer->SetUpdateInformationCallback(exporter->GetUpdateInformationCallback()); importer->SetPipelineModifiedCallback(exporter->GetPipelineModifiedCallback()); importer->SetWholeExtentCallback(exporter->GetWholeExtentCallback()); importer->SetSpacingCallback(exporter->GetSpacingCallback()); importer->SetOriginCallback(exporter->GetOriginCallback()); importer->SetScalarTypeCallback(exporter->GetScalarTypeCallback()); importer->SetNumberOfComponentsCallback(exporter->GetNumberOfComponentsCallback()); importer->SetPropagateUpdateExtentCallback(exporter->GetPropagateUpdateExtentCallback()); importer->SetUpdateDataCallback(exporter->GetUpdateDataCallback()); importer->SetDataExtentCallback(exporter->GetDataExtentCallback()); importer->SetBufferPointerCallback(exporter->GetBufferPointerCallback()); importer->SetCallbackUserData(exporter->GetCallbackUserData()); } template < typename TPixel, unsigned int VImageDimension > void InternalCalculateMaskFromPlanarFigure( itk::Image< TPixel, VImageDimension > *image, unsigned int axis, std::string nodeName ); template < typename TPixel, unsigned int VImageDimension > void InternalReorientImagePlane( const itk::Image< TPixel, VImageDimension > *image, mitk::Geometry3D* planegeo3D, int additionalIndex ); void GenerateStats(); + void UpdateGui(); berry::ISelectionListener::Pointer m_SelListener; berry::IStructuredSelection::ConstPointer m_CurrentSelection; private: int m_EllipseCounter; int m_PolygonCounter; //contains the selected FiberBundles std::vector m_SelectedFB; //contains the selected PlanarFigures std::vector m_SelectedPF; - mitk::Image::ConstPointer m_Image; - mitk::Image::Pointer m_InternalImage; - mitk::PlanarFigure::Pointer m_PlanarFigure; - float m_UpsamplingFactor; - MaskImage3DType::Pointer m_InternalImageMask3D; - MaskImage3DType::Pointer m_PlanarFigureImage; - mitk::FiberBundle::Pointer m_FiberBundle; - mitk::DataNode::Pointer m_FiberBundleNode; + mitk::Image::ConstPointer m_SelectedImage; + mitk::Image::Pointer m_InternalImage; + mitk::PlanarFigure::Pointer m_PlanarFigure; + float m_UpsamplingFactor; + UCharImageType::Pointer m_InternalImageMask3D; + UCharImageType::Pointer m_PlanarFigureImage; void AddCompositeToDatastorage(mitk::PlanarFigureComposite::Pointer, mitk::DataNode::Pointer); void debugPFComposition(mitk::PlanarFigureComposite::Pointer , int ); void CompositeExtraction(mitk::DataNode::Pointer node, mitk::Image* image); - void GenerateTractDensityImage(bool binary); - void GenerateColorHeatmap(); - void GenerateFiberEndingsImage(); - void GenerateFiberEndingsPointSet(); - void DWIGenerationStart(); + mitk::DataNode::Pointer GenerateTractDensityImage(mitk::FiberBundleX::Pointer fib, bool binary); + mitk::DataNode::Pointer GenerateColorHeatmap(mitk::FiberBundleX::Pointer fib); + mitk::DataNode::Pointer GenerateFiberEndingsImage(mitk::FiberBundleX::Pointer fib); + mitk::DataNode::Pointer GenerateFiberEndingsPointSet(mitk::FiberBundleX::Pointer fib); }; #endif // _QMITKFIBERTRACKINGVIEW_H_INCLUDED diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingViewControls.ui b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingViewControls.ui index 97244e0a4f..7a880cdd4d 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingViewControls.ui +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkFiberProcessingViewControls.ui @@ -1,562 +1,592 @@ QmitkFiberProcessingViewControls 0 0 665 587 Form 5 0 5 0 Fiber Bundle Modification 0 0 200 0 16777215 60 QFrame::NoFrame QFrame::Raised 0 30 30 Draw circular ROI :/QmitkDiffusionImaging/circle.png:/QmitkDiffusionImaging/circle.png 32 32 false true 30 30 Draw rectangular ROI :/QmitkDiffusionImaging/rectangle.png:/QmitkDiffusionImaging/rectangle.png 32 32 true true 30 30 Draw polygonal ROI :/QmitkDiffusionImaging/polygon.png:/QmitkDiffusionImaging/polygon.png 32 32 true true Qt::Horizontal 40 20 QFrame::NoFrame QFrame::Raised 0 false 0 0 200 16777215 11 Extract fibers passing through selected ROI or composite ROI Extract false 0 0 200 16777215 11 Returns fiber bundle containing all fibers the two selected bundles dont't have in common Substract - + false 0 0 16777215 16777215 11 Generate a binary image containing all selected ROIs ROI Image false 0 0 200 16777215 11 Merge selected fiber bundles Join Qt::Horizontal 40 20 + + + + true + + + + 0 + 0 + + + + + 200 + 16777215 + + + + + 11 + + + + Extract fibers passing through selected surface mesh + + + Extract 3D + + + 0 0 200 0 16777215 60 QFrame::NoFrame QFrame::Raised 0 Qt::Horizontal 40 20 false 60 16777215 Create AND composition with selected ROIs AND false 60 16777215 Create OR composition with selected ROIs OR false 60 16777215 Create NOT composition from selected ROI NOT Fiber Bundle Processing 0 0 Tract Density Image (TDI) Binary Envelope Fiber Bundle Image Fiber Endings Image Fiber Endings Pointset Upsampling Factor 1 10 - 4 + 2 - + false 0 0 200 16777215 11 Perform selected operation on fiber bundle Generate If selected operation generates an image, the inverse image is returned Invert Fiber Bundle Statistics Qt::Vertical 20 40 diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.cpp b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.cpp index 7ca69c9b58..25914ced2c 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.cpp +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.cpp @@ -1,796 +1,786 @@ /*========================================================================= Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Blueberry #include #include // Qmitk #include "QmitkGibbsTrackingView.h" #include // Qt #include #include #include // MITK #include #include #include #include // ITK #include #include // MISC #include QmitkTrackingWorker::QmitkTrackingWorker(QmitkGibbsTrackingView* view) : m_View(view) { } void QmitkTrackingWorker::run() { m_View->m_GlobalTracker = QmitkGibbsTrackingView::GibbsTrackingFilterType::New(); MITK_INFO << "Resampling mask images"; // setup resampler typedef itk::ResampleImageFilter ResamplerType; ResamplerType::Pointer resampler = ResamplerType::New(); resampler->SetOutputSpacing( m_View->m_ItkQBallImage->GetSpacing() ); resampler->SetOutputOrigin( m_View->m_ItkQBallImage->GetOrigin() ); resampler->SetOutputDirection( m_View->m_ItkQBallImage->GetDirection() ); resampler->SetSize( m_View->m_ItkQBallImage->GetLargestPossibleRegion().GetSize() ); // resample mask image resampler->SetInput( m_View->m_MaskImage ); resampler->SetDefaultPixelValue(0); resampler->Update(); m_View->m_MaskImage = resampler->GetOutput(); if (m_View->m_GfaImage.IsNotNull()) { ResamplerType::Pointer resampler = ResamplerType::New(); resampler->SetOutputSpacing( m_View->m_ItkQBallImage->GetSpacing() ); resampler->SetOutputOrigin( m_View->m_ItkQBallImage->GetOrigin() ); resampler->SetOutputDirection( m_View->m_ItkQBallImage->GetDirection() ); resampler->SetSize( m_View->m_ItkQBallImage->GetLargestPossibleRegion().GetSize() ); resampler->SetInput( m_View->m_GfaImage ); resampler->SetDefaultPixelValue(0); resampler->Update(); m_View->m_GfaImage = resampler->GetOutput(); } m_View->m_GlobalTracker->SetInput0(m_View->m_ItkQBallImage.GetPointer()); m_View->m_GlobalTracker->SetMaskImage(m_View->m_MaskImage); m_View->m_GlobalTracker->SetGfaImage(m_View->m_GfaImage); m_View->m_GlobalTracker->SetTempStart((float)m_View->m_Controls->m_StartTempSlider->value()/100); m_View->m_GlobalTracker->SetTempEnd((float)m_View->m_Controls->m_EndTempSlider->value()/10000); m_View->m_GlobalTracker->SetNumIt(m_View->m_Iterations); m_View->m_GlobalTracker->SetParticleWeight((float)m_View->m_Controls->m_ParticleWeightSlider->value()/10000); m_View->m_GlobalTracker->SetSubtractMean(m_View->m_Controls->m_MeanSubtractionCheckbox->isChecked()); m_View->m_GlobalTracker->SetParticleWidth((float)(m_View->m_Controls->m_ParticleWidthSlider->value())/10); m_View->m_GlobalTracker->SetParticleLength((float)(m_View->m_Controls->m_ParticleLengthSlider->value())/10); m_View->m_GlobalTracker->SetInexBalance((float)m_View->m_Controls->m_InExBalanceSlider->value()/10); m_View->m_GlobalTracker->SetFiberLength(m_View->m_Controls->m_FiberLengthSlider->value()); m_View->m_GlobalTracker->Update(); m_View->m_TrackingThread.quit(); } const std::string QmitkGibbsTrackingView::VIEW_ID = "org.mitk.views.gibbstracking"; QmitkGibbsTrackingView::QmitkGibbsTrackingView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) , m_ThreadIsRunning(false) , m_GlobalTracker(NULL) , m_QBallImage(NULL) , m_MaskImage(NULL) , m_GfaImage(NULL) , m_GfaImageNode(NULL) , m_QBallImageNode(NULL) , m_ItkQBallImage(NULL) , m_FiberBundleNode(NULL) , m_TrackingWorker(this) , m_QBallSelected(false) - , m_FibSelected(false) , m_Iterations(10000000) , m_LastStep(0) { m_TrackingWorker.moveToThread(&m_TrackingThread); connect(&m_TrackingThread, SIGNAL(started()), this, SLOT(BeforeThread())); connect(&m_TrackingThread, SIGNAL(started()), &m_TrackingWorker, SLOT(run())); connect(&m_TrackingThread, SIGNAL(finished()), this, SLOT(AfterThread())); connect(&m_TrackingThread, SIGNAL(terminated()), this, SLOT(AfterThread())); m_TrackingTimer = new QTimer(this); } QmitkGibbsTrackingView::~QmitkGibbsTrackingView() { delete m_TrackingTimer; } // update tracking status and generate fiber bundle void QmitkGibbsTrackingView::TimerUpdate() { mitk::ProgressBar::GetInstance()->Progress(m_GlobalTracker->GetCurrentStep()-m_LastStep); m_LastStep = m_GlobalTracker->GetCurrentStep(); UpdateTrackingStatus(); GenerateFiberBundle(); } // tell global tractography filter to stop after current step void QmitkGibbsTrackingView::StopGibbsTracking() { if (m_GlobalTracker.IsNull()) return; mitk::ProgressBar::GetInstance()->Progress(m_GlobalTracker->GetSteps()-m_LastStep); m_GlobalTracker->SetAbortTracking(true); m_Controls->m_TrackingStop->setEnabled(false); m_Controls->m_TrackingStop->setText("Stopping Tractography ..."); } // update gui elements and generate fiber bundle after tracking is finished void QmitkGibbsTrackingView::AfterThread() { m_ThreadIsRunning = false; m_TrackingTimer->stop(); UpdateGUI(); UpdateTrackingStatus(); GenerateFiberBundle(); QString paramMessage; if(m_Controls->m_ParticleWeightSlider->value()==0) { m_Controls->m_ParticleWeightLabel->setText(QString::number(m_GlobalTracker->GetParticleWeight())); m_Controls->m_ParticleWeightSlider->setValue(m_GlobalTracker->GetParticleWeight()*10000); paramMessage += "Particle weight was set to " + QString::number(m_GlobalTracker->GetParticleWeight()) + "\n"; } if(m_Controls->m_ParticleWidthSlider->value()==0) { m_Controls->m_ParticleWidthLabel->setText(QString::number(m_GlobalTracker->GetParticleWidth())); m_Controls->m_ParticleWidthSlider->setValue(m_GlobalTracker->GetParticleWidth()*10); paramMessage += "Particle width was set to " + QString::number(m_GlobalTracker->GetParticleWidth()) + " mm\n"; } if(m_Controls->m_ParticleLengthSlider->value()==0) { m_Controls->m_ParticleLengthLabel->setText(QString::number(m_GlobalTracker->GetParticleLength())); m_Controls->m_ParticleLengthSlider->setValue(m_GlobalTracker->GetParticleLength()*10); paramMessage += "Particle length was set to " + QString::number(m_GlobalTracker->GetParticleLength()) + " mm\n"; } m_FiberBundleNode = NULL; if (paramMessage.length()>0) QMessageBox::information(NULL, "Automatically selected parameters", paramMessage); } // start tracking timer and update gui elements before tracking is started void QmitkGibbsTrackingView::BeforeThread() { m_ThreadIsRunning = true; m_TrackingTime = QTime::currentTime(); m_ElapsedTime = 0; m_TrackingTimer->start(1000); m_LastStep = 0; UpdateGUI(); } // setup gui elements and signal/slot connections void QmitkGibbsTrackingView::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::QmitkGibbsTrackingViewControls; m_Controls->setupUi( parent ); AdvancedSettings(); connect( m_TrackingTimer, SIGNAL(timeout()), this, SLOT(TimerUpdate()) ); connect( m_Controls->m_TrackingStop, SIGNAL(clicked()), this, SLOT(StopGibbsTracking()) ); connect( m_Controls->m_TrackingStart, SIGNAL(clicked()), this, SLOT(StartGibbsTracking()) ); connect( m_Controls->m_SetMaskButton, SIGNAL(clicked()), this, SLOT(SetMask()) ); connect( m_Controls->m_SetGfaButton, SIGNAL(clicked()), this, SLOT(SetGfaImage()) ); connect( m_Controls->m_AdvancedSettingsCheckbox, SIGNAL(clicked()), this, SLOT(AdvancedSettings()) ); connect( m_Controls->m_SaveTrackingParameters, SIGNAL(clicked()), this, SLOT(SaveTrackingParameters()) ); connect( m_Controls->m_LoadTrackingParameters, SIGNAL(clicked()), this, SLOT(LoadTrackingParameters()) ); connect( m_Controls->m_IterationsSlider, SIGNAL(valueChanged(int)), this, SLOT(SetIterations(int)) ); connect( m_Controls->m_ParticleWidthSlider, SIGNAL(valueChanged(int)), this, SLOT(SetParticleWidth(int)) ); connect( m_Controls->m_ParticleLengthSlider, SIGNAL(valueChanged(int)), this, SLOT(SetParticleLength(int)) ); connect( m_Controls->m_InExBalanceSlider, SIGNAL(valueChanged(int)), this, SLOT(SetInExBalance(int)) ); connect( m_Controls->m_FiberLengthSlider, SIGNAL(valueChanged(int)), this, SLOT(SetFiberLength(int)) ); connect( m_Controls->m_ParticleWeightSlider, SIGNAL(valueChanged(int)), this, SLOT(SetParticleWeight(int)) ); connect( m_Controls->m_StartTempSlider, SIGNAL(valueChanged(int)), this, SLOT(SetStartTemp(int)) ); connect( m_Controls->m_EndTempSlider, SIGNAL(valueChanged(int)), this, SLOT(SetEndTemp(int)) ); } } void QmitkGibbsTrackingView::SetInExBalance(int value) { m_Controls->m_InExBalanceLabel->setText(QString::number((float)value/10)); } void QmitkGibbsTrackingView::SetFiberLength(int value) { m_Controls->m_FiberLengthLabel->setText(QString::number(value)); } void QmitkGibbsTrackingView::SetParticleWeight(int value) { if (value>0) { m_Controls->m_ParticleWeightLabel->setText(QString::number((float)value/10000)); m_Controls->m_GfaFrame->setEnabled(false); } else { m_Controls->m_ParticleWeightLabel->setText("auto"); m_Controls->m_GfaFrame->setEnabled(true); } } void QmitkGibbsTrackingView::SetStartTemp(int value) { m_Controls->m_StartTempLabel->setText(QString::number((float)value/100)); } void QmitkGibbsTrackingView::SetEndTemp(int value) { m_Controls->m_EndTempLabel->setText(QString::number((float)value/10000)); } void QmitkGibbsTrackingView::SetParticleWidth(int value) { if (value>0) m_Controls->m_ParticleWidthLabel->setText(QString::number((float)value/10)+" mm"); else m_Controls->m_ParticleWidthLabel->setText("auto"); } void QmitkGibbsTrackingView::SetParticleLength(int value) { if (value>0) m_Controls->m_ParticleLengthLabel->setText(QString::number((float)value/10)+" mm"); else m_Controls->m_ParticleLengthLabel->setText("auto"); } void QmitkGibbsTrackingView::SetIterations(int value) { switch(value) { case 0: m_Controls->m_IterationsLabel->setText("Iterations: 10^4"); m_Iterations = 10000; break; case 1: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^4"); m_Iterations = 50000; break; case 2: m_Controls->m_IterationsLabel->setText("Iterations: 10^5"); m_Iterations = 100000; break; case 3: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^5"); m_Iterations = 500000; break; case 4: m_Controls->m_IterationsLabel->setText("Iterations: 10^6"); m_Iterations = 1000000; break; case 5: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^6"); m_Iterations = 5000000; break; case 6: m_Controls->m_IterationsLabel->setText("Iterations: 10^7"); m_Iterations = 10000000; break; case 7: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^7"); m_Iterations = 50000000; break; case 8: m_Controls->m_IterationsLabel->setText("10^8"); m_Iterations = 100000000; break; case 9: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^8"); m_Iterations = 500000000; break; case 10: m_Controls->m_IterationsLabel->setText("Iterations: 10^9"); m_Iterations = 1000000000; break; case 11: m_Controls->m_IterationsLabel->setText("Iterations: 5x10^9"); m_Iterations = 5000000000; break; } } void QmitkGibbsTrackingView::StdMultiWidgetAvailable(QmitkStdMultiWidget &stdMultiWidget) { m_MultiWidget = &stdMultiWidget; } void QmitkGibbsTrackingView::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; } // called if datamanager selection changes void QmitkGibbsTrackingView::OnSelectionChanged( std::vector nodes ) { m_QBallSelected = false; - m_FibSelected = false; // iterate all selected objects for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { m_QBallSelected = true; m_QBallImageNode = node; } - else if (node.IsNotNull() && dynamic_cast(node->GetData())) - { - m_FibSelected = true; - m_FiberBundleNode = node; - } } UpdateGUI(); } // update gui elements displaying trackings status void QmitkGibbsTrackingView::UpdateTrackingStatus() { if (m_GlobalTracker.IsNull()) return; m_ElapsedTime += m_TrackingTime.elapsed()/1000; m_TrackingTime.restart(); unsigned long hours = m_ElapsedTime/3600; unsigned long minutes = (m_ElapsedTime%3600)/60; unsigned long seconds = m_ElapsedTime%60; m_Controls->m_ProposalAcceptance->setText(QString::number(m_GlobalTracker->GetProposalAcceptance()*100)+"%"); m_Controls->m_TrackingTimeLabel->setText( QString::number(hours)+QString("h ")+QString::number(minutes)+QString("m ")+QString::number(seconds)+QString("s") ); m_Controls->m_NumConnectionsLabel->setText( QString::number(m_GlobalTracker->GetNumConnections()) ); m_Controls->m_NumParticlesLabel->setText( QString::number(m_GlobalTracker->GetNumParticles()) ); m_Controls->m_CurrentStepLabel->setText( QString::number(100*(float)m_GlobalTracker->GetCurrentStep()/m_GlobalTracker->GetSteps())+"%" ); m_Controls->m_AcceptedFibersLabel->setText( QString::number(m_GlobalTracker->GetNumAcceptedFibers()) ); } // update gui elements (enable/disable elements and set tooltips) void QmitkGibbsTrackingView::UpdateGUI() { if (!m_ThreadIsRunning && m_QBallSelected) { m_Controls->m_TrackingStop->setEnabled(false); m_Controls->m_TrackingStart->setEnabled(true); m_Controls->m_LoadTrackingParameters->setEnabled(true); m_Controls->m_MaskFrame->setEnabled(true); m_Controls->m_GfaFrame->setEnabled(true); m_Controls->m_IterationsSlider->setEnabled(true); m_Controls->m_AdvancedFrame->setEnabled(true); m_Controls->m_TrackingStop->setText("Stop Tractography"); m_Controls->m_TrackingStart->setToolTip("Start tractography. No further change of parameters possible."); m_Controls->m_TrackingStop->setToolTip(""); } else if (!m_ThreadIsRunning) { m_Controls->m_TrackingStop->setEnabled(false); m_Controls->m_TrackingStart->setEnabled(false); m_Controls->m_LoadTrackingParameters->setEnabled(true); m_Controls->m_MaskFrame->setEnabled(true); m_Controls->m_GfaFrame->setEnabled(true); m_Controls->m_IterationsSlider->setEnabled(true); m_Controls->m_AdvancedFrame->setEnabled(true); m_Controls->m_TrackingStop->setText("Stop Tractography"); m_Controls->m_TrackingStart->setToolTip("No Q-Ball image selected."); m_Controls->m_TrackingStop->setToolTip(""); } else { m_Controls->m_TrackingStop->setEnabled(true); m_Controls->m_TrackingStart->setEnabled(false); m_Controls->m_LoadTrackingParameters->setEnabled(false); m_Controls->m_MaskFrame->setEnabled(false); m_Controls->m_GfaFrame->setEnabled(false); m_Controls->m_IterationsSlider->setEnabled(false); m_Controls->m_AdvancedFrame->setEnabled(false); m_Controls->m_AdvancedFrame->setVisible(false); m_Controls->m_AdvancedSettingsCheckbox->setChecked(false); m_Controls->m_TrackingStart->setToolTip("Tracking in progress."); m_Controls->m_TrackingStop->setToolTip("Stop tracking and display results."); } } // show/hide advanced settings frame void QmitkGibbsTrackingView::AdvancedSettings() { m_Controls->m_AdvancedFrame->setVisible(m_Controls->m_AdvancedSettingsCheckbox->isChecked()); } // set mask image data node void QmitkGibbsTrackingView::SetMask() { std::vector nodes = GetDataManagerSelection(); if (nodes.empty()) { m_MaskImageNode = NULL; m_Controls->m_MaskImageEdit->setText("N/A"); return; } for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if (node.IsNotNull() && dynamic_cast(node->GetData())) { m_MaskImageNode = node; m_Controls->m_MaskImageEdit->setText(node->GetName().c_str()); return; } } } // set gfa image data node void QmitkGibbsTrackingView::SetGfaImage() { std::vector nodes = GetDataManagerSelection(); if (nodes.empty()) { m_GfaImageNode = NULL; m_Controls->m_GfaImageEdit->setText("N/A"); return; } for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) { mitk::DataNode::Pointer node = *it; if (node.IsNotNull() && dynamic_cast(node->GetData())) { m_GfaImageNode = node; m_Controls->m_GfaImageEdit->setText(node->GetName().c_str()); return; } } } // cast image to float template void QmitkGibbsTrackingView::CastToFloat(InputImageType* image, mitk::Image::Pointer outImage) { typedef itk::CastImageFilter ItkCastFilter; typename ItkCastFilter::Pointer itkCaster = ItkCastFilter::New(); itkCaster->SetInput(image); itkCaster->Update(); outImage->InitializeByItk(itkCaster->GetOutput()); outImage->SetVolume(itkCaster->GetOutput()->GetBufferPointer()); } // check for mask and qbi and start tracking thread void QmitkGibbsTrackingView::StartGibbsTracking() { if(m_ThreadIsRunning) { MITK_WARN("QmitkGibbsTrackingView")<<"Thread already running!"; return; } if (!m_QBallSelected) { // Nothing selected. Inform the user and return QMessageBox::information( NULL, "Warning", "Please load and select a qball image before starting image processing."); return; } // a node itself is not very useful, we need its data item (the image) mitk::BaseData* data = m_QBallImageNode->GetData(); if (!data) return; // test if this data item is an image or not (could also be a surface or something totally different) m_QBallImage = dynamic_cast( data ); if (m_QBallImage.IsNull()) return; // cast qbi to itk m_ItkQBallImage = ItkQBallImgType::New(); mitk::CastToItkImage(m_QBallImage, m_ItkQBallImage); // mask image found? // catch exceptions thrown by the itkAccess macros try{ if(m_Controls->m_MaskImageEdit->text().compare("N/A") != 0) { m_MaskImage = 0; if (dynamic_cast(m_MaskImageNode->GetData())) mitk::CastToItkImage(dynamic_cast(m_MaskImageNode->GetData()), m_MaskImage); } } catch(...) { QMessageBox::warning(NULL, "Warning", "Incompatible mask image chosen. Processing without masking."); //reset mask image m_MaskImage = NULL; } // if no mask image is selected generate it if( m_MaskImage.IsNull() ) { m_MaskImage = MaskImgType::New(); m_MaskImage->SetSpacing( m_ItkQBallImage->GetSpacing() ); // Set the image spacing m_MaskImage->SetOrigin( m_ItkQBallImage->GetOrigin() ); // Set the image origin m_MaskImage->SetDirection( m_ItkQBallImage->GetDirection() ); // Set the image direction m_MaskImage->SetLargestPossibleRegion( m_ItkQBallImage->GetLargestPossibleRegion()); m_MaskImage->SetBufferedRegion( m_ItkQBallImage->GetLargestPossibleRegion() ); m_MaskImage->Allocate(); itk::ImageRegionIterator it (m_MaskImage, m_MaskImage->GetLargestPossibleRegion() ); for (it = it.Begin(); !it.IsAtEnd(); ++it) { it.Set(1); } } // gfa image found? // catch exceptions thrown by the itkAccess macros try{ if(m_Controls->m_GfaImageEdit->text().compare("N/A") != 0) { m_GfaImage = 0; if (dynamic_cast(m_GfaImageNode->GetData())) mitk::CastToItkImage(dynamic_cast(m_GfaImageNode->GetData()), m_GfaImage); } } catch(...) { QMessageBox::warning(NULL, "Warning", "Incompatible GFA image chosen. Processing without GFA image."); m_GfaImage = NULL; } unsigned int steps = m_Iterations/10000; if (steps<10) steps = 10; m_LastStep = 0; mitk::ProgressBar::GetInstance()->AddStepsToDo(steps); // start worker thread m_TrackingThread.start(QThread::LowestPriority); } // generate mitkFiberBundle from tracking filter output void QmitkGibbsTrackingView::GenerateFiberBundle() { if (m_GlobalTracker.IsNull() || m_ItkQBallImage.IsNull() || m_QBallImage.IsNull() || (!m_Controls->m_VisualizationCheckbox->isChecked() && m_ThreadIsRunning)) return; - m_FiberBundle = mitk::FiberBundle::New(); typedef std::vector< itk::Point > FiberTractType; typedef std::vector< FiberTractType > FiberBundleType; - FiberBundleType* fiberBundle = m_GlobalTracker->GetFiberBundle(); + vtkSmartPointer fiberBundle = m_GlobalTracker->GetFiberBundle(); - for (int i=0; isize(); i++) - { - FiberTractType* tract = &fiberBundle->at(i); - for (int j=0; jsize(); j++) - m_FiberBundle->PushPoint(i, tract->at(j)); - } - m_FiberBundle->initFiberGroup(); - - float bounds[] = {0,0,0}; - bounds[0] = m_ItkQBallImage->GetLargestPossibleRegion().GetSize().GetElement(0); - bounds[1] = m_ItkQBallImage->GetLargestPossibleRegion().GetSize().GetElement(1); - bounds[2] = m_ItkQBallImage->GetLargestPossibleRegion().GetSize().GetElement(2); - m_FiberBundle->SetBounds(bounds); - m_FiberBundle->SetGeometry(m_QBallImage->GetGeometry()); + m_FiberBundle = mitk::FiberBundleX::New(fiberBundle); + + double qBallImageSpacing[3] = {m_ItkQBallImage->GetSpacing().GetElement(0),m_ItkQBallImage->GetSpacing().GetElement(1),m_ItkQBallImage->GetSpacing().GetElement(2)}; + float minSpacing; + if(qBallImageSpacing[0]ResampleFibers(minSpacing); if (m_FiberBundleNode.IsNotNull()){ GetDefaultDataStorage()->Remove(m_FiberBundleNode); m_FiberBundleNode = 0; } m_FiberBundleNode = mitk::DataNode::New(); m_FiberBundleNode->SetData(m_FiberBundle); QString name(m_QBallImageNode->GetName().c_str()); name += "_FiberBundle"; m_FiberBundleNode->SetName(name.toStdString()); m_FiberBundleNode->SetVisibility(true); if(m_QBallImageNode.IsNull()) GetDataStorage()->Add(m_FiberBundleNode); else GetDataStorage()->Add(m_FiberBundleNode, m_QBallImageNode); } // save current tracking paramters as xml file (.gtp) void QmitkGibbsTrackingView::SaveTrackingParameters() { TiXmlDocument documentXML; TiXmlDeclaration* declXML = new TiXmlDeclaration( "1.0", "", "" ); documentXML.LinkEndChild( declXML ); TiXmlElement* mainXML = new TiXmlElement("global_tracking_parameter_file"); mainXML->SetAttribute("file_version", "0.1"); documentXML.LinkEndChild(mainXML); TiXmlElement* paramXML = new TiXmlElement("parameter_set"); paramXML->SetAttribute("iterations", QString::number(m_Iterations).toStdString()); paramXML->SetAttribute("particle_length", QString::number((float)m_Controls->m_ParticleLengthSlider->value()/10).toStdString()); paramXML->SetAttribute("particle_width", QString::number((float)m_Controls->m_ParticleWidthSlider->value()/10).toStdString()); paramXML->SetAttribute("particle_weight", QString::number((float)m_Controls->m_ParticleWeightSlider->value()/10000).toStdString()); paramXML->SetAttribute("temp_start", QString::number((float)m_Controls->m_StartTempSlider->value()/100).toStdString()); paramXML->SetAttribute("temp_end", QString::number((float)m_Controls->m_EndTempSlider->value()/10000).toStdString()); paramXML->SetAttribute("inexbalance", QString::number((float)m_Controls->m_InExBalanceSlider->value()/10).toStdString()); paramXML->SetAttribute("fiber_length", QString::number(m_Controls->m_FiberLengthSlider->value()).toStdString()); mainXML->LinkEndChild(paramXML); QString filename = QFileDialog::getSaveFileName( 0, tr("Save Parameters"), QDir::currentPath()+"/param.gtp", tr("Global Tracking Parameters (*.gtp)") ); if(filename.isEmpty() || filename.isNull()) return; if(!filename.endsWith(".gtp")) filename += ".gtp"; documentXML.SaveFile( filename.toStdString() ); } void QmitkGibbsTrackingView::UpdateIteraionsGUI(unsigned long iterations) { switch(iterations) { case 10000: m_Controls->m_IterationsSlider->setValue(0); m_Controls->m_IterationsLabel->setText("Iterations: 10^4"); break; case 50000: m_Controls->m_IterationsSlider->setValue(1); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^4"); break; case 100000: m_Controls->m_IterationsSlider->setValue(2); m_Controls->m_IterationsLabel->setText("Iterations: 10^5"); break; case 500000: m_Controls->m_IterationsSlider->setValue(3); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^5"); break; case 1000000: m_Controls->m_IterationsSlider->setValue(4); m_Controls->m_IterationsLabel->setText("Iterations: 10^6"); break; case 5000000: m_Controls->m_IterationsSlider->setValue(5); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^6"); break; case 10000000: m_Controls->m_IterationsSlider->setValue(6); m_Controls->m_IterationsLabel->setText("Iterations: 10^7"); break; case 50000000: m_Controls->m_IterationsSlider->setValue(7); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^7"); break; case 100000000: m_Controls->m_IterationsSlider->setValue(8); m_Controls->m_IterationsLabel->setText("Iterations: 10^8"); break; case 500000000: m_Controls->m_IterationsSlider->setValue(9); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^8"); break; case 1000000000: m_Controls->m_IterationsSlider->setValue(10); m_Controls->m_IterationsLabel->setText("Iterations: 10^9"); break; case 5000000000: m_Controls->m_IterationsSlider->setValue(11); m_Controls->m_IterationsLabel->setText("Iterations: 5x10^9"); break; } } // load current tracking paramters from xml file (.gtp) void QmitkGibbsTrackingView::LoadTrackingParameters() { QString filename = QFileDialog::getOpenFileName(0, tr("Load Parameters"), QDir::currentPath(), tr("Global Tracking Parameters (*.gtp)") ); if(filename.isEmpty() || filename.isNull()) return; TiXmlDocument doc( filename.toStdString() ); doc.LoadFile(); TiXmlHandle hDoc(&doc); TiXmlElement* pElem; TiXmlHandle hRoot(0); pElem = hDoc.FirstChildElement().Element(); hRoot = TiXmlHandle(pElem); pElem = hRoot.FirstChildElement("parameter_set").Element(); QString iterations(pElem->Attribute("iterations")); m_Iterations = iterations.toULong(); UpdateIteraionsGUI(m_Iterations); QString particleLength(pElem->Attribute("particle_length")); float pLength = particleLength.toFloat(); QString particleWidth(pElem->Attribute("particle_width")); float pWidth = particleWidth.toFloat(); if (pLength==0) m_Controls->m_ParticleLengthLabel->setText("auto"); else m_Controls->m_ParticleLengthLabel->setText(particleLength+" mm"); if (pWidth==0) m_Controls->m_ParticleWidthLabel->setText("auto"); else m_Controls->m_ParticleWidthLabel->setText(particleWidth+" mm"); m_Controls->m_ParticleWidthSlider->setValue(pWidth*10); m_Controls->m_ParticleLengthSlider->setValue(pLength*10); QString partWeight(pElem->Attribute("particle_weight")); m_Controls->m_ParticleWeightSlider->setValue(partWeight.toFloat()*10000); m_Controls->m_ParticleWeightLabel->setText(partWeight); QString startTemp(pElem->Attribute("temp_start")); m_Controls->m_StartTempSlider->setValue(startTemp.toFloat()*100); m_Controls->m_StartTempLabel->setText(startTemp); QString endTemp(pElem->Attribute("temp_end")); m_Controls->m_EndTempSlider->setValue(endTemp.toFloat()*10000); m_Controls->m_EndTempLabel->setText(endTemp); QString inExBalance(pElem->Attribute("inexbalance")); m_Controls->m_InExBalanceSlider->setValue(inExBalance.toFloat()*10); m_Controls->m_InExBalanceLabel->setText(inExBalance); QString fiberLength(pElem->Attribute("fiber_length")); m_Controls->m_FiberLengthSlider->setValue(fiberLength.toInt()); m_Controls->m_FiberLengthLabel->setText(fiberLength); } diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.h b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.h index 6f17ec2341..7facb0eed6 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.h +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkGibbsTrackingView.h @@ -1,165 +1,167 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ Version: $Revision: 21975 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef QmitkGibbsTrackingView_h #define QmitkGibbsTrackingView_h #include #include #include "ui_QmitkGibbsTrackingViewControls.h" #include #include -#include +#include #include #include +#include +#include class QmitkGibbsTrackingView; class QmitkTrackingWorker : public QObject { Q_OBJECT public: QmitkTrackingWorker(QmitkGibbsTrackingView* view); public slots: void run(); private: QmitkGibbsTrackingView* m_View; }; /*! \brief QmitkGibbsTrackingView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ typedef itk::Image< float, 3 > FloatImageType; namespace itk { template class GibbsTrackingFilter; } class QmitkGibbsTrackingView : 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: typedef itk::Image MaskImgType; typedef itk::Vector OdfVectorType; typedef itk::Image ItkQBallImgType; typedef itk::GibbsTrackingFilter GibbsTrackingFilterType; static const std::string VIEW_ID; QmitkGibbsTrackingView(); virtual ~QmitkGibbsTrackingView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); signals: protected slots: void StartGibbsTracking(); void StopGibbsTracking(); void AfterThread(); void BeforeThread(); void TimerUpdate(); void SetMask(); void SetGfaImage(); void AdvancedSettings(); void SaveTrackingParameters(); void LoadTrackingParameters(); void SetIterations(int value); void SetParticleWidth(int value); void SetParticleLength(int value); void SetInExBalance(int value); void SetFiberLength(int value); void SetParticleWeight(int value); void SetStartTemp(int value); void SetEndTemp(int value); private: // Visualization & GUI void GenerateFiberBundle(); void UpdateGUI(); void UpdateTrackingStatus(); /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); template void CastToFloat(InputImageType* image, typename mitk::Image::Pointer outImage); void UpdateIteraionsGUI(unsigned long iterations); Ui::QmitkGibbsTrackingViewControls* m_Controls; QmitkStdMultiWidget* m_MultiWidget; // data objects - mitk::FiberBundle::Pointer m_FiberBundle; + mitk::FiberBundleX::Pointer m_FiberBundle; MaskImgType::Pointer m_MaskImage; MaskImgType::Pointer m_GfaImage; mitk::QBallImage::Pointer m_QBallImage; ItkQBallImgType::Pointer m_ItkQBallImage; // data nodes mitk::DataNode::Pointer m_QBallImageNode; mitk::DataNode::Pointer m_MaskImageNode; mitk::DataNode::Pointer m_GfaImageNode; mitk::DataNode::Pointer m_FiberBundleNode; // flags etc. bool m_ThreadIsRunning; QTimer* m_TrackingTimer; QTime m_TrackingTime; unsigned long m_ElapsedTime; bool m_QBallSelected; bool m_FibSelected; unsigned long m_Iterations; int m_LastStep; // global tracker and friends itk::SmartPointer m_GlobalTracker; QmitkTrackingWorker m_TrackingWorker; QThread m_TrackingThread; friend class QmitkTrackingWorker; }; #endif // _QMITKGibbsTrackingVIEW_H_INCLUDED diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.cpp b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.cpp index 9873a691d2..2db143d7d3 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.cpp +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.cpp @@ -1,670 +1,272 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ Version: $Revision: 21975 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Blueberry #include #include -#include "berryIStructuredSelection.h" - +#include // Qmitk #include "QmitkStochasticFiberTrackingView.h" #include "QmitkStdMultiWidget.h" // Qt #include -//MITK -//#include "mitkNodePredicateProperty.h" -//#include "mitkNodePredicateAND.h" +// MITK #include +#include -#include - +// VTK #include #include #include -#include -#include #include #include - - - #include -#include -#include -#include -#include -#include -#include -#include -#include -#include const std::string QmitkStochasticFiberTrackingView::VIEW_ID = "org.mitk.views.stochasticfibertracking"; const std::string id_DataManager = "org.mitk.views.datamanager"; using namespace berry; -// Strings for Data handling -const QString qDiffStr = "DiffusionImage"; -const QString qStatusErr = "[Err]"; -const QString qStatusOk = "[OK]"; -const QString qSeed = "Seed"; - - -//*****PERSONAL REMINDER****** -//############################## -/* THIS CLASS IS A MESS!! - * CLEANUP IN PROGRESS... - */ -//############################## - - - - QmitkStochasticFiberTrackingView::QmitkStochasticFiberTrackingView() : QmitkFunctionality() , m_Controls( 0 ) , m_MultiWidget( NULL ) +, m_DiffusionImage( NULL ) +, m_SeedRoi( NULL ) { } // Destructor QmitkStochasticFiberTrackingView::~QmitkStochasticFiberTrackingView() { } - void QmitkStochasticFiberTrackingView::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::QmitkStochasticFiberTrackingViewControls; m_Controls->setupUi( parent ); - // set tableWidget column with - m_Controls->tableWidget->setColumnWidth(0,38); - m_Controls->tableWidget->setColumnWidth(1,250); - m_Controls->tableWidget->setEnabled(false); - m_Controls->tableWidget->setLineWidth(0); - connect( m_Controls->commandLinkButton, SIGNAL(clicked()), this, SLOT(DoFiberTracking()) ); - //connect( m_Controls->comboBox_fiberAlgo, SIGNAL(selected()), this, SLOT(handleAlgoSelection() ); - - + connect( m_Controls->m_SeedsPerVoxelSlider, SIGNAL(valueChanged(int)), this, SLOT(OnSeedsPerVoxelChanged(int)) ); + connect( m_Controls->m_MaxCacheSizeSlider, SIGNAL(valueChanged(int)), this, SLOT(OnMaxCacheSizeChanged(int)) ); + connect( m_Controls->m_MaxTractLengthSlider, SIGNAL(valueChanged(int)), this, SLOT(OnMaxTractLengthChanged(int)) ); } } -void QmitkStochasticFiberTrackingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) +void QmitkStochasticFiberTrackingView::OnSeedsPerVoxelChanged(int value) { - m_MultiWidget = &stdMultiWidget; + m_Controls->m_SeedsPerVoxelLabel->setText(QString("Seeds per Voxel: ")+QString::number(value)); } - -void QmitkStochasticFiberTrackingView::StdMultiWidgetNotAvailable() +void QmitkStochasticFiberTrackingView::OnMaxTractLengthChanged(int value) { - m_MultiWidget = NULL; + m_Controls->m_MaxTractLengthLabel->setText(QString("Max. Tract Length: ")+QString::number(value)); } -/* This method refreshes the Status-Message and its corresponding filename of tableWidget - Input: tmpVec: contains either dwi-image-DataNode or seedImage-DataNodes - tmpStatus: flag if dataNode-vector contains correct nodes or not */ -void QmitkStochasticFiberTrackingView::refreshTableWidget(std::vector tmpVec , QString tmpStatus) +void QmitkStochasticFiberTrackingView::OnMaxCacheSizeChanged(int value) { - - for(int idw=0; idw<(int)tmpVec.size(); idw++){ - mitk::DataNode::Pointer tmpnode; - QTableWidgetItem *itemStatus = new QTableWidgetItem; - QTableWidgetItem *itemText = new QTableWidgetItem; - tmpnode = tmpVec.at(idw); - itemText->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter); - itemText->setText( tmpnode->GetName().c_str() ); - itemStatus->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter); - itemStatus->setText(tmpStatus); - if(tmpStatus.compare(qStatusErr) == 0){ - itemText->setTextColor(QColor(90, 0, 3, 255)); - itemStatus->setTextColor(QColor(90, 0, 3, 255)); - }else{ - itemText->setTextColor(QColor(92, 198, 10, 255)); - itemStatus->setTextColor(QColor(92, 198, 10, 255)); - } - /* take next available row */ - int row = m_Controls->tableWidget->rowCount(); - m_Controls->tableWidget->insertRow(row); - m_Controls->tableWidget->setItem(row,0,itemStatus); - m_Controls->tableWidget->setItem(row,1,itemText); - - } - + m_Controls->m_MaxCacheSizeLabel->setText(QString("Max. Cache Size: ")+QString::number(value)+"GB"); } -/* This method checks if given node is validSeed image*/ -bool QmitkStochasticFiberTrackingView::checkSeedROI( mitk::DataNode::Pointer node ) +void QmitkStochasticFiberTrackingView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget) { - bool isSeed = false; - QString qClassName = node->GetData()->GetNameOfClass(); - - /* propValue contains the result after calling GetPropertyValue - success contains the bool if desired propertyname is available or not */ - bool propValue = false; - bool success = node->GetPropertyValue("binary",propValue); - - if(qClassName.compare("Image") == 0 && success == true && propValue == true) - isSeed = true; - - return isSeed; + m_MultiWidget = &stdMultiWidget; } -/* This method checks if given node is dwi image*/ -bool QmitkStochasticFiberTrackingView::checkDWIType( mitk::DataNode::Pointer node ) -{ - bool isDwi = false; - QString qClassName = node->GetData()->GetNameOfClass(); // ie. TensorImage or DiffusionImage - if(qClassName.compare(qDiffStr) == 0) - isDwi = true; - return isDwi; +void QmitkStochasticFiberTrackingView::StdMultiWidgetNotAvailable() +{ + m_MultiWidget = NULL; } -/* OnSelectionChanged is registered to SelectionService, therefore no need to - implement SelectionService Listener explicitly */ - void QmitkStochasticFiberTrackingView::OnSelectionChanged( std::vector nodes ) { - //++++++++RESET GUI AND POINTER VECTORS+++++++++++++++ - /* clear GUI tableWidget */ - for( int i=m_Controls->tableWidget->rowCount(); i >= 0; --i) - { - m_Controls->tableWidget->removeRow(i); - } - - /* reset DWI selection vector */ - vPselDWImg.clear(); - vSeedROI.clear(); - //+++++++++++++++++++++++++++++++++++++++++++++++++++++ + m_DiffusionImage = NULL; + m_SeedRoi = NULL; + m_Controls->m_DiffusionImageLabel->setText("-"); + m_Controls->m_RoiImageLabel->setText("-"); - //############### HOMELAND SECURITY ################################ - /* When selection not empty, extract data of interest, - otherwise return */ - if(!nodes.empty()){ + if(nodes.empty()) + return; - /* Flag to set commandButton enabled or not - keep flag true until selection is not DWIImage */ - bool flag_execFTComd = true; - - /* checkpoint for singe Seedpoint track */ - // singleSeedpoint is depricated - // m_singleSeedpoint = false; //for debugging singleSeedpoint is init here, otherwise get boolean from GUI + for( std::vector::iterator it = nodes.begin(); it != nodes.end(); ++it ) + { + mitk::DataNode::Pointer node = *it; - for( std::vector::iterator it = nodes.begin(); - it != nodes.end(); ++it ) + if( node.IsNotNull() && dynamic_cast(node->GetData()) ) { - //flags needed for algorithm execution logic - bool isDWI = false; - bool isSeed = false; - mitk::DataNode::Pointer node = *it; - if( node.IsNotNull() && dynamic_cast(node->GetData()) ) + if( dynamic_cast*>(node->GetData()) ) { - /* Check and sort image types */ - isDWI = checkDWIType(node); - if( isDWI ){ - vPselDWImg.push_back(*it); - - } else if(!m_singleSeedpoint){ - isSeed = checkSeedROI(node); - if( isSeed ) - vSeedROI.push_back(*it); - - } //else single seedPoint - - } //end if node.IsNotNull && dynamic_cast mitkImage - } //end node iterator - - - //############### BORDER CONTROL ################################ - /* ++++++++ Logic to en/disable execution of Algorithm +++++++++++ - Requirements: 1 dwi Image, >=1 Seedimage(s) or 1 single seedpoint */ - if(vPselDWImg.size() > 1){ - flag_execFTComd = false; - std::cout << "TODO GUI Warning, too much dwi images selected \n"; - refreshTableWidget(vPselDWImg, qStatusErr); - - }else if(vPselDWImg.empty()){ - flag_execFTComd = false; - std::cout << "TODO GUI Warning, NO dwi image selected \n"; - - }else{ // exactly 1 node in vector - flag_execFTComd = true; - refreshTableWidget(vPselDWImg, qStatusOk); - } - - if(!m_singleSeedpoint){ - //no manual selection - - if(vSeedROI.empty()){ - flag_execFTComd = false; - std::cout << "TODO GUI Warning, NO seed image selected \n"; - }else{ - //color seedImages green - refreshTableWidget(vSeedROI, qSeed); + m_DiffusionImage = dynamic_cast*>(node->GetData()); + m_Controls->m_DiffusionImageLabel->setText(node->GetName().c_str()); + } + else + { + bool isBinary = false; + node->GetPropertyValue("binary", isBinary); + if (isBinary) + { + m_SeedRoi = dynamic_cast(node->GetData()); + m_Controls->m_RoiImageLabel->setText(node->GetName().c_str()); + } } - - } - - /* Logic to Dis-/Enable Execute-FiberTracking-Button */ - if (m_Controls->commandLinkButton->isEnabled()) - { - if(!flag_execFTComd) - m_Controls->commandLinkButton->setEnabled(false); - - } else if(flag_execFTComd){ - - m_Controls->commandLinkButton->setEnabled(true); - } - } else { // else statement of " if node.isEmpty() " - - /* Selection from datamanager is empty - therefore set commandButton disable if necessary */ - if(m_Controls->commandLinkButton->isEnabled()) - { - m_Controls->commandLinkButton->setEnabled(false); - return; } } + if(m_DiffusionImage.IsNotNull() && m_SeedRoi.IsNotNull()) + m_Controls->commandLinkButton->setEnabled(true); + else + m_Controls->commandLinkButton->setEnabled(false); } void QmitkStochasticFiberTrackingView::DoFiberTracking() { - - // for debugging use only first image node - mitk::DataNode::Pointer SpDWI = vPselDWImg.at(0); - - - - - // cast node to compatible type - mitk::DiffusionImage::Pointer dwiImg = dynamic_cast< mitk::DiffusionImage* >( SpDWI->GetData() ); - /* get Gradients/Direction of dwi */ - itk::VectorContainer< unsigned int, vnl_vector_fixed >::Pointer Pdir = dwiImg->GetDirections(); + itk::VectorContainer< unsigned int, vnl_vector_fixed >::Pointer Pdir = m_DiffusionImage->GetDirections(); /* bValueContainer, Container includes b-values according to corresponding gradient-direction*/ PTFilterType::bValueContainerType::Pointer vecCont = PTFilterType::bValueContainerType::New(); /* for each gradient set b-Value; for 0-gradient set b-value eq. 0 */ for ( int i=0; i<(int)Pdir->size(); ++i) { vnl_vector_fixed valsGrad = Pdir->at(i); if (valsGrad.get(0) == 0 && valsGrad.get(1) == 0 && valsGrad.get(2) == 0) { //set 0-Gradient to bValue 0 vecCont->InsertElement(i,0); }else{ - vecCont->InsertElement(i,dwiImg->GetB_Value()); + vecCont->InsertElement(i,m_DiffusionImage->GetB_Value()); } } - /* former variant without setting 0-Gradient to 0 - for(int i=0; iGetDirections()->Size(); i++) - vecCont->InsertElement(i,dwiImg->GetB_Value()); - */ - /* define measurement frame (identity-matrix 3x3) */ - PTFilterType::MeasurementFrameType measurement_frame; - measurement_frame.set_identity(); + PTFilterType::MeasurementFrameType measurement_frame = m_DiffusionImage->GetMeasurementFrame(); - /* generate white matterImage */ + /* generate white matterImage (dummy?)*/ FloatImageType::Pointer wmImage = FloatImageType::New(); - wmImage->SetSpacing( dwiImg->GetVectorImage()->GetSpacing() ); - wmImage->SetOrigin( dwiImg->GetVectorImage()->GetOrigin() ); - wmImage->SetDirection( dwiImg->GetVectorImage()->GetDirection() ); - wmImage->SetLargestPossibleRegion( dwiImg->GetVectorImage()->GetLargestPossibleRegion() ); + wmImage->SetSpacing( m_DiffusionImage->GetVectorImage()->GetSpacing() ); + wmImage->SetOrigin( m_DiffusionImage->GetVectorImage()->GetOrigin() ); + wmImage->SetDirection( m_DiffusionImage->GetVectorImage()->GetDirection() ); + wmImage->SetLargestPossibleRegion( m_DiffusionImage->GetVectorImage()->GetLargestPossibleRegion() ); wmImage->SetBufferedRegion( wmImage->GetLargestPossibleRegion() ); wmImage->SetRequestedRegion( wmImage->GetLargestPossibleRegion() ); wmImage->Allocate(); itk::ImageRegionIterator ot(wmImage, wmImage->GetLargestPossibleRegion() ); while (!ot.IsAtEnd()) { ot.Set(1); ++ot; } - /* init TractographyFilter, note: it's a smartpointer */ - PTFilterType::Pointer ptfilterPtr = PTFilterType::New(); - - ptfilterPtr->SetInput(dwiImg->GetVectorImage().GetPointer()); - ptfilterPtr->SetbValues(vecCont); - ptfilterPtr->SetGradients(Pdir); - ptfilterPtr->SetMeasurementFrame(measurement_frame); - ptfilterPtr->SetWhiteMatterProbabilityImageInput(wmImage); - /*** get parameters from GUI ... TODO check validity during user input ***/ - ptfilterPtr->SetTotalTracts(m_Controls->lineEdit_totalTracts->text().toInt()); - ptfilterPtr->SetMaxLikelihoodCacheSize(m_Controls->lineEdit_likelihood_cache->text().toInt()); - ptfilterPtr->SetMaxTractLength(m_Controls->lineEdit_maxTractLength->text().toInt()); - - - /* define seed Index manual */ - //PTFilterType::InputDWIImageType::IndexType seedIdx; - //seedIdx[0] = m_Controls->lineEdit_seedIndex1->text().toInt(); - //seedIdx[1] = m_Controls->lineEdit_seedIndex2->text().toInt(); - //seedIdx[2] = m_Controls->lineEdit_seedIndex3->text().toInt(); - - + /* init TractographyFilter */ + PTFilterType::Pointer trackingFilter = PTFilterType::New(); + trackingFilter->SetInput(m_DiffusionImage->GetVectorImage().GetPointer()); + trackingFilter->SetbValues(vecCont); + trackingFilter->SetGradients(Pdir); + trackingFilter->SetMeasurementFrame(measurement_frame); + trackingFilter->SetWhiteMatterProbabilityImageInput(wmImage); + trackingFilter->SetTotalTracts(m_Controls->m_SeedsPerVoxelSlider->value()); + trackingFilter->SetMaxLikelihoodCacheSize(m_Controls->m_MaxCacheSizeSlider->value()*1000); + trackingFilter->SetMaxTractLength(m_Controls->m_MaxTractLengthSlider->value()); - - /* SEEDPOINT/REGION PREPARATION */ m_tractcontainer = PTFilterType::TractContainerType::New(); - - - //int seedROIcnt = vSeedROI.size(); - - // ############## SEED OPERATIONS ######## - // todo iterate over all seed ROIs - /// for(int si=0; si(SpSeedR->GetData()); - - /* nice structure of fibers in datamanager */ -/* mitk::DataNode::Pointer roiParentNode; - roiParentNode = mitk::DataNode::New(); - roiParentNode->SetName("FiberBundle_ROI_1"); - roiParentNode->SetData(mitkSeed); - roiParentNode->SetVisibility(true); - - GetDataStorage()->Add(roiParentNode);*/ - - - //itk::Image< char, 3 > - mitk::ImageToItk< itk::Image< unsigned char, 3 > >::Pointer binaryImageToItk1 = mitk::ImageToItk< itk::Image< unsigned char, 3 > >::New(); - binaryImageToItk1->SetInput( mitkSeed ); + mitk::ImageToItk< itk::Image< unsigned char, 3 > >::Pointer binaryImageToItk1 = mitk::ImageToItk< itk::Image< unsigned char, 3 > >::New(); + binaryImageToItk1->SetInput( m_SeedRoi ); binaryImageToItk1->Update(); - - itk::ImageRegionConstIterator< BinaryImageType > it(binaryImageToItk1->GetOutput(), binaryImageToItk1->GetOutput()->GetRequestedRegion()); it.Begin(); while(!it.IsAtEnd()) { itk::ImageConstIterator::PixelType tmpPxValue = it.Get(); if(tmpPxValue != 0){ itk::ImageRegionConstIterator< BinaryImageType >::IndexType seedIdx = it.GetIndex(); - ptfilterPtr->SetSeedIndex(seedIdx); - ptfilterPtr->Update(); + trackingFilter->SetSeedIndex(seedIdx); + trackingFilter->Update(); /* get results from Filter */ /* write each single tract into member container */ - PTFilterType::TractContainerType::Pointer container_tmp = ptfilterPtr->GetOutputTractContainer(); - CImageType::Pointer cmap = ptfilterPtr->GetOutput(); - + PTFilterType::TractContainerType::Pointer container_tmp = trackingFilter->GetOutputTractContainer(); PTFilterType::TractContainerType::Iterator elIt = container_tmp->Begin(); PTFilterType::TractContainerType::Iterator end = container_tmp->End(); while( elIt != end ){ PTFilterType::TractContainerType::Element tract_tmp = elIt.Value(); m_tractcontainer->InsertElement(m_tractcontainer->Size(),tract_tmp); ++elIt; } } ++it; - } - // } /* allocate the VTK Polydata to output the tracts */ - vtkSmartPointer pts = vtkSmartPointer::New(); - - vtkSmartPointer cells = vtkSmartPointer::New(); - - float bounds[] = {0,0,0}; - bounds[0] = dwiImg->GetLargestPossibleRegion().GetSize().GetElement(0); - bounds[1] = dwiImg->GetLargestPossibleRegion().GetSize().GetElement(1); - bounds[2] = dwiImg->GetLargestPossibleRegion().GetSize().GetElement(2); - - - - mitk::FiberBundle::Pointer transformer = mitk::FiberBundle::New(); - transformer->additkStochTractContainer(m_tractcontainer); - transformer->initFiberGroup(); - transformer->SetGeometry(dwiImg->GetGeometry()); - transformer->SetBounds(bounds); - - - //transformer->debug_members(); - - //testing, get dti Fibers out of group - mitk::FiberBundle::FiberGroupType::Pointer fiberBundle = transformer->GetGroupFiberBundle(); - mitk::FiberBundle::ChildrenListType *fibersList = fiberBundle->GetChildren(); - for(mitk::FiberBundle::ChildrenListType::iterator itFibers = fibersList->begin(); - itFibers != fibersList->end(); - ++itFibers) - { - //we know we have DTITubeSpatialObjects stored in List - DTITubeType::Pointer dtiTract = dynamic_cast (itFibers->GetPointer()); - - - } - - mitk::DataNode::Pointer fbNode; - fbNode = mitk::DataNode::New(); - fbNode->SetData(transformer); - fbNode->SetName("GroupFinberBundle"); - fbNode->SetVisibility(true); - GetDataStorage()->Add(fbNode); + vtkSmartPointer vPoints = vtkSmartPointer::New(); + vtkSmartPointer vCellArray = vtkSmartPointer::New(); for( int i=0; i<(int)m_tractcontainer->Size(); i++ ) { - - /* for each iteration create a new dtiTube containing a list of its points */ - DTITubeType::Pointer dtiTube = DTITubeType::New(); - DTITubeType::PointListType list; - - mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); mitk::Point3D point; - PTFilterType::TractContainerType::Element tract = - m_tractcontainer->GetElement(i); - PTFilterType::TractContainerType::Element::ObjectType::VertexListType::ConstPointer vertexlist = - tract->GetVertexList(); + PTFilterType::TractContainerType::Element tract = m_tractcontainer->GetElement(i); + PTFilterType::TractContainerType::Element::ObjectType::VertexListType::ConstPointer vertexlist = tract->GetVertexList(); - /* create VTK points and PolyLine */ - - vtkSmartPointer polyLine = vtkSmartPointer::New(); - polyLine->GetPointIds()->SetNumberOfIds((int)vertexlist->Size()); - - unsigned long pntIdxHelper = pts->GetNumberOfPoints(); - - for( int j=0; j<(int)vertexlist->Size(); j++){ - - PTFilterType::TractContainerType::Element::ObjectType::VertexListType::Element vertex = - vertexlist->GetElement(j); - - float vertex_f[3] = {(float)vertex[0],(float)vertex[1],(float)vertex[2]}; - mitk::Point3D world(vertex_f); - - dwiImg->GetGeometry()->IndexToWorld(world, point); - - /* VTK add Points */ - double vertex_d[3] = {(double)vertex[0],(double)vertex[1],(double)vertex[2]}; - pts->InsertNextPoint(vertex_d); - polyLine->GetPointIds()->SetId(j,j+pntIdxHelper); + vtkSmartPointer vPolyLine = vtkSmartPointer::New(); + for( int j=0; j<(int)vertexlist->Size(); j++) + { + PTFilterType::TractContainerType::Element::ObjectType::VertexListType::Element vertex = vertexlist->GetElement(j); + mitk::Point3D index; + index[0] = (float)vertex[0]; + index[1] = (float)vertex[1]; + index[2] = (float)vertex[2]; + m_DiffusionImage->GetGeometry()->IndexToWorld(index, point); + vtkIdType id = vPoints->InsertNextPoint(point.GetDataPointer()); + vPolyLine->GetPointIds()->InsertNextId(id); } - - - /* dtiTubes - dtiTube->GetProperty()->SetName("dtiTube"); - dtiTube->SetId(i); - dtiTube->SetPoints(list); - myFiberScene->AddSpatialObject(dtiTube);*/ - - - /* VTK add line */ - cells->InsertNextCell(polyLine); - - - - /*mitk::DataNode::Pointer curveNode; - curveNode = mitk::DataNode::New(); - curveNode->SetData(spline); - curveNode->SetName("Fiber"); - curveNode->SetVisibility(true); - GetDataStorage()->Add(curveNode, roiParentNode); - */ - - mitk::Point3D newIdx3D; - - - // std::cout << "cross position world: " << m_MultiWidget->GetCrossPosition() << "\n" ; - // std::cout << "cross position index: " << newIdx3D << "\n" ; - - + vCellArray->InsertNextCell(vPolyLine); } + vtkSmartPointer fiberPolyData = vtkSmartPointer::New(); + fiberPolyData->SetPoints(vPoints); + fiberPolyData->SetLines(vCellArray); - /* - ////////////// - // Klaus' Code - - ////////////////////// - // Generate RGBA Image - typedef itk::RGBAPixel OutPixType; - - // run generator - typedef itk::TractsToProbabilityImageFilter ImageGeneratorType; - ImageGeneratorType::Pointer generator = ImageGeneratorType::New(); - generator->SetInput(wmImage); - generator->SetTractContainer(m_tractcontainer); - generator->SetUpsamplingFactor(20); - generator->SetMinTractLength(10); - //generator->Update(); - - // get result - typedef itk::Image OutType; - OutType::Pointer outImg = generator->GetOutput(); - - mitk::Image::Pointer img = mitk::Image::New(); - img->InitializeByItk(outImg.GetPointer()); - img->SetVolume(outImg->GetBufferPointer()); - - // write to datastorage - mitk::DataNode::Pointer node1 = mitk::DataNode::New(); - node1->SetData(img); - node1->SetName("RgbImage"); - node1->SetVisibility(true); - - mitk::LevelWindow opaclevwin; - opaclevwin.SetRangeMinMax(0,255); - opaclevwin.SetWindowBounds(0,0); - mitk::LevelWindowProperty::Pointer prop = mitk::LevelWindowProperty::New(opaclevwin); - node1->AddProperty( "opaclevelwindow", prop ); - - GetDataStorage()->Add(node1); - - /////////////////////////////// - // Generate unsigned char Image - typedef unsigned char OutPixType2; - - // run generator - typedef itk::TractsToProbabilityImageFilter ImageGeneratorType2; - ImageGeneratorType2::Pointer generator2 = ImageGeneratorType2::New(); - generator2->SetInput(wmImage); - generator2->SetTractContainer(m_tractcontainer); - generator2->SetUpsamplingFactor(20); - generator2->SetMinTractLength(10); - generator2->Update(); - - // get result - typedef itk::Image OutType2; - OutType2::Pointer outImg2 = generator2->GetOutput(); - - mitk::Image::Pointer img2 = mitk::Image::New(); - img2->InitializeByItk(outImg2.GetPointer()); - img2->SetVolume(outImg2->GetBufferPointer()); - - // to datastorage - mitk::DataNode::Pointer node2 = mitk::DataNode::New(); - node2->SetData(img2); - node2->SetName("ProbImage"); - node2->SetVisibility(true); - - mitk::LevelWindow opaclevwin2; - opaclevwin2.SetRangeMinMax(0,255); - opaclevwin2.SetWindowBounds(0,0); - mitk::LevelWindowProperty::Pointer prop2 = mitk::LevelWindowProperty::New(opaclevwin2); - node2->AddProperty( "opaclevelwindow", prop2 ); - - GetDataStorage()->Add(node2); - */ - - GetDataStorage()->Modified(); - - m_MultiWidget->RequestUpdate(); - - - /* - vtkSmartPointer linesPolyData = vtkSmartPointer::New(); - - linesPolyData->SetPoints(pts); - linesPolyData->SetLines(cells); - - //setup actor and mapper - vtkSmartPointer mapper = - vtkSmartPointer::New(); - mapper->SetInput(linesPolyData); - - vtkSmartPointer actor = - vtkSmartPointer::New(); - actor->SetMapper(mapper); - - //setup render window, renderer, and interactor - vtkSmartPointer renderer = - vtkSmartPointer::New(); - vtkSmartPointer renderWindow = - vtkSmartPointer::New(); - renderWindow->AddRenderer(renderer); - vtkSmartPointer renderWindowInteractor = - vtkSmartPointer::New(); - renderWindowInteractor->SetRenderWindow(renderWindow); - renderer->AddActor(actor); - - renderWindow->Render(); - renderWindowInteractor->Start(); - - */ - + mitk::FiberBundleX::Pointer fib = mitk::FiberBundleX::New(fiberPolyData); + mitk::DataNode::Pointer fbNode = mitk::DataNode::New(); + fbNode->SetData(fib); + fbNode->SetName("GroupFinberBundle"); + fbNode->SetVisibility(true); + GetDataStorage()->Add(fbNode); } diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.h b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.h index 4595c0560a..34f31895ba 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.h +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingView.h @@ -1,125 +1,102 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ Version: $Revision: 21975 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef QmitkStochasticFiberTrackingView_h #define QmitkStochasticFiberTrackingView_h #include #include - #include -#include #include "ui_QmitkStochasticFiberTrackingViewControls.h" -#include -#include - #include -#include - #include + +#include +#include #include #include #include - -#include - - - - - +#include //define the input/output types typedef itk::VectorImage< short int, 3 > DWIVectorImageType; typedef itk::Image< float, 3 > FloatImageType; typedef itk::Image< unsigned int, 3 > CImageType; typedef itk::StochasticTractographyFilter< DWIVectorImageType, FloatImageType, CImageType > PTFilterType; typedef itk::DTITubeSpatialObject<3> DTITubeType; typedef itk::DTITubeSpatialObjectPoint<3> DTITubePointType; typedef itk::SceneSpatialObject<3> SceneSpatialObjectType; /*! \brief QmitkFiberTrackingView \warning This application module is not yet documented. Use "svn blame/praise/annotate" and ask the author to provide basic documentation. \sa QmitkFunctionality \ingroup Functionalities */ -class /*MitkDiffusionImaging_EXPORT*/ QmitkStochasticFiberTrackingView : public QmitkFunctionality +class QmitkStochasticFiberTrackingView : 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; QmitkStochasticFiberTrackingView(); virtual ~QmitkStochasticFiberTrackingView(); virtual void CreateQtPartControl(QWidget *parent); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: - /// \brief Called when the user clicks the GUI button void DoFiberTracking(); -// void handleAlgoSelection(); - - protected: /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( std::vector nodes ); - Ui::QmitkStochasticFiberTrackingViewControls* m_Controls; - QmitkStdMultiWidget* m_MultiWidget; -private: +protected slots: + + void OnSeedsPerVoxelChanged(int value); + void OnMaxTractLengthChanged(int value); + void OnMaxCacheSizeChanged(int value); +private: -// \brief vector containing related (DiffusionImage) nodes of interest - std::vector vPselDWImg; -// \brief vector containing SeedRegions(binary) nodes of interest - std::vector vSeedROI; + mitk::Image::Pointer m_SeedRoi; + mitk::DiffusionImage::Pointer m_DiffusionImage; -// \brief flag to de-/activate manual seedPoint index-coordinates - bool m_singleSeedpoint; - bool checkDWIType( mitk::DataNode::Pointer ); - void refreshTableWidget(std::vector , QString ); - bool checkSeedROI( mitk::DataNode::Pointer ); typedef itk::Image< unsigned char, 3 > BinaryImageType; - // \brief container storing all found tracts PTFilterType::TractContainerType::Pointer m_tractcontainer; - - }; #endif // _QMITKFIBERTRACKINGVIEW_H_INCLUDED diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingViewControls.ui b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingViewControls.ui index 3f1a1be865..7d32869673 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingViewControls.ui +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimaging/src/internal/QmitkStochasticFiberTrackingViewControls.ui @@ -1,173 +1,200 @@ QmitkStochasticFiberTrackingViewControls 0 0 - 290 - 331 + 480 + 553 0 0 QmitkTemplate - - - - - Selected Image(s) - + + + + + Data + + + + + + Diffusion Image: + + + + + + + - + + + + + + + ROI Image: + + + + + + + - + + + + - - - - true - - - - 204 - 0 - - - - QFrame::StyledPanel - - - true - - - Qt::NoPen - - - true - - - - Status - - - - - FileName - - + + + + Parameters + + + + + + Maximum tract length in voxel + + + 1 + + + 500 + + + 100 + + + Qt::Horizontal + + + + + + + Length of single tracts + + + Max. Tract Length: 100 + + + + + + + Number of tracts for each seedpoint + + + Seeds per Voxel: 1 + + + + + + + Likelihood cache in Megabytes + + + Max. Chache Size: 1GB + + + + + + + Number of tracts started in each voxel of the seed ROI + + + 1 + + + 10 + + + Qt::Horizontal + + + + + + + 1 + + + 10 + + + 1 + + + Qt::Horizontal + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 200 + 0 + + + + + - - - - Qt::Horizontal - - - - 12 - 20 - - - - - + false - execute stochastic fiber tracking + Start Tracking - + Qt::Vertical QSizePolicy::Expanding 20 220 - - - - Length of single tracts - - - tarct length - - - - - - - define length of single tract - - - 50 - - - - - - - Number of tracts for each seedpoint - - - # of tracts - - - - - - - define number of tracts for each seedpoint - - - 1 - - - - - - - Likelihood cache in Megabytes - - - cache (MB) - - - - - - - define likelihood cache in Megabytes - - - 500 - - - - tableWidget commandLinkButton diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/files.cmake b/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/files.cmake index 9cb5a6290f..373f0964d1 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/files.cmake +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/files.cmake @@ -1,96 +1,98 @@ SET(SRC_CPP_FILES QmitkDiffusionImagingAppApplication.cpp QmitkDiffusionImagingAppWorkbenchAdvisor.cpp ) SET(INTERNAL_CPP_FILES mitkPluginActivator.cpp QmitkDiffusionImagingAppIntroPart.cpp QmitkDiffusionImagingAppPerspective.cpp QmitkWelcomePerspective.cpp QmitkDIAppConnectomicsPerspective.cpp QmitkDIAppDicomImportPerspective.cpp QmitkDIAppFiberTractographyPerspective.cpp QmitkDIAppIVIMPerspective.cpp QmitkDIAppPreprocessingReconstructionPerspective.cpp QmitkDIAppQuantificationPerspective.cpp QmitkDIAppScreenshotsMoviesPerspective.cpp QmitkDIAppTBSSPerspective.cpp QmitkDIAppVolumeVisualizationPerspective.cpp + QmitkDIAppTrackingEvaluationPerspective.cpp ) SET(UI_FILES src/internal/QmitkWelcomeScreenViewControls.ui ) SET(MOC_H_FILES src/internal/QmitkDiffusionImagingAppIntroPart.h src/internal/mitkPluginActivator.h src/QmitkDiffusionImagingAppApplication.h src/internal/QmitkDiffusionImagingAppPerspective.h src/internal/QmitkWelcomePerspective.h src/internal/QmitkDIAppConnectomicsPerspective.h src/internal/QmitkDIAppDicomImportPerspective.h src/internal/QmitkDIAppFiberTractographyPerspective.h src/internal/QmitkDIAppIVIMPerspective.h src/internal/QmitkDIAppPreprocessingReconstructionPerspective.h src/internal/QmitkDIAppQuantificationPerspective.h src/internal/QmitkDIAppScreenshotsMoviesPerspective.h src/internal/QmitkDIAppTBSSPerspective.h src/internal/QmitkDIAppVolumeVisualizationPerspective.h + src/internal/QmitkDIAppTrackingEvaluationPerspective.h ) SET(CACHED_RESOURCE_FILES # list of resource files which can be used by the plug-in # system without loading the plug-ins shared library, # for example the icon used in the menu and tabs for the # plug-in views in the workbench plugin.xml resources/icon_dicom.xpm resources/diffusionimaging.png resources/preprocessing.png resources/Measurement_48.png resources/volvis.png resources/perspectives/diffusionimaging.png resources/perspectives/icon_home.png resources/perspectives/connectomics.png resources/perspectives/dicomimport.png resources/perspectives/tractography.png resources/perspectives/ivim.png resources/perspectives/preprocessingreconstruction.png resources/perspectives/quantification.png resources/perspectives/screenshotsmovies.png resources/perspectives/tbss.png resources/perspectives/volumevizualization.png ) SET(QRC_FILES # uncomment the following line if you want to use Qt resources resources/welcome/QmitkWelcomeScreenView.qrc resources/org_mitk_gui_qt_diffusionimagingapp.qrc ) # SET(CPP_FILES) foreach(file ${SRC_CPP_FILES}) SET(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) SET(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) #----------- Qt Help Collection Project -------------# IF (BLUEBERRY_USE_QT_HELP) SET(_plugin_qhcp_input "${CMAKE_CURRENT_SOURCE_DIR}/documentation/MitkDiffusionImagingAppQtHelpCollectionProject.qhcp") SET(_plugin_qhcp_output "${CMAKE_CURRENT_BINARY_DIR}/MitkDiffusionImagingAppQtHelpCollection.qhc") ADD_CUSTOM_COMMAND(OUTPUT ${_plugin_qhcp_output} COMMAND ${QT_COLLECTIONGENERATOR_EXECUTABLE} ${_plugin_qhcp_input} -o ${_plugin_qhcp_output} DEPENDS ${_plugin_qhcp_input} ) LIST(APPEND CACHED_RESOURCE_FILES ${_plugin_qhcp_output}) #SET(FILE_DEPENDENCIES ${_plugin_qhcp_output}) ENDIF() diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/plugin.xml b/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/plugin.xml index 174abdcf6d..d4c20d714a 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/plugin.xml +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/plugin.xml @@ -1,69 +1,73 @@ + diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDIAppTrackingEvaluationPerspective.cpp b/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDIAppTrackingEvaluationPerspective.cpp new file mode 100644 index 0000000000..fcd0d3dc94 --- /dev/null +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDIAppTrackingEvaluationPerspective.cpp @@ -0,0 +1,49 @@ +/*========================================================================= + + Program: BlueBerry Platform + Language: C++ + Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ + Version: $Revision: 19652 $ + + Copyright (c) German Cancer Research Center, Division of Medical and + Biological Informatics. All rights reserved. + See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ + +#include "QmitkDIAppTrackingEvaluationPerspective.h" +#include "berryIViewLayout.h" + +void QmitkDIAppTrackingEvaluationPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) +{ + ///////////////////////////////////////////////////// + // all di-app perspectives should have the following: + ///////////////////////////////////////////////////// + + std::string editorArea = layout->GetEditorArea(); + + layout->AddStandaloneView("org.mitk.views.datamanager", + false, berry::IPageLayout::LEFT, 0.3f, editorArea); + + layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview", + false, berry::IPageLayout::BOTTOM, .2f, "org.mitk.views.datamanager"); + + berry::IFolderLayout::Pointer left = + layout->CreateFolder("org.mitk.diffusionimaginginternal.leftcontrols", + berry::IPageLayout::BOTTOM, 0.15f, "org.mitk.views.controlvisualizationpropertiesview"); + + layout->AddStandaloneView("org.mitk.views.imagenavigator", + false, berry::IPageLayout::BOTTOM, .4f, "org.mitk.diffusionimaginginternal.leftcontrols"); + + ///////////////////////////////////////////// + // here goes the perspective specific stuff + ///////////////////////////////////////////// + + left->AddView("org.mitk.views.artificialqballevaluation"); + berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.artificialqballevaluation"); + lo->SetCloseable(false); +} diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDIAppTrackingEvaluationPerspective.h b/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDIAppTrackingEvaluationPerspective.h new file mode 100644 index 0000000000..327ae819be --- /dev/null +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/src/internal/QmitkDIAppTrackingEvaluationPerspective.h @@ -0,0 +1,42 @@ +/*========================================================================= + + Program: BlueBerry Platform + Language: C++ + Date: $Date: 2009-10-23 02:59:36 +0200 (Fr, 23 Okt 2009) $ + Version: $Revision: 19652 $ + + Copyright (c) German Cancer Research Center, Division of Medical and + Biological Informatics. All rights reserved. + See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ + + +#ifndef QmitkDIAppTrackingEvaluationPerspective_H_ +#define QmitkDIAppTrackingEvaluationPerspective_H_ + +#include + +class QmitkDIAppTrackingEvaluationPerspective : public QObject, public berry::IPerspectiveFactory +{ + Q_OBJECT + Q_INTERFACES(berry::IPerspectiveFactory) + +public: + + QmitkDIAppTrackingEvaluationPerspective() {} + QmitkDIAppTrackingEvaluationPerspective(const QmitkDIAppTrackingEvaluationPerspective& other) + { + Q_UNUSED(other) + throw std::runtime_error("Copy constructor not implemented"); + } + ~QmitkDIAppTrackingEvaluationPerspective() {} + + void CreateInitialLayout(berry::IPageLayout::Pointer layout); +}; + +#endif /* QmitkDIAppTrackingEvaluationPerspective_H_ */ diff --git a/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/src/internal/mitkPluginActivator.cpp b/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/src/internal/mitkPluginActivator.cpp index c08bb4b388..b251a54b97 100644 --- a/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/src/internal/mitkPluginActivator.cpp +++ b/Modules/Bundles/org.mitk.gui.qt.diffusionimagingapp/src/internal/mitkPluginActivator.cpp @@ -1,136 +1,138 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkPluginActivator.h" #include #include #include #include "src/QmitkDiffusionImagingAppApplication.h" #include "QmitkWelcomePerspective.h" #include "src/internal/QmitkDiffusionImagingAppIntroPart.h" #include "src/internal/QmitkDiffusionImagingAppPerspective.h" #include "src/internal/QmitkDIAppConnectomicsPerspective.h" #include "src/internal/QmitkDIAppDicomImportPerspective.h" #include "src/internal/QmitkDIAppFiberTractographyPerspective.h" #include "src/internal/QmitkDIAppIVIMPerspective.h" #include "src/internal/QmitkDIAppPreprocessingReconstructionPerspective.h" #include "src/internal/QmitkDIAppQuantificationPerspective.h" #include "src/internal/QmitkDIAppScreenshotsMoviesPerspective.h" #include "src/internal/QmitkDIAppTBSSPerspective.h" #include "src/internal/QmitkDIAppVolumeVisualizationPerspective.h" +#include "src/internal/QmitkDIAppTrackingEvaluationPerspective.h" #include #include mitkPluginActivator* mitkPluginActivator::inst = 0; mitkPluginActivator::mitkPluginActivator() : pluginListener(0) { inst = this; } mitkPluginActivator::~mitkPluginActivator() { delete pluginListener; } mitkPluginActivator* mitkPluginActivator::GetDefault() { return inst; } void mitkPluginActivator::start(ctkPluginContext* context) { berry::AbstractUICTKPlugin::start(context); this->context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkDiffusionImagingAppApplication, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDiffusionImagingAppIntroPart, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDiffusionImagingAppPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkWelcomePerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppConnectomicsPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppDicomImportPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppFiberTractographyPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppIVIMPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppPreprocessingReconstructionPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppQuantificationPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppScreenshotsMoviesPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppTBSSPerspective, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppVolumeVisualizationPerspective, context) + BERRY_REGISTER_EXTENSION_CLASS(QmitkDIAppTrackingEvaluationPerspective, context) delete pluginListener; pluginListener = new berry::QCHPluginListener(context); context->connectPluginListener(pluginListener, SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection); // register all QCH files from all the currently installed plugins pluginListener->processPlugins(); } QString mitkPluginActivator::GetQtHelpCollectionFile() const { if (!helpCollectionFile.isEmpty()) { return helpCollectionFile; } QString collectionFilename; QString na("n/a"); // if (na != MITK_REVISION) // collectionFilename = "MitkDiffusionImagingAppQtHelpCollection_" MITK_REVISION ".qhc"; // else collectionFilename = "MitkDiffusionImagingAppQtHelpCollection.qhc"; QFileInfo collectionFileInfo = context->getDataFile(collectionFilename); QFileInfo pluginFileInfo = QFileInfo(QUrl(context->getPlugin()->getLocation()).toLocalFile()); if (!collectionFileInfo.exists() || pluginFileInfo.lastModified() > collectionFileInfo.lastModified()) { // extract the qhc file from the plug-in QByteArray content = context->getPlugin()->getResource(collectionFilename); if (content.isEmpty()) { BERRY_WARN << "Could not get plug-in resource: " << collectionFilename.toStdString(); } else { QFile file(collectionFileInfo.absoluteFilePath()); file.open(QIODevice::WriteOnly); file.write(content); file.close(); } } if (QFile::exists(collectionFileInfo.absoluteFilePath())) { helpCollectionFile = collectionFileInfo.absoluteFilePath(); } return helpCollectionFile; } Q_EXPORT_PLUGIN2(org_mitk_gui_qt_diffusionimagingapp, mitkPluginActivator) diff --git a/Modules/DiffusionImaging/Algorithms/itkTractDensityImageFilter.cpp b/Modules/DiffusionImaging/Algorithms/itkTractDensityImageFilter.cpp new file mode 100644 index 0000000000..69cc220f6e --- /dev/null +++ b/Modules/DiffusionImaging/Algorithms/itkTractDensityImageFilter.cpp @@ -0,0 +1,200 @@ +#include "itkTractDensityImageFilter.h" + +// VTK +#include +#include +#include + +// misc +#include + +namespace itk{ + + template< class OutputImageType > + TractDensityImageFilter< OutputImageType >::TractDensityImageFilter() + : m_BinaryOutput(false) + , m_InvertImage(false) + , m_UpsamplingFactor(1) + , m_InputImage(NULL) + , m_UseImageGeometry(false) + { + + } + + template< class OutputImageType > + TractDensityImageFilter< OutputImageType >::~TractDensityImageFilter() + { + } + + template< class OutputImageType > + itk::Point TractDensityImageFilter< OutputImageType >::GetItkPoint(double point[3]) + { + itk::Point itkPoint; + itkPoint[0] = point[0]; + itkPoint[1] = point[1]; + itkPoint[2] = point[2]; + return itkPoint; + } + + template< class OutputImageType > + void TractDensityImageFilter< OutputImageType >::GenerateData() + { + // generate upsampled image + mitk::Geometry3D::Pointer geometry = m_FiberBundle->GetGeometry(); + typename OutputImageType::Pointer outImage = this->GetOutput(); + + // calculate new image parameters + mitk::Vector3D newSpacing; + mitk::Point3D newOrigin; + itk::Matrix newDirection; + ImageRegion<3> upsampledRegion; + if (m_UseImageGeometry && !m_InputImage.IsNull()) + { + newSpacing = m_InputImage->GetSpacing()/m_UpsamplingFactor; + upsampledRegion = m_InputImage->GetLargestPossibleRegion(); + newOrigin = m_InputImage->GetOrigin(); + typename OutputImageType::RegionType::SizeType size = upsampledRegion.GetSize(); + size[0] *= m_UpsamplingFactor; + size[1] *= m_UpsamplingFactor; + size[2] *= m_UpsamplingFactor; + upsampledRegion.SetSize(size); + newDirection = m_InputImage->GetDirection(); + } + else + { + newSpacing = geometry->GetSpacing()/m_UpsamplingFactor; + newOrigin = geometry->GetOrigin(); + mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds(); + newOrigin[0] += bounds.GetElement(0); + newOrigin[1] += bounds.GetElement(2); + newOrigin[2] += bounds.GetElement(4); + + for (int i=0; i<3; i++) + for (int j=0; j<3; j++) + newDirection[j][i] = geometry->GetMatrixColumn(i)[j]; + upsampledRegion.SetSize(0, geometry->GetExtent(0)*m_UpsamplingFactor); + upsampledRegion.SetSize(1, geometry->GetExtent(1)*m_UpsamplingFactor); + upsampledRegion.SetSize(2, geometry->GetExtent(2)*m_UpsamplingFactor); + } + typename OutputImageType::RegionType::SizeType upsampledSize = upsampledRegion.GetSize(); + + // apply new image parameters + outImage->SetSpacing( newSpacing ); + outImage->SetOrigin( newOrigin ); + outImage->SetDirection( newDirection ); + outImage->SetRegions( upsampledRegion ); + outImage->Allocate(); + + int w = upsampledSize[0]; + int h = upsampledSize[1]; + int d = upsampledSize[2]; + + // set/initialize output + OutPixelType* outImageBufferPointer = (OutPixelType*)outImage->GetBufferPointer(); + for (int i=0; iGetDeepCopy(); + m_FiberBundle->ResampleFibers(minSpacing/10); + + vtkSmartPointer fiberPolyData = m_FiberBundle->GetFiberPolyData(); + vtkSmartPointer vLines = fiberPolyData->GetLines(); + vLines->InitTraversal(); + + int numFibers = m_FiberBundle->GetNumFibers(); + for( int i=0; iGetNextCell ( numPoints, points ); + + // fill output image + for( int j=0; j vertex = GetItkPoint(fiberPolyData->GetPoint(points[j])); + itk::Index<3> index; + itk::ContinuousIndex contIndex; + outImage->TransformPhysicalPointToIndex(vertex, index); + outImage->TransformPhysicalPointToContinuousIndex(vertex, contIndex); + + float frac_x = contIndex[0] - index[0]; + float frac_y = contIndex[1] - index[1]; + float frac_z = contIndex[2] - index[2]; + + int px = index[0]; + if (frac_x<0) + { + px -= 1; + frac_x += 1; + } + + int py = index[1]; + if (frac_y<0) + { + py -= 1; + frac_y += 1; + } + + int pz = index[2]; + if (frac_z<0) + { + pz -= 1; + frac_z += 1; + } + + // int coordinates inside image? + if (px < 0 || px >= w-1) + continue; + if (py < 0 || py >= h-1) + continue; + if (pz < 0 || pz >= d-1) + continue; + + if (m_BinaryOutput) + { + outImageBufferPointer[( px + w*(py + h*pz ))] = 1; + outImageBufferPointer[( px + w*(py+1+ h*pz ))] = 1; + outImageBufferPointer[( px + w*(py + h*pz+h))] = 1; + outImageBufferPointer[( px + w*(py+1+ h*pz+h))] = 1; + outImageBufferPointer[( px+1 + w*(py + h*pz ))] = 1; + outImageBufferPointer[( px+1 + w*(py + h*pz+h))] = 1; + outImageBufferPointer[( px+1 + w*(py+1+ h*pz ))] = 1; + outImageBufferPointer[( px+1 + w*(py+1+ h*pz+h))] = 1; + } + else + { + outImageBufferPointer[( px + w*(py + h*pz ))] += ( frac_x)*( frac_y)*( frac_z); + outImageBufferPointer[( px + w*(py+1+ h*pz ))] += ( frac_x)*(1-frac_y)*( frac_z); + outImageBufferPointer[( px + w*(py + h*pz+h))] += ( frac_x)*( frac_y)*(1-frac_z); + outImageBufferPointer[( px + w*(py+1+ h*pz+h))] += ( frac_x)*(1-frac_y)*(1-frac_z); + outImageBufferPointer[( px+1 + w*(py + h*pz ))] += (1-frac_x)*( frac_y)*( frac_z); + outImageBufferPointer[( px+1 + w*(py + h*pz+h))] += (1-frac_x)*( frac_y)*(1-frac_z); + outImageBufferPointer[( px+1 + w*(py+1+ h*pz ))] += (1-frac_x)*(1-frac_y)*( frac_z); + outImageBufferPointer[( px+1 + w*(py+1+ h*pz+h))] += (1-frac_x)*(1-frac_y)*(1-frac_z); + } + } + } + if (!m_BinaryOutput) + { + OutPixelType max = 0; + for (int i=0; i0) + for (int i=0; i +#include +#include +#include +#include + +namespace itk{ + +template< class OutputImageType > +class TractDensityImageFilter : public ImageSource< OutputImageType > +{ + +public: + typedef TractDensityImageFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + typedef typename OutputImageType::PixelType OutPixelType; + + itkNewMacro(Self); + itkTypeMacro( TractDensityImageFilter, ImageSource ); + + /** Upsampling factor **/ + itkSetMacro( UpsamplingFactor, unsigned int); + itkGetMacro( UpsamplingFactor, unsigned int); + + /** Invert Image **/ + itkSetMacro( InvertImage, bool); + itkGetMacro( InvertImage, bool); + + /** Binary Output **/ + itkSetMacro( BinaryOutput, bool); + itkGetMacro( BinaryOutput, bool); + + /** Use input image geometry to initialize output image **/ + itkSetMacro( UseImageGeometry, bool); + itkGetMacro( UseImageGeometry, bool); + + itkSetMacro( FiberBundle, mitk::FiberBundleX::Pointer); + itkSetMacro( InputImage, typename OutputImageType::Pointer); + + void GenerateData(); + +protected: + + itk::Point GetItkPoint(double point[3]); + + TractDensityImageFilter(); + virtual ~TractDensityImageFilter(); + + typename OutputImageType::Pointer m_InputImage; + mitk::FiberBundleX::Pointer m_FiberBundle; + unsigned int m_UpsamplingFactor; + bool m_InvertImage; + bool m_BinaryOutput; + bool m_UseImageGeometry; +}; + +} + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkTractDensityImageFilter.cpp" +#endif + +#endif // __itkTractDensityImageFilter_h__ diff --git a/Modules/DiffusionImaging/Algorithms/itkTractsToFiberEndingsImageFilter.cpp b/Modules/DiffusionImaging/Algorithms/itkTractsToFiberEndingsImageFilter.cpp index 8a232aad6e..ca729da0ff 100644 --- a/Modules/DiffusionImaging/Algorithms/itkTractsToFiberEndingsImageFilter.cpp +++ b/Modules/DiffusionImaging/Algorithms/itkTractsToFiberEndingsImageFilter.cpp @@ -1,137 +1,135 @@ #include "itkTractsToFiberEndingsImageFilter.h" -#include "itkBSplineUpsampleImageFilter.h" - -#define __CEIL_UCHAR__(val) (val) = \ -( (val) < 0 ) ? ( 0 ) : ( ( (val)>255 ) ? ( 255 ) : ( (val) ) ); +// VTK +#include +#include +#include namespace itk{ - template< class TInputImage, class TOutputPixelType > - TractsToFiberEndingsImageFilter< TInputImage, TOutputPixelType > - ::TractsToFiberEndingsImageFilter() + template< class OutputImageType > + TractsToFiberEndingsImageFilter< OutputImageType >::TractsToFiberEndingsImageFilter() + : m_InvertImage(false) + , m_UpsamplingFactor(1) + , m_InputImage(NULL) + , m_UseImageGeometry(false) { - this->SetNumberOfRequiredInputs(0); + } - template< class TInputImage, class TOutputPixelType > - TractsToFiberEndingsImageFilter< TInputImage, TOutputPixelType > - ::~TractsToFiberEndingsImageFilter() + template< class OutputImageType > + TractsToFiberEndingsImageFilter< OutputImageType >::~TractsToFiberEndingsImageFilter() { } - template< class TInputImage, class TOutputPixelType > - void TractsToFiberEndingsImageFilter< TInputImage, TOutputPixelType > - ::GenerateData() + template< class OutputImageType > + itk::Point TractsToFiberEndingsImageFilter< OutputImageType >::GetItkPoint(double point[3]) { - MITK_INFO << "Generating 2D fiber endings image"; - if(&typeid(TOutputPixelType) != &typeid(unsigned char)) - { - MITK_INFO << "Only 'unsigned char' and 'itk::RGBAPixel supported as OutputPixelType"; - return; - } - mitk::Geometry3D::Pointer geometry = m_FiberBundle->GetGeometry(); - - typename OutputImageType::Pointer outImage = - static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0)); + itk::Point itkPoint; + itkPoint[0] = point[0]; + itkPoint[1] = point[1]; + itkPoint[2] = point[2]; + return itkPoint; + } - outImage->SetSpacing( geometry->GetSpacing()/m_UpsamplingFactor ); // Set the image spacing + template< class OutputImageType > + void TractsToFiberEndingsImageFilter< OutputImageType >::GenerateData() + { + // generate upsampled image + mitk::Geometry3D::Pointer geometry = m_FiberBundle->GetGeometry(); + typename OutputImageType::Pointer outImage = this->GetOutput(); - mitk::Point3D origin = geometry->GetOrigin(); - mitk::Point3D indexOrigin; - geometry->WorldToIndex(origin, indexOrigin); - indexOrigin[0] = indexOrigin[0] - .5 * (1.0-1.0/m_UpsamplingFactor); - indexOrigin[1] = indexOrigin[1] - .5 * (1.0-1.0/m_UpsamplingFactor); - indexOrigin[2] = indexOrigin[2] - .5 * (1.0-1.0/m_UpsamplingFactor); + // calculate new image parameters + mitk::Vector3D newSpacing; mitk::Point3D newOrigin; - geometry->IndexToWorld(indexOrigin, newOrigin); - - outImage->SetOrigin( newOrigin ); // Set the image origin - - itk::Matrix matrix; - for (int i=0; i<3; i++) - for (int j=0; j<3; j++) - matrix[j][i] = geometry->GetMatrixColumn(i)[j]/geometry->GetSpacing().GetElement(i); - outImage->SetDirection( matrix ); // Set the image direction - - float* bounds = m_FiberBundle->GetBounds(); + itk::Matrix newDirection; ImageRegion<3> upsampledRegion; - upsampledRegion.SetSize(0, bounds[0]); - upsampledRegion.SetSize(1, bounds[1]); - upsampledRegion.SetSize(2, bounds[2]); - - typename InputImageType::RegionType::SizeType upsampledSize = upsampledRegion.GetSize(); - for (unsigned int n = 0; n < 3; n++) + if (m_UseImageGeometry && !m_InputImage.IsNull()) { - upsampledSize[n] = upsampledSize[n] * m_UpsamplingFactor; + newSpacing = m_InputImage->GetSpacing()/m_UpsamplingFactor; + upsampledRegion = m_InputImage->GetLargestPossibleRegion(); + newOrigin = m_InputImage->GetOrigin(); + typename OutputImageType::RegionType::SizeType size = upsampledRegion.GetSize(); + size[0] *= m_UpsamplingFactor; + size[1] *= m_UpsamplingFactor; + size[2] *= m_UpsamplingFactor; + upsampledRegion.SetSize(size); + newDirection = m_InputImage->GetDirection(); } - upsampledRegion.SetSize( upsampledSize ); - outImage->SetRegions( upsampledRegion ); + else + { + newSpacing = geometry->GetSpacing()/m_UpsamplingFactor; + newOrigin = geometry->GetOrigin(); + mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds(); + newOrigin[0] += bounds.GetElement(0); + newOrigin[1] += bounds.GetElement(2); + newOrigin[2] += bounds.GetElement(4); + + for (int i=0; i<3; i++) + for (int j=0; j<3; j++) + newDirection[j][i] = geometry->GetMatrixColumn(i)[j]; + upsampledRegion.SetSize(0, geometry->GetExtent(0)*m_UpsamplingFactor); + upsampledRegion.SetSize(1, geometry->GetExtent(1)*m_UpsamplingFactor); + upsampledRegion.SetSize(2, geometry->GetExtent(2)*m_UpsamplingFactor); + } + typename OutputImageType::RegionType::SizeType upsampledSize = upsampledRegion.GetSize(); + // apply new image parameters + outImage->SetSpacing( newSpacing ); + outImage->SetOrigin( newOrigin ); + outImage->SetDirection( newDirection ); + outImage->SetRegions( upsampledRegion ); outImage->Allocate(); int w = upsampledSize[0]; int h = upsampledSize[1]; int d = upsampledSize[2]; - - unsigned char* accuout; - accuout = reinterpret_cast(outImage->GetBufferPointer()); - for (int i=0; iGetTractContainer(); - - for (int i=0; iSize(); i++) + // set/initialize output + OutPixelType* outImageBufferPointer = (OutPixelType*)outImage->GetBufferPointer(); + for (int i=0; i fiberPolyData = m_FiberBundle->GetFiberPolyData(); + vtkSmartPointer vLines = fiberPolyData->GetLines(); + vLines->InitTraversal(); + + int numFibers = m_FiberBundle->GetNumFibers(); + for( int i=0; iGetElement(i); - int tractsize = tract->Size(); + vtkIdType numPoints(0); + vtkIdType* points(NULL); + vLines->GetNextCell ( numPoints, points ); + + // fill output image + if (numPoints>0) + { + itk::Point vertex = GetItkPoint(fiberPolyData->GetPoint(points[0])); + itk::Index<3> index; + outImage->TransformPhysicalPointToIndex(vertex, index); + outImage->SetPixel(index, 1); + } - if (tractsize>1) + if (numPoints>2) { - ContainerPointType start = tract->GetElement(0); - ContainerPointType end = tract->GetElement(tractsize-1); - - start[0] = (start[0]+0.5) * m_UpsamplingFactor; - start[1] = (start[1]+0.5) * m_UpsamplingFactor; - start[2] = (start[2]+0.5) * m_UpsamplingFactor; - - // int coordinates inside image? - int px = (int) (start[0]); - if (px < 0 || px >= w) - continue; - int py = (int) (start[1]); - if (py < 0 || py >= h) - continue; - int pz = (int) (start[2]); - if (pz < 0 || pz >= d) - continue; - - accuout[( px + w*(py + h*pz ))] += 1; - - - end[0] = (end[0]+0.5) * m_UpsamplingFactor; - end[1] = (end[1]+0.5) * m_UpsamplingFactor; - end[2] = (end[2]+0.5) * m_UpsamplingFactor; - - // int coordinates inside image? - px = (int) (end[0]); - if (px < 0 || px >= w) - continue; - py = (int) (end[1]); - if (py < 0 || py >= h) - continue; - pz = (int) (end[2]); - if (pz < 0 || pz >= d) - continue; - - accuout[( px + w*(py + h*pz ))] += 1; + itk::Point vertex = GetItkPoint(fiberPolyData->GetPoint(points[numPoints-1])); + itk::Index<3> index; + outImage->TransformPhysicalPointToIndex(vertex, index); + outImage->SetPixel(index, 1); } } - MITK_INFO << "2D fiber endings image generated"; + if (m_InvertImage) + for (int i=0; i +#include +#include +#include +#include namespace itk{ -template< class TInputImage, class TOutputPixelType > -class TractsToFiberEndingsImageFilter : - public ImageToImageFilter > -//huhu public ImageToImageFilter > +template< class OutputImageType > +class TractsToFiberEndingsImageFilter : public ImageSource< OutputImageType > { public: typedef TractsToFiberEndingsImageFilter Self; - typedef ImageToImageFilter > Superclass; -//huhu typedef ImageToImageFilter > Superclass; + typedef ProcessObject Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; - - itkNewMacro(Self); - itkTypeMacro( TractsToFiberEndingsImageFilter, - ImageToImageFilter ); - - /** Types for the Output Image**/ - typedef TInputImage InputImageType; - - /** Types for the Output Image**/ - typedef itk::Image OutputImageType; - /** Type for the directions **/ - typedef VectorContainer< unsigned int, vnl_vector_fixed< double, 3 > > - TractOrientationsType; + typedef typename OutputImageType::PixelType OutPixelType; - /** Type for the directions container **/ - typedef VectorContainer< unsigned int, TractOrientationsType > - TractOrientationsContainerType; + itkNewMacro(Self); + itkTypeMacro( TractsToFiberEndingsImageFilter, ImageSource ); /** Upsampling factor **/ itkSetMacro( UpsamplingFactor, unsigned int); itkGetMacro( UpsamplingFactor, unsigned int); - - itkSetMacro(FiberBundle, mitk::FiberBundle::Pointer); - itkGetMacro(FiberBundle, mitk::FiberBundle::Pointer); + + /** Invert Image **/ + itkSetMacro( InvertImage, bool); + itkGetMacro( InvertImage, bool); + + itkSetMacro( FiberBundle, mitk::FiberBundleX::Pointer); + itkSetMacro( InputImage, typename OutputImageType::Pointer); + + /** Use input image geometry to initialize output image **/ + itkSetMacro( UseImageGeometry, bool); + itkGetMacro( UseImageGeometry, bool); void GenerateData(); - + protected: + itk::Point GetItkPoint(double point[3]); + TractsToFiberEndingsImageFilter(); virtual ~TractsToFiberEndingsImageFilter(); + mitk::FiberBundleX::Pointer m_FiberBundle; unsigned int m_UpsamplingFactor; - mitk::FiberBundle::Pointer m_FiberBundle; - + bool m_InvertImage; + bool m_UseImageGeometry; + typename OutputImageType::Pointer m_InputImage; }; } #ifndef ITK_MANUAL_INSTANTIATION #include "itkTractsToFiberEndingsImageFilter.cpp" #endif #endif // __itkTractsToFiberEndingsImageFilter_h__ diff --git a/Modules/DiffusionImaging/Algorithms/itkTractsToProbabilityImageFilter.cpp b/Modules/DiffusionImaging/Algorithms/itkTractsToProbabilityImageFilter.cpp deleted file mode 100644 index 5c8b9ac092..0000000000 --- a/Modules/DiffusionImaging/Algorithms/itkTractsToProbabilityImageFilter.cpp +++ /dev/null @@ -1,359 +0,0 @@ -#include "itkTractsToProbabilityImageFilter.h" - -#include "itkBSplineUpsampleImageFilter.h" - -#define __CEIL_UCHAR__(val) (val) = \ -( (val) < 0 ) ? ( 0 ) : ( ( (val)>255 ) ? ( 255 ) : ( (val) ) ); - -namespace itk{ - - template< class TInputImage, class TOutputPixelType > - TractsToProbabilityImageFilter< TInputImage, TOutputPixelType > - ::TractsToProbabilityImageFilter(): - m_BinaryEnvelope(false) - { - this->SetNumberOfRequiredInputs(0); - } - - template< class TInputImage, class TOutputPixelType > - TractsToProbabilityImageFilter< TInputImage, TOutputPixelType > - ::~TractsToProbabilityImageFilter() - { - } - - template< class TInputImage, class TOutputPixelType > - void TractsToProbabilityImageFilter< TInputImage, TOutputPixelType > - ::GenerateData() - { - bool isRgba = false; - if(&typeid(TOutputPixelType) == &typeid(itk::RGBAPixel)) - { - isRgba = true; - } - else if(&typeid(TOutputPixelType) != &typeid(unsigned char)) - { - MITK_INFO << "Only 'unsigned char' and 'itk::RGBAPixel supported as OutputPixelType"; - return; - } - - mitk::Geometry3D::Pointer geometry = m_FiberBundle->GetGeometry(); - - typename OutputImageType::Pointer outImage = - static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0)); - - outImage->SetSpacing( geometry->GetSpacing()/m_UpsamplingFactor ); // Set the image spacing - - mitk::Point3D origin = geometry->GetOrigin(); - mitk::Point3D indexOrigin; - geometry->WorldToIndex(origin, indexOrigin); - indexOrigin[0] = indexOrigin[0] - .5 * (1.0-1.0/m_UpsamplingFactor); - indexOrigin[1] = indexOrigin[1] - .5 * (1.0-1.0/m_UpsamplingFactor); - indexOrigin[2] = indexOrigin[2] - .5 * (1.0-1.0/m_UpsamplingFactor); - mitk::Point3D newOrigin; - geometry->IndexToWorld(indexOrigin, newOrigin); - - outImage->SetOrigin( newOrigin ); // Set the image origin - itk::Matrix matrix; - for (int i=0; i<3; i++) - for (int j=0; j<3; j++) - matrix[j][i] = geometry->GetMatrixColumn(i)[j]/geometry->GetSpacing().GetElement(i); - outImage->SetDirection( matrix ); // Set the image direction - - float* bounds = m_FiberBundle->GetBounds(); - ImageRegion<3> upsampledRegion; - upsampledRegion.SetSize(0, bounds[0]); - upsampledRegion.SetSize(1, bounds[1]); - upsampledRegion.SetSize(2, bounds[2]); - - typename InputImageType::RegionType::SizeType upsampledSize = upsampledRegion.GetSize(); - for (unsigned int n = 0; n < 3; n++) - { - upsampledSize[n] = upsampledSize[n] * m_UpsamplingFactor; - } - upsampledRegion.SetSize( upsampledSize ); - outImage->SetRegions( upsampledRegion ); - - outImage->Allocate(); - // itk::RGBAPixel pix; - // pix.Set(0,0,0,0); - // outImage->FillBuffer(pix); - - int w = upsampledSize[0]; - int h = upsampledSize[1]; - int d = upsampledSize[2]; - - - unsigned char* accuout; - float* accu; - - accuout = reinterpret_cast(outImage->GetBufferPointer()); - - if(isRgba) - { -// accuout = static_cast( outImage->GetBufferPointer()[0].GetDataPointer()); - accu = new float[w*h*d*4]; - for (int i=0; iGetNumTracts(); - for( int i=0; i > vertices; - - // for each vertex - int numVertices = m_FiberBundle->GetNumPoints(i); - for( int j=0; j point = m_FiberBundle->GetPoint(i,j); - itk::Point nextPoint = m_FiberBundle->GetPoint(i,j+1); - point[0] += 0.5 - 0.5/m_UpsamplingFactor; - point[1] += 0.5 - 0.5/m_UpsamplingFactor; - point[2] += 0.5 - 0.5/m_UpsamplingFactor; - nextPoint[0] += 0.5 - 0.5/m_UpsamplingFactor; - nextPoint[1] += 0.5 - 0.5/m_UpsamplingFactor; - nextPoint[2] += 0.5 - 0.5/m_UpsamplingFactor; - - for(int k=1; k<=m_UpsamplingFactor; k++) - { - itk::Point newPoint; - newPoint[0] = point[0] + ((double)k/(double)m_UpsamplingFactor)*(nextPoint[0]-point[0]); - newPoint[1] = point[1] + ((double)k/(double)m_UpsamplingFactor)*(nextPoint[1]-point[1]); - newPoint[2] = point[2] + ((double)k/(double)m_UpsamplingFactor)*(nextPoint[2]-point[2]); - vertices.push_back(newPoint); - } - } - - //////////////////// - // calc directions (which are used as weights) - std::list< itk::Point > rgbweights; - std::list intensities; - - // for each vertex - numVertices = vertices.size(); - for( int j=0; j vertex = vertices.at(j); - itk::Point vertexPost = vertices.at(j+1); - - itk::Point dir; - dir[0] = fabs((vertexPost[0] - vertex[0]) * outImage->GetSpacing()[0]); - dir[1] = fabs((vertexPost[1] - vertex[1]) * outImage->GetSpacing()[1]); - dir[2] = fabs((vertexPost[2] - vertex[2]) * outImage->GetSpacing()[2]); - - if(isRgba) - { - rgbweights.push_back(dir); - } - - float intensity = sqrt(dir[0]*dir[0]+dir[1]*dir[1]+dir[2]*dir[2]); - intensities.push_back(intensity); - - // last point gets same as previous one - if(j==numVertices-2) - { - if(isRgba) - { - rgbweights.push_back(dir); - } - intensities.push_back(intensity); - } - } - - - //////////////////// - // fill output image - - // for each vertex - for( int j=0; j vertex = vertices.at(j); - itk::Point rgbweight; - if(isRgba) - { - rgbweight = rgbweights.front(); - rgbweights.pop_front(); - } - float intweight = intensities.front(); - intensities.pop_front(); - - // scaling coordinates (index coords scale with upsampling) - vertex[0] = vertex[0] * m_UpsamplingFactor; - vertex[1] = vertex[1] * m_UpsamplingFactor; - vertex[2] = vertex[2] * m_UpsamplingFactor; - - // int coordinates inside image? - int px = (int) (vertex[0]); - if (px < 0 || px >= w-1) - continue; - int py = (int) (vertex[1]); - if (py < 0 || py >= h-1) - continue; - int pz = (int) (vertex[2]); - if (pz < 0 || pz >= d-1) - continue; - - // float fraction of coordinates - float frac_x = vertex[0] - px; - float frac_y = vertex[1] - py; - float frac_z = vertex[2] - pz; - - float scale = 100 * pow((float)m_UpsamplingFactor,3); - - if(isRgba) - { - // add to r-channel in output image - accu[0+4*( px + w*(py + h*pz ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[0] * scale; - accu[0+4*( px + w*(py+1+ h*pz ))] += (1-frac_x)*( frac_y)*(1-frac_z) * rgbweight[0] * scale; - accu[0+4*( px + w*(py + h*pz+h))] += (1-frac_x)*(1-frac_y)*( frac_z) * rgbweight[0] * scale; - accu[0+4*( px + w*(py+1+ h*pz+h))] += (1-frac_x)*( frac_y)*( frac_z) * rgbweight[0] * scale; - accu[0+4*( px+1 + w*(py + h*pz ))] += ( frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[0] * scale; - accu[0+4*( px+1 + w*(py + h*pz+h))] += ( frac_x)*(1-frac_y)*( frac_z) * rgbweight[0] * scale; - accu[0+4*( px+1 + w*(py+1+ h*pz ))] += ( frac_x)*( frac_y)*(1-frac_z) * rgbweight[0] * scale; - accu[0+4*( px+1 + w*(py+1+ h*pz+h))] += ( frac_x)*( frac_y)*( frac_z) * rgbweight[0] * scale; - - // add to g-channel in output image - accu[1+4*( px + w*(py + h*pz ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[1] * scale; - accu[1+4*( px + w*(py+1+ h*pz ))] += (1-frac_x)*( frac_y)*(1-frac_z) * rgbweight[1] * scale; - accu[1+4*( px + w*(py + h*pz+h))] += (1-frac_x)*(1-frac_y)*( frac_z) * rgbweight[1] * scale; - accu[1+4*( px + w*(py+1+ h*pz+h))] += (1-frac_x)*( frac_y)*( frac_z) * rgbweight[1] * scale; - accu[1+4*( px+1 + w*(py + h*pz ))] += ( frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[1] * scale; - accu[1+4*( px+1 + w*(py + h*pz+h))] += ( frac_x)*(1-frac_y)*( frac_z) * rgbweight[1] * scale; - accu[1+4*( px+1 + w*(py+1+ h*pz ))] += ( frac_x)*( frac_y)*(1-frac_z) * rgbweight[1] * scale; - accu[1+4*( px+1 + w*(py+1+ h*pz+h))] += ( frac_x)*( frac_y)*( frac_z) * rgbweight[1] * scale; - - // add to b-channel in output image - accu[2+4*( px + w*(py + h*pz ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[2] * scale; - accu[2+4*( px + w*(py+1+ h*pz ))] += (1-frac_x)*( frac_y)*(1-frac_z) * rgbweight[2] * scale; - accu[2+4*( px + w*(py + h*pz+h))] += (1-frac_x)*(1-frac_y)*( frac_z) * rgbweight[2] * scale; - accu[2+4*( px + w*(py+1+ h*pz+h))] += (1-frac_x)*( frac_y)*( frac_z) * rgbweight[2] * scale; - accu[2+4*( px+1 + w*(py + h*pz ))] += ( frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[2] * scale; - accu[2+4*( px+1 + w*(py + h*pz+h))] += ( frac_x)*(1-frac_y)*( frac_z) * rgbweight[2] * scale; - accu[2+4*( px+1 + w*(py+1+ h*pz ))] += ( frac_x)*( frac_y)*(1-frac_z) * rgbweight[2] * scale; - accu[2+4*( px+1 + w*(py+1+ h*pz+h))] += ( frac_x)*( frac_y)*( frac_z) * rgbweight[2] * scale; - - // add to a-channel in output image - accu[3+4*( px + w*(py + h*pz ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * intweight * scale; - accu[3+4*( px + w*(py+1+ h*pz ))] += (1-frac_x)*( frac_y)*(1-frac_z) * intweight * scale; - accu[3+4*( px + w*(py + h*pz+h))] += (1-frac_x)*(1-frac_y)*( frac_z) * intweight * scale; - accu[3+4*( px + w*(py+1+ h*pz+h))] += (1-frac_x)*( frac_y)*( frac_z) * intweight * scale; - accu[3+4*( px+1 + w*(py + h*pz ))] += ( frac_x)*(1-frac_y)*(1-frac_z) * intweight * scale; - accu[3+4*( px+1 + w*(py + h*pz+h))] += ( frac_x)*(1-frac_y)*( frac_z) * intweight * scale; - accu[3+4*( px+1 + w*(py+1+ h*pz ))] += ( frac_x)*( frac_y)*(1-frac_z) * intweight * scale; - accu[3+4*( px+1 + w*(py+1+ h*pz+h))] += ( frac_x)*( frac_y)*( frac_z) * intweight * scale; - } - else if (m_BinaryEnvelope) - { - accu[( px + w*(py + h*pz ))] = 1; - accu[( px + w*(py+1+ h*pz ))] = 1; - accu[( px + w*(py + h*pz+h))] = 1; - accu[( px + w*(py+1+ h*pz+h))] = 1; - accu[( px+1 + w*(py + h*pz ))] = 1; - accu[( px+1 + w*(py + h*pz+h))] = 1; - accu[( px+1 + w*(py+1+ h*pz ))] = 1; - accu[( px+1 + w*(py+1+ h*pz+h))] = 1; - } - else - { - accu[( px + w*(py + h*pz ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * intweight * scale; - accu[( px + w*(py+1+ h*pz ))] += (1-frac_x)*( frac_y)*(1-frac_z) * intweight * scale; - accu[( px + w*(py + h*pz+h))] += (1-frac_x)*(1-frac_y)*( frac_z) * intweight * scale; - accu[( px + w*(py+1+ h*pz+h))] += (1-frac_x)*( frac_y)*( frac_z) * intweight * scale; - accu[( px+1 + w*(py + h*pz ))] += ( frac_x)*(1-frac_y)*(1-frac_z) * intweight * scale; - accu[( px+1 + w*(py + h*pz+h))] += ( frac_x)*(1-frac_y)*( frac_z) * intweight * scale; - accu[( px+1 + w*(py+1+ h*pz ))] += ( frac_x)*( frac_y)*(1-frac_z) * intweight * scale; - accu[( px+1 + w*(py+1+ h*pz+h))] += ( frac_x)*( frac_y)*( frac_z) * intweight * scale; - } - - } - } - - float maxRgb = 0.000000001; - float maxInt = 0.000000001; - int numPix; - - if(isRgba) - { - numPix = w*h*d*4; - - // calc maxima - for(int i=0; i maxRgb) - { - maxRgb = accu[i]; - } - } - else - { - if(accu[i] > maxInt) - { - maxInt = accu[i]; - } - } - } - - // write output, normalized uchar 0..255 - for(int i=0; i maxInt) - { - maxInt = accu[i]; - } - } - - // write output, normalized uchar 0..255 - for(int i=0; i -class TractsToProbabilityImageFilter : - public ImageToImageFilter > -//huhu public ImageToImageFilter > -{ - -public: - typedef TractsToProbabilityImageFilter Self; - typedef ImageToImageFilter > Superclass; -//huhu typedef ImageToImageFilter > Superclass; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer< const Self > ConstPointer; - - itkNewMacro(Self); - itkTypeMacro( TractsToProbabilityImageFilter, - ImageToImageFilter ); - - /** Types for the Output Image**/ - typedef TInputImage InputImageType; - - /** Types for the Output Image**/ - typedef itk::Image OutputImageType; - - /** Type for the directions **/ - typedef VectorContainer< unsigned int, vnl_vector_fixed< double, 3 > > - TractOrientationsType; - - /** Type for the directions container **/ - typedef VectorContainer< unsigned int, TractOrientationsType > - TractOrientationsContainerType; - - /** Upsampling factor **/ - itkSetMacro( UpsamplingFactor, unsigned int); - itkGetMacro( UpsamplingFactor, unsigned int); - - /** Upsampling factor **/ - itkSetMacro( InvertImage, bool); - itkGetMacro( InvertImage, bool); - - itkSetMacro(FiberBundle, mitk::FiberBundle::Pointer); - itkGetMacro(FiberBundle, mitk::FiberBundle::Pointer); - - itkSetMacro( BinaryEnvelope, bool); - itkGetMacro( BinaryEnvelope, bool); - - void GenerateData(); - -protected: - - TractsToProbabilityImageFilter(); - virtual ~TractsToProbabilityImageFilter(); - - unsigned int m_UpsamplingFactor; - mitk::FiberBundle::Pointer m_FiberBundle; - - bool m_InvertImage; - bool m_BinaryEnvelope; -}; - -} - -#ifndef ITK_MANUAL_INSTANTIATION -#include "itkTractsToProbabilityImageFilter.cpp" -#endif - -#endif // __itkTractsToProbabilityImageFilter_h__ diff --git a/Modules/DiffusionImaging/Algorithms/itkTractsToRgbaImageFilter.cpp b/Modules/DiffusionImaging/Algorithms/itkTractsToRgbaImageFilter.cpp new file mode 100644 index 0000000000..2cbb38202a --- /dev/null +++ b/Modules/DiffusionImaging/Algorithms/itkTractsToRgbaImageFilter.cpp @@ -0,0 +1,272 @@ +#include "itkTractsToRgbaImageFilter.h" + +// VTK +#include +#include +#include + +// misc +#include + +namespace itk{ + + template< class OutputImageType > + TractsToRgbaImageFilter< OutputImageType >::TractsToRgbaImageFilter() + : m_BinaryOutput(false) + , m_InvertImage(false) + , m_UpsamplingFactor(1) + , m_InputImage(NULL) + , m_UseImageGeometry(false) + { + + } + + template< class OutputImageType > + TractsToRgbaImageFilter< OutputImageType >::~TractsToRgbaImageFilter() + { + } + + template< class OutputImageType > + itk::Point TractsToRgbaImageFilter< OutputImageType >::GetItkPoint(double point[3]) + { + itk::Point itkPoint; + itkPoint[0] = point[0]; + itkPoint[1] = point[1]; + itkPoint[2] = point[2]; + return itkPoint; + } + + template< class OutputImageType > + void TractsToRgbaImageFilter< OutputImageType >::GenerateData() + { + if(&typeid(OutPixelType) != &typeid(itk::RGBAPixel)) + return; + + // generate upsampled image + mitk::Geometry3D::Pointer geometry = m_FiberBundle->GetGeometry(); + typename OutputImageType::Pointer outImage = this->GetOutput(); + + // calculate new image parameters + mitk::Vector3D newSpacing; + mitk::Point3D newOrigin; + itk::Matrix newDirection; + ImageRegion<3> upsampledRegion; + if (m_UseImageGeometry && !m_InputImage.IsNull()) + { + newSpacing = m_InputImage->GetSpacing()/m_UpsamplingFactor; + upsampledRegion = m_InputImage->GetLargestPossibleRegion(); + newOrigin = m_InputImage->GetOrigin(); + typename OutputImageType::RegionType::SizeType size = upsampledRegion.GetSize(); + size[0] *= m_UpsamplingFactor; + size[1] *= m_UpsamplingFactor; + size[2] *= m_UpsamplingFactor; + upsampledRegion.SetSize(size); + newDirection = m_InputImage->GetDirection(); + } + else + { + newSpacing = geometry->GetSpacing()/m_UpsamplingFactor; + newOrigin = geometry->GetOrigin(); + mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds(); + newOrigin[0] += bounds.GetElement(0); + newOrigin[1] += bounds.GetElement(2); + newOrigin[2] += bounds.GetElement(4); + + for (int i=0; i<3; i++) + for (int j=0; j<3; j++) + newDirection[j][i] = geometry->GetMatrixColumn(i)[j]; + upsampledRegion.SetSize(0, geometry->GetExtent(0)*m_UpsamplingFactor); + upsampledRegion.SetSize(1, geometry->GetExtent(1)*m_UpsamplingFactor); + upsampledRegion.SetSize(2, geometry->GetExtent(2)*m_UpsamplingFactor); + } + typename OutputImageType::RegionType::SizeType upsampledSize = upsampledRegion.GetSize(); + + // apply new image parameters + outImage->SetSpacing( newSpacing ); + outImage->SetOrigin( newOrigin ); + outImage->SetDirection( newDirection ); + outImage->SetRegions( upsampledRegion ); + outImage->Allocate(); + + int w = upsampledSize[0]; + int h = upsampledSize[1]; + int d = upsampledSize[2]; + + // set/initialize output + unsigned char* outImageBufferPointer = (unsigned char*)outImage->GetBufferPointer(); + float* buffer = new float[w*h*d*4]; + for (int i=0; iGetDeepCopy(); + m_FiberBundle->ResampleFibers(minSpacing/10); + + vtkSmartPointer fiberPolyData = m_FiberBundle->GetFiberPolyData(); + vtkSmartPointer vLines = fiberPolyData->GetLines(); + vLines->InitTraversal(); + + int numFibers = m_FiberBundle->GetNumFibers(); + for( int i=0; iGetNextCell ( numPoints, points ); + + // calc directions (which are used as weights) + std::list< itk::Point > rgbweights; + std::list intensities; + + for( int j=0; j vertex = GetItkPoint(fiberPolyData->GetPoint(points[j])); + itk::Point vertexPost = GetItkPoint(fiberPolyData->GetPoint(points[j+1])); + + itk::Point dir; + dir[0] = fabs((vertexPost[0] - vertex[0]) * outImage->GetSpacing()[0]); + dir[1] = fabs((vertexPost[1] - vertex[1]) * outImage->GetSpacing()[1]); + dir[2] = fabs((vertexPost[2] - vertex[2]) * outImage->GetSpacing()[2]); + + rgbweights.push_back(dir); + + float intensity = sqrt(dir[0]*dir[0]+dir[1]*dir[1]+dir[2]*dir[2]); + intensities.push_back(intensity); + + // last point gets same as previous one + if(j==numPoints-2) + { + rgbweights.push_back(dir); + intensities.push_back(intensity); + } + } + + // fill output image + for( int j=0; j vertex = GetItkPoint(fiberPolyData->GetPoint(points[j])); + itk::Index<3> index; + itk::ContinuousIndex contIndex; + outImage->TransformPhysicalPointToIndex(vertex, index); + outImage->TransformPhysicalPointToContinuousIndex(vertex, contIndex); + + int ix = Math::Round(contIndex[0]); + int iy = Math::Round(contIndex[1]); + int iz = Math::Round(contIndex[2]); + + float frac_x = contIndex[0] - ix; + float frac_y = contIndex[1] - iy; + float frac_z = contIndex[2] - iz; + + int px = (int)contIndex[0]; + if (frac_x<0) + { + px -= 1; + frac_x *= -1; + } + int py = (int)contIndex[1]; + if (frac_y<0) + { + py -= 1; + frac_y *= -1; + } + int pz = (int)contIndex[2]; + if (frac_z<0) + { + pz -= 1; + frac_z *= -1; + } + + // int coordinates inside image? + if (px < 0 || px >= w-1) + continue; + if (py < 0 || py >= h-1) + continue; + if (pz < 0 || pz >= d-1) + continue; + + float scale = 100 * pow((float)m_UpsamplingFactor,3); + itk::Point rgbweight = rgbweights.front(); + rgbweights.pop_front(); + float intweight = intensities.front(); + intensities.pop_front(); + + // add to r-channel in output image + buffer[0+4*( px + w*(py + h*pz ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[0] * scale; + buffer[0+4*( px + w*(py+1+ h*pz ))] += (1-frac_x)*( frac_y)*(1-frac_z) * rgbweight[0] * scale; + buffer[0+4*( px + w*(py + h*pz+h))] += (1-frac_x)*(1-frac_y)*( frac_z) * rgbweight[0] * scale; + buffer[0+4*( px + w*(py+1+ h*pz+h))] += (1-frac_x)*( frac_y)*( frac_z) * rgbweight[0] * scale; + buffer[0+4*( px+1 + w*(py + h*pz ))] += ( frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[0] * scale; + buffer[0+4*( px+1 + w*(py + h*pz+h))] += ( frac_x)*(1-frac_y)*( frac_z) * rgbweight[0] * scale; + buffer[0+4*( px+1 + w*(py+1+ h*pz ))] += ( frac_x)*( frac_y)*(1-frac_z) * rgbweight[0] * scale; + buffer[0+4*( px+1 + w*(py+1+ h*pz+h))] += ( frac_x)*( frac_y)*( frac_z) * rgbweight[0] * scale; + + // add to g-channel in output image + buffer[1+4*( px + w*(py + h*pz ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[1] * scale; + buffer[1+4*( px + w*(py+1+ h*pz ))] += (1-frac_x)*( frac_y)*(1-frac_z) * rgbweight[1] * scale; + buffer[1+4*( px + w*(py + h*pz+h))] += (1-frac_x)*(1-frac_y)*( frac_z) * rgbweight[1] * scale; + buffer[1+4*( px + w*(py+1+ h*pz+h))] += (1-frac_x)*( frac_y)*( frac_z) * rgbweight[1] * scale; + buffer[1+4*( px+1 + w*(py + h*pz ))] += ( frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[1] * scale; + buffer[1+4*( px+1 + w*(py + h*pz+h))] += ( frac_x)*(1-frac_y)*( frac_z) * rgbweight[1] * scale; + buffer[1+4*( px+1 + w*(py+1+ h*pz ))] += ( frac_x)*( frac_y)*(1-frac_z) * rgbweight[1] * scale; + buffer[1+4*( px+1 + w*(py+1+ h*pz+h))] += ( frac_x)*( frac_y)*( frac_z) * rgbweight[1] * scale; + + // add to b-channel in output image + buffer[2+4*( px + w*(py + h*pz ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[2] * scale; + buffer[2+4*( px + w*(py+1+ h*pz ))] += (1-frac_x)*( frac_y)*(1-frac_z) * rgbweight[2] * scale; + buffer[2+4*( px + w*(py + h*pz+h))] += (1-frac_x)*(1-frac_y)*( frac_z) * rgbweight[2] * scale; + buffer[2+4*( px + w*(py+1+ h*pz+h))] += (1-frac_x)*( frac_y)*( frac_z) * rgbweight[2] * scale; + buffer[2+4*( px+1 + w*(py + h*pz ))] += ( frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[2] * scale; + buffer[2+4*( px+1 + w*(py + h*pz+h))] += ( frac_x)*(1-frac_y)*( frac_z) * rgbweight[2] * scale; + buffer[2+4*( px+1 + w*(py+1+ h*pz ))] += ( frac_x)*( frac_y)*(1-frac_z) * rgbweight[2] * scale; + buffer[2+4*( px+1 + w*(py+1+ h*pz+h))] += ( frac_x)*( frac_y)*( frac_z) * rgbweight[2] * scale; + + // add to a-channel in output image + buffer[3+4*( px + w*(py + h*pz ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * intweight * scale; + buffer[3+4*( px + w*(py+1+ h*pz ))] += (1-frac_x)*( frac_y)*(1-frac_z) * intweight * scale; + buffer[3+4*( px + w*(py + h*pz+h))] += (1-frac_x)*(1-frac_y)*( frac_z) * intweight * scale; + buffer[3+4*( px + w*(py+1+ h*pz+h))] += (1-frac_x)*( frac_y)*( frac_z) * intweight * scale; + buffer[3+4*( px+1 + w*(py + h*pz ))] += ( frac_x)*(1-frac_y)*(1-frac_z) * intweight * scale; + buffer[3+4*( px+1 + w*(py + h*pz+h))] += ( frac_x)*(1-frac_y)*( frac_z) * intweight * scale; + buffer[3+4*( px+1 + w*(py+1+ h*pz ))] += ( frac_x)*( frac_y)*(1-frac_z) * intweight * scale; + buffer[3+4*( px+1 + w*(py+1+ h*pz+h))] += ( frac_x)*( frac_y)*( frac_z) * intweight * scale; + } + } + float maxRgb = 0.000000001; + float maxInt = 0.000000001; + int numPix; + + numPix = w*h*d*4; + // calc maxima + for(int i=0; i maxRgb) + maxRgb = buffer[i]; + } + else + { + if(buffer[i] > maxInt) + maxInt = buffer[i]; + } + } + + // write output, normalized uchar 0..255 + for(int i=0; i +#include +#include +#include +#include + +namespace itk{ + +template< class OutputImageType > +class TractsToRgbaImageFilter : public ImageSource< OutputImageType > +{ + +public: + typedef TractsToRgbaImageFilter Self; + typedef ProcessObject Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + typedef typename OutputImageType::PixelType OutPixelType; + typedef itk::Image InputImageType; + + itkNewMacro(Self); + itkTypeMacro( TractsToRgbaImageFilter, ImageSource ); + + /** Upsampling factor **/ + itkSetMacro( UpsamplingFactor, unsigned int); + itkGetMacro( UpsamplingFactor, unsigned int); + + /** Invert Image **/ + itkSetMacro( InvertImage, bool); + itkGetMacro( InvertImage, bool); + + /** Binary Output **/ + itkSetMacro( BinaryOutput, bool); + itkGetMacro( BinaryOutput, bool); + + itkSetMacro( FiberBundle, mitk::FiberBundleX::Pointer); + itkSetMacro( InputImage, typename InputImageType::Pointer); + + /** Use input image geometry to initialize output image **/ + itkSetMacro( UseImageGeometry, bool); + itkGetMacro( UseImageGeometry, bool); + + + void GenerateData(); + +protected: + + itk::Point GetItkPoint(double point[3]); + + TractsToRgbaImageFilter(); + virtual ~TractsToRgbaImageFilter(); + + mitk::FiberBundleX::Pointer m_FiberBundle; + unsigned int m_UpsamplingFactor; + bool m_InvertImage; + bool m_BinaryOutput; + bool m_UseImageGeometry; + typename InputImageType::Pointer m_InputImage; +}; + +} + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkTractsToRgbaImageFilter.cpp" +#endif + +#endif // __itkTractsToRgbaImageFilter_h__ diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/itkSlowPolyLineParametricPath.h b/Modules/DiffusionImaging/IODataStructures/FiberBundle/itkSlowPolyLineParametricPath.h deleted file mode 100644 index e4b0f53d37..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/itkSlowPolyLineParametricPath.h +++ /dev/null @@ -1,112 +0,0 @@ -#ifndef _itkSlowPolyLineParametricPathPath_h -#define _itkSlowPolyLineParametricPathPath_h - -#include "itkPolyLineParametricPath.h" -#include "itkVectorContainer.h" -#include "itkContinuousIndex.h" -#include "itkIndex.h" -#include "itkOffset.h" -#include "itkVector.h" - -namespace itk -{ - - -/** \class SlowPolyLineParametricPath - * \brief Represent a path of line segments through ND Space - * - * This class is intended to represent parametric paths through an image, where - * the paths are composed of line segments. Each line segment traverses one - * unit of input. A classic application of this class is the representation of - * contours in 2D images, especially when the contours only need to be - * approximately correct. Another use of a path is to guide the movement of an - * iterator through an image. - * - * \sa EllipseParametricPath - * \sa FourierSeriesPath - * \sa OrthogonallyCorrectedParametricPath - * \sa ParametricPath - * \sa ChainCodePath - * \sa Path - * \sa ContinuousIndex - * \sa Index - * \sa Offset - * \sa Vector - * - * \ingroup PathObjects - */ -template -class ITK_EXPORT SlowPolyLineParametricPath : public -PolyLineParametricPath< VDimension > -{ -public: - /** Standard class typedefs. */ - typedef SlowPolyLineParametricPath Self; - typedef PolyLineParametricPath Superclass; - typedef SmartPointer Pointer; - typedef SmartPointer ConstPointer; - - /** Run-time type information (and related methods). */ - itkTypeMacro(SlowPolyLineParametricPath, PolyLineParametricPath); - - /** Input type */ - typedef typename Superclass::InputType InputType; - - /** Output type */ - typedef typename Superclass::OutputType OutputType; - - - /** Basic data-structure types used */ - typedef typename Superclass::ContinuousIndexType ContinuousIndexType; - typedef typename Superclass::IndexType IndexType; - typedef typename Superclass::OffsetType OffsetType; - typedef typename Superclass::PointType PointType; - typedef typename Superclass::VectorType VectorType; - typedef typename Superclass::VertexType VertexType; - typedef typename Superclass::VertexListType VertexListType; - typedef typename Superclass::VertexListPointer VertexListPointer; - - /** Increment the input variable passed by reference such that the ND index of - * the path moves to its next vertex-connected (8-connected in 2D) neighbor. - * Return the Index-space offset of the path from its prior input to its new - * input. If the path is unable to increment, input is not changed and an - * offset of Zero is returned. Children are not required to implement bounds - * checking. - * - * This is a fairly slow, iterative algorithm that numerically converges to - * the next index along the path, in a vertex-connected (8-connected in 2D) - * fashion. When possible, children of this class should overload this - * function with something more efficient. - * - * WARNING: This default implementation REQUIRES that the ND endpoint of - * the path be either unique or coincident only with the startpoint, since it - * uses the endpoint as a stopping condition. */ - virtual OffsetType IncrementInput(InputType & input) const; - - - ///** Evaluate the first derivative of the ND output with respect to the 1D - // * input. This is an exact, algebraic function. */ - //virtual VectorType EvaluateDerivative(const InputType & input) const; - - - /** New() method for dynamic construction */ - itkNewMacro( Self ); - - -protected: - SlowPolyLineParametricPath(); - ~SlowPolyLineParametricPath(){} - void PrintSelf(std::ostream& os, Indent indent) const; - -private: - SlowPolyLineParametricPath(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented -}; - -} // namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -#include "itkSlowPolyLineParametricPath.txx" -#endif - -#endif diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/itkSlowPolyLineParametricPath.txx b/Modules/DiffusionImaging/IODataStructures/FiberBundle/itkSlowPolyLineParametricPath.txx deleted file mode 100644 index e0852d1614..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/itkSlowPolyLineParametricPath.txx +++ /dev/null @@ -1,115 +0,0 @@ -#ifndef _itkSlowPolyLineParametricPath_txx -#define _itkSlowPolyLineParametricPath_txx - -#include "itkSlowPolyLineParametricPath.h" -#include - - - -namespace itk -{ - -//template -//typename SlowPolyLineParametricPath::VectorType -//SlowPolyLineParametricPath -//::EvaluateDerivative(const InputType & input) const -//{ -//} - - - -/** - * Constructor - */ -template -SlowPolyLineParametricPath -::SlowPolyLineParametricPath() -{ - this->SetDefaultInputStepSize( 0.3 ); -} - - -template -typename SlowPolyLineParametricPath::OffsetType -SlowPolyLineParametricPath -::IncrementInput(InputType & input) const -{ - int iterationCount; - bool tooSmall; - bool tooBig; - InputType inputStepSize; - InputType finalInputValue; - OffsetType offset; - IndexType currentImageIndex; - IndexType nextImageIndex; - IndexType finalImageIndex; - - iterationCount = 0; - inputStepSize = this->GetDefaultInputStepSize(); - - // Are we already at (or past) the end of the input? - finalInputValue = this->EndOfInput(); - currentImageIndex = this->EvaluateToIndex( input ); - finalImageIndex = this->EvaluateToIndex( finalInputValue ); - offset = finalImageIndex - currentImageIndex; - if( ( offset == this->GetZeroOffset() && input != this->StartOfInput() ) || - ( input >=finalInputValue ) ) - { - return this->GetZeroOffset(); - } - - do - { - if( iterationCount++ > 10000 ) {itkExceptionMacro(<<"Too many iterations");} - - nextImageIndex = this->EvaluateToIndex( input + inputStepSize ); - offset = nextImageIndex - currentImageIndex; - - tooBig = false; - tooSmall = ( offset == this->GetZeroOffset() ); - if( tooSmall ) - { - // increase the input step size, but don't go past the end of the input - inputStepSize *= 2; - if( (input + inputStepSize) >= finalInputValue ){ - //inputStepSize = finalInputValue - input; - inputStepSize += this->GetDefaultInputStepSize(); - } - } - else - { - // Search for an offset dimension that is too big - for( unsigned int i=0; i= 2 || offset[i] <= -2 ); - } - - if( tooBig ){ - //inputStepSize /= 1.5; - inputStepSize -= (this->GetDefaultInputStepSize()/0.5); - } - } - } - while( tooSmall || tooBig ); - - input += inputStepSize; - return offset; -} - - -/** - * Standard "PrintSelf" method - */ -template -void -SlowPolyLineParametricPath -::PrintSelf( std::ostream& os, Indent indent) const -{ - Superclass::PrintSelf( os, indent ); -} - - - -} // end namespaceitk - -#endif diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundle.cpp b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundle.cpp deleted file mode 100644 index 875015a42f..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundle.cpp +++ /dev/null @@ -1,1821 +0,0 @@ -/*========================================================================= - - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ - Version: $Revision: 21975 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ - - -#include "mitkFiberBundle.h" -#include -#include -#include -#include - - -#include -#include -#include -#include - -#include -//#include - - -/* statics values to define the position of a fiberTractPoint - * related to the plane of a ROI - */ -const int mitk::FiberBundle::TRACTPOINT_BACKFACE = 0; -const int mitk::FiberBundle::TRACTPOINT_ON_PLANE = 1; -const int mitk::FiberBundle::TRACTPOINT_FRNTFACE = 2; - -// implementation of all essential methods from superclass - -mitk::FiberBundle::FiberBundle() -{ - m_GroupFiberBundle = FiberGroupType::New(); - - m_TractContainer = ContainerType::New(); - - //by default set a standard geometry, usually geometry is set by the user on initializing - //a mitkFiberBundle Object - mitk::Geometry3D::Pointer fbgeometry = mitk::Geometry3D::New(); - fbgeometry->SetIdentity(); - this->SetGeometry(fbgeometry); - - /* for debugging only */ - m_debugITKContainer = itkStochTractContainerType::New(); - - -} - -mitk::FiberBundle::~FiberBundle() -{ - -} - -void mitk::FiberBundle::SetBounds(float* b) -{ - m_boundsFB[0] = b[0]; - m_boundsFB[1] = b[1]; - m_boundsFB[2] = b[2]; -} - -void mitk::FiberBundle::SetBounds(double* b) -{ - m_boundsFB[0] = b[0]; - m_boundsFB[1] = b[1]; - m_boundsFB[2] = b[2]; -} - -float* mitk::FiberBundle::GetBounds() -{ - return m_boundsFB; -} - -void mitk::FiberBundle::PushPoint(int fiberIndex, ContainerPointType point) -{ - if( (unsigned)fiberIndex >= m_TractContainer->Size() ) - { - fiberIndex = m_TractContainer->Size(); - ContainerTractType::Pointer tract = ContainerTractType::New(); - tract->InsertElement(tract->Size(),point); - m_TractContainer->InsertElement(fiberIndex, tract); - } - else if(fiberIndex>=0) - { - m_TractContainer->ElementAt(fiberIndex)->InsertElement(m_TractContainer->ElementAt(fiberIndex)->Size(), point); - } -} - -void mitk::FiberBundle::PushTract(ContainerTractType::Pointer tract) -{ - m_TractContainer->InsertElement(m_TractContainer->Size(), tract); -} - -mitk::FiberBundle::Pointer mitk::FiberBundle::JoinBundle(mitk::FiberBundle::Pointer bundle) -{ - mitk::FiberBundle::Pointer retval = mitk::FiberBundle::New(); - retval->SetGeometry(this->GetGeometry()); - retval->SetBounds(this->m_boundsFB); - - retval->InsertBundle(this); - retval->InsertBundle(bundle); - return retval; -} - -void mitk::FiberBundle::InsertBundle(mitk::FiberBundle::Pointer bundle) -{ - - // INCOMPLETE, SHOULD CHECK FOR DIFFERENT GEOMETRIES IN THIS+BUNDLE - // DO INDEX1 -> WORLD -> INDEX2 TRANSFORMATION, IF THEY ARE DIFFERENT. - - int num = this->GetNumTracts(); - - FiberGroupType::Pointer groupFiberBundle = bundle->GetGroupFiberBundle(); - ChildrenListType *fiberList = groupFiberBundle->GetChildren(); - for(ChildrenListType::iterator itLst = fiberList->begin(); - itLst != fiberList->end(); - ++itLst) - { - - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - mitk::FiberBundle::DTITubeType::Pointer dtiTract = dynamic_cast< mitk::FiberBundle::DTITubeType * > (tmp_fbr.GetPointer()); - - if (dtiTract.IsNull()) - { - MITK_INFO << "DTI Tract is NULL!!!!! omg"; - continue; - } - - dtiTract->SetId(num++); - this->addSingleDTITract(dtiTract); - } - - ContainerType::Pointer container = bundle->GetTractContainer(); - for(int i=0; iSize();i++) - { - this->PushTract(container->ElementAt(i)); - } - -} - -int mitk::FiberBundle::FindTractByEndpoints(mitk::FiberBundle::DTITubeType::Pointer searchTract) -{ - int searchNrPnts = searchTract->GetNumberOfPoints(); - mitk::FiberBundle::DTITubeType::PointListType searchPntList = searchTract->GetPoints(); - - typedef mitk::FiberBundle::DTITubeType::PointType PointType; - - DTITubePointType searchPointFirst = searchPntList.at(0); - PointType searchPos1 = searchPointFirst.GetPosition(); - DTITubePointType searchPointLast = searchPntList.at(searchNrPnts-1); - PointType searchPos2 = searchPointLast.GetPosition(); - - FiberGroupType::Pointer groupFiberBundle = this->GetGroupFiberBundle(); - ChildrenListType *fiberList = groupFiberBundle->GetChildren(); - for(ChildrenListType::iterator itLst = fiberList->begin(); - itLst != fiberList->end(); - ++itLst) - { - - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - mitk::FiberBundle::DTITubeType::Pointer dtiTract = dynamic_cast< mitk::FiberBundle::DTITubeType * > (tmp_fbr.GetPointer()); - - if (dtiTract.IsNull()) - { - MITK_INFO << "DTI Tract is NULL!!!!! omg"; - continue; - } - - mitk::FiberBundle::DTITubeType::PointListType dtiPntList = dtiTract->GetPoints(); - int fibrNrPnts = dtiTract->GetNumberOfPoints(); - - DTITubePointType point_first = dtiPntList.at(0); - PointType pos1 = point_first.GetPosition(); - DTITubePointType point_last = dtiPntList.at(fibrNrPnts-1); - PointType pos2 = point_last.GetPosition(); - - if( (pos1 == searchPos1 && pos2 == searchPos2) || - (pos2 == searchPos1 && pos1 == searchPos2) ) - { - return dtiTract->GetId(); - } - } - - return -1; -} - -mitk::FiberBundle::Pointer mitk::FiberBundle::SubstractBundle(mitk::FiberBundle::Pointer bundle) -{ - - mitk::FiberBundle::Pointer retval = mitk::FiberBundle::New(); - retval->SetGeometry(this->GetGeometry()); - - mitk::FiberBundle::Pointer largeBundle = bundle; - mitk::FiberBundle::Pointer smallBundle = this; - - MITK_INFO << "large children " << largeBundle->GetGroupFiberBundle()->GetNumberOfChildren() << "!="<GetNumTracts(); - MITK_INFO << "small children " << smallBundle->GetGroupFiberBundle()->GetNumberOfChildren() << "!="<GetNumTracts(); - - if(this->GetGroupFiberBundle()->GetNumberOfChildren() > bundle->GetGroupFiberBundle()->GetNumberOfChildren()) - { - MITK_INFO << "this is large (" << this->GetNumTracts() << ">" << bundle->GetNumTracts() << ")"; - largeBundle = this; - smallBundle = bundle; - } - - - ContainerType::Pointer container = largeBundle->GetTractContainer(); - int counter = 0; - - FiberGroupType::Pointer groupFiberBundle = largeBundle->GetGroupFiberBundle(); - ChildrenListType *fiberList = groupFiberBundle->GetChildren(); - MITK_INFO << "large number children " << groupFiberBundle->GetNumberOfChildren(); - for(ChildrenListType::iterator itLst = fiberList->begin(); - itLst != fiberList->end(); - ++itLst) - { - - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - mitk::FiberBundle::DTITubeType::Pointer dtiTract = dynamic_cast< mitk::FiberBundle::DTITubeType * > (tmp_fbr.GetPointer()); - - if (dtiTract.IsNull()) - { - MITK_INFO << "DTI Tract is NULL!!!!! omg"; - continue; - } - - int delId = smallBundle->FindTractByEndpoints(dtiTract); - if( delId == -1 ) - { - retval->addSingleDTITract(dtiTract); - retval->PushTract(container->ElementAt(counter)); - } - - MITK_INFO << "Counter " << counter++; - } - - return retval; -} - -mitk::FiberBundle::ContainerPointType mitk::FiberBundle::GetPoint(int tractIndex, int pointIndex) -{ - if (tractIndex>=0 && tractIndex=0 && pointIndexGetElement(tractIndex)->GetElement(pointIndex); - } - return NULL; -} - -int mitk::FiberBundle::GetNumTracts() -{ - return m_TractContainer->Size(); -} - -int mitk::FiberBundle::GetNumPoints(int tractIndex) -{ - if ((unsigned)tractIndex>=0 && (unsigned)tractIndexSize()) - { - return m_TractContainer->GetElement(tractIndex)->Size(); - - } else { - //added by igi - return NULL; - } - -} - -mitk::FiberBundle::ContainerTractType::Pointer mitk::FiberBundle::GetTract(int tractIndex) -{ - ContainerTractType::Pointer out; - if ((unsigned)tractIndex>0 && (unsigned)tractIndexSize()) - return m_TractContainer->GetElement(tractIndex); - return out; -} - -void mitk::FiberBundle::additkStochTractContainer(itkStochTractContainerType::Pointer itkStochCont) -{ - //for debugging only - m_debugITKContainer = itkStochCont; - //******************** - - - /* transform itkStochContainer to standardized TractContainer */ - - for (itkStochTractContainerType::ConstIterator itCont = itkStochCont->Begin(); - itCont != itkStochCont->End(); - ++itCont) - { - - // get fiber of itkContainer - itkStochTractType::Pointer tract = itCont->Value(); - itkStochTractType::VertexListType::ConstPointer vertexlist = tract->GetVertexList(); - - //init a desired containerFiber - ContainerTractType::Pointer contTract = ContainerTractType::New(); - - //get points of fiber - for( int j=0; j<(int)vertexlist->Size(); ++j) - { - - // put the point of vertex pointList in itkContainer - itkStochTractType::VertexType vertex = vertexlist->GetElement(j); - - //prepare for dtiPoint - ContainerPointType contPnt; - contPnt[0] = (float) vertex[0]; - contPnt[1] = (float) vertex[1]; - contPnt[2] = (float) vertex[2]; - - contTract->InsertElement(contTract->Size(), contPnt); - - /* coordinate testing*/ - /*if ((float)vertex[0] == contPnt[0]) { - MITK_INFO << " [OK] ... X "; - }else { - MITK_INFO << "[FAIL] ... itkX: " << vertex[0] << " " << contPnt[0] << "\n" ; - } - - if ((float)vertex[1] == contPnt[1]) { - MITK_INFO << " [OK] ... Y "; - }else { - MITK_INFO << "[FAIL] ... itkY: " << vertex[1] << " " << contPnt[1] << "\n" ; - } - if ((float)vertex[2] == contPnt[2]) { - MITK_INFO << " [OK] ... Z " << "\n" ; - MITK_INFO << " Values X Y Z: " << contPnt[0] << " " << contPnt[1] << " " << contPnt[2] << "\n"; - }else { - MITK_INFO << "[FAIL] ... itkZ: " << vertex[2] << " " << contPnt[2] << "\n" ; - } - */ - - - - } - - // add filled fiber to container - m_TractContainer->InsertElement(m_TractContainer->Size(), contTract); - - } - - -} - -void mitk::FiberBundle::addTractContainer( ContainerType::Pointer tractContainer ) -{ - m_TractContainer = tractContainer; -} - - -void mitk::FiberBundle::initFiberGroup() -{ - /* iterate through the tractContainer and store fibers in DTISpatialObjects */ - for (ContainerType::ConstIterator itCont = m_TractContainer->Begin(); - itCont != m_TractContainer->End(); - ++itCont) - { - // init new dtiTube and - DTITubeType::Pointer dtiTube = DTITubeType::New(); - DTITubeType::PointListType list; - - // get current tract of container - ContainerTractType::Pointer contTract = itCont->Value(); - - // iterate through the number of points ... use iterator, no index-output is needed anyway - for(ContainerTractType::Iterator itContTrct = contTract->Begin(); - itContTrct != contTract->End(); - ++itContTrct) - { - // init DTITube point - DTITubePointType p; - ContainerPointType cntp = itContTrct->Value(); - p.SetPosition(cntp[0], cntp[1], cntp[2]); - p.SetRadius(1); - - mitk::FiberBundle::fiberPostprocessing_setTensorMatrix( &p ); - - - mitk::FiberBundle::fiberPostprocessing_FA( &p ); - //mitk::FiberBundle::fiberPostprocessing_setTensorMatrix( &p ); - - p.AddField(DTITubePointType::GA, 3); - - p.SetColor(1,0,0,1); - list.push_back(p); - } - // dtiTubes - dtiTube->GetProperty()->SetName("dtiTube"); - dtiTube->SetId(itCont->Index()); - dtiTube->SetPoints(list); - m_GroupFiberBundle->AddSpatialObject(dtiTube); - } -} - -void mitk::FiberBundle::fiberPostprocessing_setTensorMatrix(DTITubePointType *dtiP) -{ - float tMatrix[6]; - tMatrix[0]=0.0f; - tMatrix[1]=1.0f; - tMatrix[2]=2.0f; - tMatrix[3]=3.0f; - tMatrix[4]=4.0f; - tMatrix[5]=5.0f; - - dtiP->SetTensorMatrix(tMatrix); - - -} - -/* this method is a HowTo method, used for debugging only */ -void mitk::FiberBundle::fiberPostprocessing_setPoint(DTITubePointType *dtiP, ContainerPointType vrtx) -{ - /* get values of variable referenced by a ponter - double vtxIdx1, vtxIdx2, vtxIdx3; - vtxIdx1 = * (double*) &vrtx[0]; - vtxIdx2 = * (double*) &vrtx[1]; - vtxIdx3 = * (double*) &vrtx[2]; - - dtiP->SetPosition(vtxIdx1, vtxIdx2, vtxIdx3); - */ - - dtiP->SetPosition(vrtx[0], vrtx[1], vrtx[2]); -} - -void mitk::FiberBundle::fiberPostprocessing_FA(DTITubePointType *dtiP) -{ - debug_PrototypeCounter ++; - float valFA; - - if (debug_PrototypeCounter % 10 < 5) { - valFA = 1.0; - } else if (debug_PrototypeCounter % 10 == 7) { - valFA = 0.3; - } else if (debug_PrototypeCounter % 10 == 8) { - valFA = 0; - } else { - valFA = 0.5; - } - - dtiP->AddField(DTITubePointType::FA, valFA); - -} - - -/* methods for high speed perfoermance dispay or live-monitoring of fiber results */ -void mitk::FiberBundle::addContainer4speedDisplay(ContainerType::Pointer speedTractContainer) -{ - -} - - - - -void mitk::FiberBundle::addSingleDTITract(mitk::FiberBundle::DTITubeType::Pointer dtiFbrTrct) -{ - - //MITK_INFO << " start addSingleDTITract(): " << m_GroupFiberBundle->GetNumberOfChildren(); - m_GroupFiberBundle->AddSpatialObject(dtiFbrTrct); - //MITK_INFO << "end addSingleDTITract(): " << m_GroupFiberBundle->GetNumberOfChildren(); - - -} - -mitk::FiberBundle::FiberGroupType::Pointer mitk::FiberBundle::getGroupFiberBundle() -{ - return m_GroupFiberBundle; -} - -std::vector mitk::FiberBundle::getAllIDsInFiberBundle() -{ - std::vector allFBIds; - - FiberGroupType::Pointer fiberGroup = this->getGroupFiberBundle(); - ChildrenListType *FiberList; - FiberList = fiberGroup->GetChildren(); - - for(ChildrenListType::iterator itLst = FiberList->begin(); - itLst != FiberList->end(); - ++itLst) - { - - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - mitk::FiberBundle::DTITubeType::Pointer dtiTract = dynamic_cast< mitk::FiberBundle::DTITubeType * > (tmp_fbr.GetPointer()); - if (dtiTract.IsNull()) { - MITK_INFO << "DTI Tract is NULL!!!!! omg"; - continue; } - - allFBIds.push_back(dtiTract->GetId()); - - } - - return allFBIds; - - -} - - -mitk::FiberBundle::Pointer mitk::FiberBundle::extractFibersById(std::vector idSet) -{ - - - mitk::FiberBundle::Pointer resultingFibers = mitk::FiberBundle::New(); - resultingFibers->SetGeometry(this->GetGeometry()); - resultingFibers->SetBounds(this->GetBounds()); - - //get Fiber by ID - //get childrenList - //compare if current FiberID is in idSet - - FiberGroupType::Pointer fiberGroup = this->getGroupFiberBundle(); - ChildrenListType *FiberList; - FiberList = fiberGroup->GetChildren(); - MITK_INFO << "writing fibers into datastructure:...."; - - for (int cg=0; cgPushTract( m_TractContainer->GetElement(trctId) ); - - } - MITK_INFO << "init new fiberBundle..."; - resultingFibers->initFiberGroup(); - MITK_INFO << "init new fiberBundle [DONE]"; - - /* - for(ChildrenListType::iterator itLst = FiberList->begin(); - itLst != FiberList->end(); - ++itLst) - { - - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - mitk::FiberBundle::DTITubeType::Pointer dtiTract = dynamic_cast< mitk::FiberBundle::DTITubeType * > (tmp_fbr.GetPointer()); - if (dtiTract.IsNull()) { - MITK_INFO << "DTI Tract is NULL!!!!! omg"; - continue; } - - // MITK_INFO << "current DTI tract id: " << dtiTract->GetId(); - - std::vector::iterator retFibers = find(idSet.begin(), idSet.end(), dtiTract->GetId()); - - - if (retFibers != idSet.end()) { - //MITK_INFO << "Fiber and ID equal: "; - - - DTITubeType::Pointer copyDTITract = this->copySingleDTITract(dtiTract); - - MITK_INFO << "fibercontainer before adding new tract" << resultingFibers->GetNumTracts(); - resultingFibers->addSingleDTITract(copyDTITract); - MITK_INFO << "fibercontainer after adding new tract" << resultingFibers->GetNumTracts(); - - - } - //else { - // MITK_INFO << "Fiber and ID not ident!"; - //} - - //std::set::iterator retFibers - //retFibers = idSet.find(dtiTract->GetId()); - - } */ - - return resultingFibers; - -} - - -/* extract fibers using planar Figures */ -//mitk::FiberBundle::Pointer mitk::FiberBundle::extractFibersPF(mitk::PlanarFigure::Pointer pf) -std::vector mitk::FiberBundle::extractFibersByPF(mitk::PlanarFigure::Pointer pf, std::vector* smaller_set) -{ - // if incoming pf is a pfc - mitk::PlanarFigureComposite::Pointer pfcomp= dynamic_cast(pf.GetPointer()); - if (!pfcomp.IsNull()) { - //PFC - switch (pfcomp->getOperationType()) { - case 0: - { - //AND - std::vector childResults = this->extractFibersByPF(pfcomp->getChildAt(0), smaller_set); - std::vector tmpChild = childResults; - for (int i=1; igetNumberOfChildren(); ++i) - { - tmpChild = extractFibersByPF(pfcomp->getChildAt(i),&tmpChild); - } - std::vector AND_Assamblage(tmpChild.begin(), tmpChild.end()); - return AND_Assamblage; - } - case 1: - { - //OR - std::vector childResults = this->extractFibersByPF(pfcomp->getChildAt(0), smaller_set); - std::sort(childResults.begin(), childResults.end()); - std::vector tmp_container(m_TractContainer->Size()); - std::vector::iterator end; - for (int i=1; igetNumberOfChildren(); ++i) - { - std::vector tmpChild = extractFibersByPF(pfcomp->getChildAt(i), smaller_set); - sort(tmpChild.begin(), tmpChild.end()); - - end = std::set_union(childResults.begin(), childResults.end(), - tmpChild.begin(), tmpChild.end(), - tmp_container.begin() ); - - childResults.assign(tmp_container.begin(), end); - - } - - std::vector OR_Assamblage(childResults.begin(), childResults.end()); - return OR_Assamblage; - } - case 2: - { - //NOT - - // FIRST AN AND OPERATION - std::vector childResults = this->extractFibersByPF(pfcomp->getChildAt(0), smaller_set); - std::sort(childResults.begin(), childResults.end()); - std::vector tmpChild = childResults; - for (int i=1; igetNumberOfChildren(); ++i) - { - tmpChild = extractFibersByPF(pfcomp->getChildAt(i),&tmpChild); - } - std::vector AND_Assamblage(tmpChild.begin(), tmpChild.end()); - - // get IDs of interesting fibers - std::vector interesting_fibers; - if(!smaller_set) - interesting_fibers = this->getAllIDsInFiberBundle(); - else - interesting_fibers.assign(smaller_set->begin(), smaller_set->end()); - std::sort(interesting_fibers.begin(), interesting_fibers.end()); - - // all interesting fibers that are not in the AND assemblage - std::vector tmp_not(interesting_fibers.size()); - std::vector::iterator end; - end = std::set_difference(interesting_fibers.begin(), interesting_fibers.end(), - AND_Assamblage.begin(), AND_Assamblage.end(), - tmp_not.begin() ); - std::vector NOT_Assamblage(tmp_not.begin(),end); - return NOT_Assamblage; - - } - default: - MITK_INFO << "we have an UNDEFINED composition... ERROR" ; - break; - } - } else { - - mitk::PlanarCircle::Pointer circleName = mitk::PlanarCircle::New(); - mitk::PlanarRectangle::Pointer rectName = mitk::PlanarRectangle::New(); - mitk::PlanarPolygon::Pointer polyName = mitk::PlanarPolygon::New(); - - if (pf->GetNameOfClass() == circleName->GetNameOfClass() ) - { - //MITK_INFO << "We have a circle :-) " ; - - - int cntGaps = 0; - //init output FiberBundle - mitk::FiberBundle::Pointer FB_Clipped = mitk::FiberBundle::New(); - FB_Clipped->SetGeometry(this->GetGeometry()); - - //get geometry containing the plane which we need to calculate the xrossingPoints - mitk::Geometry2D::ConstPointer pfgeometry = pf->GetGeometry2D(); - const mitk::PlaneGeometry* planeGeometry = dynamic_cast (pfgeometry.GetPointer()); - std::vector XingPoints; - std::vector fiberIDs; - - - //################################################################# - //############### Find Gap, FrontFace BackFace #################### - //################################################################# - - //get fibercontainer and iterate through the fibers - FiberGroupType::Pointer fiberGroup = this->getGroupFiberBundle(); - - //extract single fibers - ChildrenListType *FiberList; - FiberList = fiberGroup->GetChildren(); - - - - // iterate through each single tract - //int cntFibId = -1; - for(ChildrenListType::iterator itLst = FiberList->begin(); - itLst != FiberList->end(); - ++itLst) - { - - //MITK_INFO << "***************** NEW FIBER *********************"; - //cntFibId++; - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - mitk::FiberBundle::DTITubeType::Pointer dtiTract = dynamic_cast< mitk::FiberBundle::DTITubeType * > (tmp_fbr.GetPointer()); - if (dtiTract.IsNull()) { - MITK_INFO << " could not cast groupFiberBundle child into dtiTract!... LEVEL 4 ERROR"; - continue; } - - if (smaller_set && std::find(smaller_set->begin(), smaller_set->end(), dtiTract->GetId())==smaller_set->end()) - continue; - - //get list of points - int fibrNrPnts = dtiTract->GetNumberOfPoints(); - mitk::FiberBundle::DTITubeType::PointListType dtiPntList = dtiTract->GetPoints(); - - // if one fiber is represented by just one point.... - // check if this point is on the plane - if (fibrNrPnts <= 0) - { - MITK_INFO << "HyperERROR in mitkFiberBundle.cpp, No point in fiber....check ur algorithm:"; - continue; - } - - - /* for finding a gap we need to have knowledge of the previous normal - * be aware that there can be more than 1 gaps! - */ - - int prevPntFacing = -999999; - int currPntFacing = -999999; - //double prevFacing = -99999999099; - mitk::Point3D prevFiberPntmm; - - for(int i=0; iGetGeometry()->IndexToWorld(tmpFiberVec, currentFiberPntmm); - double faceing = pfgeometry->SignedDistance(currentFiberPntmm); - - //MITK_INFO << "FacingOutput: " << faceing; - - /////////////////////////////////////// - - if (faceing < 0) { - //backface - currPntFacing = TRACTPOINT_BACKFACE; - //MITK_INFO << "is BACKFACE" << currentFiberPntmm ; - - } else if (faceing > 0) { - //frontface - currPntFacing = TRACTPOINT_FRNTFACE; - // MITK_INFO << "is FRONTFACE" << currentFiberPntmm ; - - } else if (faceing == 0) { - //onplane - currPntFacing = TRACTPOINT_ON_PLANE; - //MITK_INFO << "is on PLANE" << currentFiberPntmm ; - } - - - //////////////////////////////////////// - - - if (currPntFacing == TRACTPOINT_ON_PLANE) - { //strike, - //calculate distance - //TODO SOURCE THIS CONTROLSTRUCTURE OUT - if(isPointInSelection(tmpFiberVec,pf)) - { - DTITubeType::Pointer copyDTITract = copySingleDTITract(dtiTract); - //MITK_INFO << "GroupFB extract after copy of Children: " << fiberGroup->GetNumberOfChildren(); - - FB_Clipped->addSingleDTITract(copyDTITract); - } - - - } else { - // Point is BACKFACE or FRONTFACE - if (i > 0) - { - //check if there is a gap between previous and current - bool isGap = checkForGap(currPntFacing, prevPntFacing); - - if (isGap == true) { - ++cntGaps; - - // - mitk::Vector3D LineDirection; - LineDirection[0] = currentFiberPntmm[0] - prevFiberPntmm[0]; - LineDirection[1] = currentFiberPntmm[1] - prevFiberPntmm[1]; - LineDirection[2] = currentFiberPntmm[2] - prevFiberPntmm[2]; - - - mitk::Line3D Xingline( prevFiberPntmm, LineDirection ); - - mitk::Point3D intersectionPoint; - - Vector3D planeNormal = planeGeometry->GetNormal(); - planeNormal.Normalize(); - - Vector3D lineDirection = Xingline.GetDirection(); - lineDirection.Normalize(); - - double t = planeNormal * lineDirection; - if ( fabs( t ) < eps ) - { - - } - - Vector3D diff; - diff = planeGeometry->GetOrigin() - Xingline.GetPoint(); - t = ( planeNormal * diff ) / t; - - intersectionPoint = Xingline.GetPoint() + lineDirection * t; - // bool successXing = planeGeometry->IntersectionPoint( Xingline, intersectionPoint ); - //mitk::Point3D intersectionPointmm; - //planeGeometry->IndexToWorld(intersectionPoint,intersectionPointmm ); - - // MITK_INFO << "PlaneIntersectionPoint: " << intersectionPoint; - - if (false) { - MITK_INFO << " ERROR CALCULATING INTERSECTION POINT.....should not happen!! "; - } - //TODO more nice if this if is outside... - bool pntInROI = isPointInSelection(intersectionPoint,pf); - if(pntInROI) - { - // MITK_INFO << "POINT ALSO in ROI"; - - // MITK_INFO << "GroupFB extract before copy new object. of Children: " << fiberGroup->GetNumberOfChildren(); - /* dtiTubeSpatial::Pointer can not occur in 2 GroupSpatialObjects, therefore we have to copy the whole dtiTract of current List and add the copy to the desired FiberBundle */ - - // DTITubeType::Pointer copyDTITract = copySingleDTITract(dtiTract); - // MITK_INFO << "GroupFB extract after copy of Children: " << fiberGroup->GetNumberOfChildren(); - - //FB_Clipped->addSingleDTITract(copyDTITract); - - //MITK_INFO << "GroupFB extract after adding dtiTract to now FB NR. of Children: " << fiberGroup->GetNumberOfChildren(); - //MITK_INFO << "DTI Tract ID: " << dtiTract->GetId(); - // MITK_INFO << "size of Vector before pushing: " << fiberIDs.size(); - fiberIDs.push_back(dtiTract->GetId()); - // MITK_INFO << "size of Vector after pushing: " << fiberIDs.size(); - //MITK_INFO << "GroupFB extract after adding dtiTract to now FB NR. of Children: " << fiberGroup->GetNumberOfChildren(); - break; - - - } - - } - - // MITK_INFO << "---no gap---"; - - } //endif i>0 - - - } //endif Facing - // MITK_INFO << "GroupFB extract end Facing, NR. of Children: " << fiberGroup->GetNumberOfChildren(); - - - //update point flag - prevPntFacing = currPntFacing; - prevFiberPntmm = currentFiberPntmm; - } //end for fiberPoints - //MITK_INFO ;<< "GroupFB extract end of single tract, NR. of Children: " << fiberGroup->GetNumberOfChildren(); - - } //end for fiberTracts - // MITK_INFO << "GroupFB extract end of iterating through fiberBundle, NR. of Children: " << fiberGroup->GetNumberOfChildren(); - - // MITK_INFO << "selected " << fiberIDs.size() << " fibers " << " | counted gaps: " << cntGaps; - return fiberIDs; - - - - - - - } else if (pf->GetNameOfClass() == rectName->GetNameOfClass() ){ - - MITK_INFO << "We have a rectangle :-) " ; - - } else if (pf->GetNameOfClass() == polyName->GetNameOfClass() ) { - - //MITK_INFO << "We have a polygon :-) " ; - int cntGaps = 0; - //init output FiberBundle - mitk::FiberBundle::Pointer FB_Clipped = mitk::FiberBundle::New(); - FB_Clipped->SetGeometry(this->GetGeometry()); - - //get geometry containing the plane which we need to calculate the xrossingPoints - mitk::Geometry2D::ConstPointer pfgeometry = pf->GetGeometry2D(); - const mitk::PlaneGeometry* planeGeometry = dynamic_cast (pfgeometry.GetPointer()); - std::vector XingPoints; - std::vector fiberIDs; - - - //################################################################# - //############### Find Gap, FrontFace BackFace #################### - //################################################################# - - //get fibercontainer and iterate through the fibers - FiberGroupType::Pointer fiberGroup = this->getGroupFiberBundle(); - - //extract single fibers - ChildrenListType *FiberList; - FiberList = fiberGroup->GetChildren(); - int nrFibrs = fiberGroup->GetNumberOfChildren(); - - - - // iterate through each single tract - int cntFib = 1; - for(ChildrenListType::iterator itLst = FiberList->begin(); - itLst != FiberList->end(); - ++itLst) - { - if (cntFib % 500 == 0) { - MITK_INFO << "================\n prosessed fibers: " << cntFib << " of " << nrFibrs;; - } - ++cntFib; - - - - //MITK_INFO << "***************** NEW FIBER *********************"; - //cntFibId++; - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - mitk::FiberBundle::DTITubeType::Pointer dtiTract = dynamic_cast< mitk::FiberBundle::DTITubeType * > (tmp_fbr.GetPointer()); - if (dtiTract.IsNull()) { - MITK_INFO << " could not cast groupFiberBundle child into dtiTract!... LEVEL 4 ERROR"; - continue; } - - if (smaller_set && std::find(smaller_set->begin(), smaller_set->end(), dtiTract->GetId())==smaller_set->end()) - continue; - - - - //get list of points - int fibrNrPnts = dtiTract->GetNumberOfPoints(); - mitk::FiberBundle::DTITubeType::PointListType dtiPntList = dtiTract->GetPoints(); - - // if one fiber is represented by just one point.... - // check if this point is on the plane - if (fibrNrPnts <= 0) - { - MITK_INFO << "HyperERROR in mitkFiberBundle.cpp, No point in fiber....check ur algorithm:"; - continue; - } - - - /* for finding a gap we need to have knowledge of the previous normal - * be aware that there can be more than 1 gaps! - */ - - int prevPntFacing = -999999; - int currPntFacing = -999999; - //double prevFacing = -99999999099; - mitk::Point3D prevFiberPntmm; - - - - for(int i=0; iGetGeometry()->IndexToWorld(tmpFiberVec, currentFiberPntmm); - double faceing = pfgeometry->SignedDistance(currentFiberPntmm); - - //MITK_INFO << "FacingOutput: " << faceing; - - /////////////////////////////////////// - - if (faceing < 0) { - //backface - currPntFacing = TRACTPOINT_BACKFACE; - //MITK_INFO << "is BACKFACE" << currentFiberPntmm ; - - } else if (faceing > 0) { - //frontface - currPntFacing = TRACTPOINT_FRNTFACE; - // MITK_INFO << "is FRONTFACE" << currentFiberPntmm ; - - } else if (faceing == 0) { - //onplane - currPntFacing = TRACTPOINT_ON_PLANE; - //MITK_INFO << "is on PLANE" << currentFiberPntmm ; - } - - - //////////////////////////////////////// - - - if (currPntFacing == TRACTPOINT_ON_PLANE) - { //strike, - //calculate distance - //TODO SOURCE THIS CONTROLSTRUCTURE OUT - if(isPointInSelection(tmpFiberVec,pf)) - { - DTITubeType::Pointer copyDTITract = copySingleDTITract(dtiTract); - //MITK_INFO << "GroupFB extract after copy of Children: " << fiberGroup->GetNumberOfChildren(); - - FB_Clipped->addSingleDTITract(copyDTITract); - } - - - } else { - // Point is BACKFACE or FRONTFACE - if (i > 0) - { - //check if there is a gap between previous and current - bool isGap = checkForGap(currPntFacing, prevPntFacing); - - if (isGap == true) { - ++cntGaps; - - // - mitk::Vector3D LineDirection; - LineDirection[0] = currentFiberPntmm[0] - prevFiberPntmm[0]; - LineDirection[1] = currentFiberPntmm[1] - prevFiberPntmm[1]; - LineDirection[2] = currentFiberPntmm[2] - prevFiberPntmm[2]; - - - mitk::Line3D Xingline( prevFiberPntmm, LineDirection ); - - mitk::Point3D intersectionPoint; - - Vector3D planeNormal = planeGeometry->GetNormal(); - planeNormal.Normalize(); - - Vector3D lineDirection = Xingline.GetDirection(); - lineDirection.Normalize(); - - double t = planeNormal * lineDirection; - if ( fabs( t ) < eps ) - { - - } - - Vector3D diff; - diff = planeGeometry->GetOrigin() - Xingline.GetPoint(); - t = ( planeNormal * diff ) / t; - - intersectionPoint = Xingline.GetPoint() + lineDirection * t; - // bool successXing = planeGeometry->IntersectionPoint( Xingline, intersectionPoint ); - //mitk::Point3D intersectionPointmm; - //planeGeometry->IndexToWorld(intersectionPoint,intersectionPointmm ); - - // MITK_INFO << "PlaneIntersectionPoint: " << intersectionPoint; - - if (false) { - MITK_INFO << " ERROR CALCULATING INTERSECTION POINT.....should not happen!! "; - } - //TODO more nice if this if is outside... - bool pntInROI = isPointInSelection(intersectionPoint,pf); - if(pntInROI) - { - // MITK_INFO << "POINT ALSO in ROI"; - - // MITK_INFO << "GroupFB extract before copy new object. of Children: " << fiberGroup->GetNumberOfChildren(); - /* dtiTubeSpatial::Pointer can not occur in 2 GroupSpatialObjects, therefore we have to copy the whole dtiTract of current List and add the copy to the desired FiberBundle */ - - // DTITubeType::Pointer copyDTITract = copySingleDTITract(dtiTract); - // MITK_INFO << "GroupFB extract after copy of Children: " << fiberGroup->GetNumberOfChildren(); - - //FB_Clipped->addSingleDTITract(copyDTITract); - - //MITK_INFO << "GroupFB extract after adding dtiTract to now FB NR. of Children: " << fiberGroup->GetNumberOfChildren(); - //MITK_INFO << "DTI Tract ID: " << dtiTract->GetId(); - // MITK_INFO << "size of Vector before pushing: " << fiberIDs.size(); - fiberIDs.push_back(dtiTract->GetId()); - // MITK_INFO << "size of Vector after pushing: " << fiberIDs.size(); - //MITK_INFO << "GroupFB extract after adding dtiTract to now FB NR. of Children: " << fiberGroup->GetNumberOfChildren(); - break; - - - } - - } - - // MITK_INFO << "---no gap---"; - - } //endif i>0 - - - } //endif Facing - // MITK_INFO << "GroupFB extract end Facing, NR. of Children: " << fiberGroup->GetNumberOfChildren(); - - - //update point flag - prevPntFacing = currPntFacing; - prevFiberPntmm = currentFiberPntmm; - } //end for fiberPoints - //MITK_INFO ;<< "GroupFB extract end of single tract, NR. of Children: " << fiberGroup->GetNumberOfChildren(); - - } //end for fiberTracts - // MITK_INFO << "GroupFB extract end of iterating through fiberBundle, NR. of Children: " << fiberGroup->GetNumberOfChildren(); - - // MITK_INFO << "selected " << fiberIDs.size() << " fibers " << " | counted gaps: " << cntGaps; - return fiberIDs; - - - } else { - MITK_INFO << "[ERROR] unhandled PlanarFigureType found!"; - } - } - - return std::vector(); -} - - -mitk::FiberBundle::DTITubeType::Pointer mitk::FiberBundle::copySingleDTITract(mitk::FiberBundle::DTITubeType::Pointer currentDtiFiber) -{ - - DTITubeType::Pointer newCopyDtiFiber = DTITubeType::New(); - //*** get ID - newCopyDtiFiber->SetId( currentDtiFiber->GetId() ); - - //*** get points - DTITubeType::PointListType list; - - - //get list of dtiPoints - int fibrNrPnts = currentDtiFiber->GetNumberOfPoints(); - mitk::FiberBundle::DTITubeType::PointListType dtiPntList = currentDtiFiber->GetPoints(); - - for(int i=0; iSetPoints(list); - std::string dtiname = currentDtiFiber->GetProperty()->GetName(); - newCopyDtiFiber->GetProperty()->SetName(dtiname.c_str()); - - - - return newCopyDtiFiber; - - -} - - - - -/* This Method checks - * To recognize a gap between the 2 points, the previous must differ from the current - * but if the previous is on the plane and the current one not, then mark this situation as no gap - * if both, previous and current are on plane, you'll never jump into this Method - */ -bool mitk::FiberBundle::checkForGap(int crntPntFacing, int prevPntFacing) -{ - - bool isGap = false; - if (prevPntFacing != TRACTPOINT_ON_PLANE && crntPntFacing != prevPntFacing) - { - isGap = true; - - } else if (prevPntFacing == TRACTPOINT_ON_PLANE && crntPntFacing == TRACTPOINT_ON_PLANE) { - MITK_INFO << "###########################################"; - MITK_INFO << "$$$ HYPER ERROR, LOGIC MALFUNCTION!! previous point and current point in a fiber are recognized as a potential GAP! THIS IS NOT ALLOWED $$$"; - MITK_INFO << "###########################################"; - } - - return isGap; - -} - -mitk::Point3D mitk::FiberBundle::calculateCrossingPoint(mitk::Point3D pntFrnt, mitk::Point3D pntbck, mitk::PlanarFigure::Pointer pf) -{ - - mitk::Point3D pntXing; - - //################################################################# - //######### Calculate intersection of plane and fiber ############# - //################################################################# - - // transform in space :-) - - // y = k*x +d - // k = (y1 - y0)/(x1 - x0) - // d = ok - - // z adoption, take xy ratio to plane intersection and adopt it to z coordinate - // z_intersx = (x1 - intersX)/(x1 - x0) * (z1 - z0) + z1 - - double k; //slope - - double x0 = pntFrnt[0]; - double y0 = pntFrnt[1]; - double z0 = pntFrnt[2]; - double x1 = pntbck[0]; - double y1 = pntbck[1]; - double z1 = pntbck[2]; - - k = (y1 - y0) / (x1 - x0); - - // if slope == 0 then leave y as it is, change x - - // if slope == 1 then leave x as it is, change y - - // if z of p0 and p1 is the same, just take z - - - /* - - mitk::PlanarCircle::Pointer circleName = mitk::PlanarCircle::New(); - mitk::PlanarRectangle::Pointer rectName = mitk::PlanarRectangle::New(); - mitk::PlanarPolygon::Pointer polyName = mitk::PlanarPolygon::New(); - - if (pf->GetNameOfClass() == circleName->GetNameOfClass() ) - { - MITK_INFO << "We have a circle :-) " ; - //controlpoint 1 is middlepoint - //controlpoint 2 is radiuspoint - mitk::Vector3D V1w = pf->GetWorldControlPoint(0); //centerPoint - mitk::Vector3D V2w = pf->GetWorldControlPoint(1); //radiusPoint - mitk::Vector3D V1; - mitk::Vector3D V2; - this->GetGeometry()->WorldToIndex(V1w, V1); - this->GetGeometry()->WorldToIndex(V2w, V2); - - //calculate distance between those 2 and - mitk::Point3D distV; - distV = V2 - V1; - distV[0] = sqrt( pow(distV[0], 2.0) ); - distV[1] = sqrt( pow(distV[1], 2.0) ); - distV[2] = sqrt( pow(distV[2], 2.0) ); - - mitk::Point3D distPnt; - distPnt = pnt3D - V1; - distPnt[0] = sqrt( pow(distPnt[0], 2.0) ); - distPnt[1] = sqrt( pow(distPnt[1], 2.0) ); - distPnt[2] = sqrt( pow(distPnt[2], 2.0) ); - - if ( (distPnt <= distV) ) { - pntIsInside = true; - - - } - - return pntIsInside; - - //compare the result to the distance of all points an a fiber - - - - - - } else if (pf->GetNameOfClass() == rectName->GetNameOfClass() ){ - - MITK_INFO << "We have a rectangle :-) " ; - - } else if (pf->GetNameOfClass() == polyName->GetNameOfClass() ) { - - MITK_INFO << "We have a polygon :-) " ; - } - - */ - - return pntXing; - - -} - - -bool mitk::FiberBundle::isPointInSelection(mitk::Point3D pnt3D, mitk::PlanarFigure::Pointer pf) -{ - /* TODO needs to be redesigned.... each time because in planarPolygonsection VTK object will be initialized for each point!...PERFORMANCE LACK!!!!!!! */ - - //calculate distances - mitk::PlanarCircle::Pointer circleName = mitk::PlanarCircle::New(); - mitk::PlanarRectangle::Pointer rectName = mitk::PlanarRectangle::New(); - mitk::PlanarPolygon::Pointer polyName = mitk::PlanarPolygon::New(); - - if (pf->GetNameOfClass() == circleName->GetNameOfClass() ) - { - //MITK_INFO << "We have a circle :-) " ; - //controlpoint 1 is middlepoint - //controlpoint 2 is radiuspoint - mitk::Point3D V1w = pf->GetWorldControlPoint(0); //centerPoint - mitk::Point3D V2w = pf->GetWorldControlPoint(1); //radiusPoint - mitk::Vector3D V1; - mitk::Vector3D V2; - // this->GetGeometry()->WorldToIndex(V1w, V1); - // this->GetGeometry()->WorldToIndex(V2w, V2); - - //calculate distance between those 2 and - double distPF; - distPF = sqrt((double) (V2w[0] - V1w[0]) * (V2w[0] - V1w[0]) + - (V2w[1] - V1w[1]) * (V2w[1] - V1w[1]) + - (V2w[2] - V1w[2]) * (V2w[2] - V1w[2])); - - double XdistPnt = sqrt((double) (pnt3D[0] - V1w[0]) * (pnt3D[0] - V1w[0]) + - (pnt3D[1] - V1w[1]) * (pnt3D[1] - V1w[1]) + - (pnt3D[2] - V1w[2]) * (pnt3D[2] - V1w[2])) ; - - if ( (distPF > XdistPnt) ) { - return true; - } - - return false; - //compare the result to the distance of all points an a fiber - } - else if (pf->GetNameOfClass() == rectName->GetNameOfClass() ){ - - MITK_INFO << "We have a rectangle :-) " ; - - } else if (pf->GetNameOfClass() == polyName->GetNameOfClass() ) { - - //create vtkPolygon using controlpoints from planarFigure polygon - vtkSmartPointer polygonVtk = vtkPolygon::New(); - - //get the control points from pf and insert them to vtkPolygon - unsigned int nrCtrlPnts = pf->GetNumberOfControlPoints(); - // MITK_INFO << "We have a polygon with " << nrCtrlPnts << " controlpoints: " ; - - for (int i=0; iGetPoints()->InsertNextPoint((double)pf->GetWorldControlPoint(i)[0], (double)pf->GetWorldControlPoint(i)[1], (double)pf->GetWorldControlPoint(i)[2] ); - } - - //prepare everything for using pointInPolygon function - double n[3]; - polygonVtk->ComputeNormal(polygonVtk->GetPoints()->GetNumberOfPoints(), - static_cast(polygonVtk->GetPoints()->GetData()->GetVoidPointer(0)), n); - - double bounds[6]; - polygonVtk->GetPoints()->GetBounds(bounds); - - double checkIn[3] = {pnt3D[0], pnt3D[1], pnt3D[2]}; - - int isInPolygon = polygonVtk->PointInPolygon(checkIn, polygonVtk->GetPoints()->GetNumberOfPoints() - , static_cast(polygonVtk->GetPoints()->GetData()->GetVoidPointer(0)), bounds, n); - - // MITK_INFO << "======IsPointOnPolygon:========\n" << isInPolygon << "\n ======================== "; - - polygonVtk->Delete(); - - if (isInPolygon == 1) - { - // MITK_INFO << "return true"; - return true; - } else if (isInPolygon == 0) - { - // MITK_INFO << "return false"; - return false; - } else { - MITK_INFO << "&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*& \n YOUR DRAWN POLYGON DOES IS DEGENERATED AND NOT ACCEPTED \n DRAW A NEW ONE!! HAI CAPITO \n &*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&*&"; - } - } - - return false; -} - - -void mitk::FiberBundle::debug_members() -{ - /* Debug Workflow description - * Test1: check if both, groupSpatialObject and Tract container have the same amount of fiberTracts - * Test2: check if points in tracts contain the same coordinates - * next... to be continued - */ - - - /* ######### TEST 1 START ######### */ - //************************************* - MITK_INFO << " ############### \n *** TEST Equal Amount of Fibers *** \n "; - - unsigned int groupEls = m_GroupFiberBundle->GetNumberOfChildren(); - unsigned int contEls = m_TractContainer->Size(); - unsigned int itkcontEls = m_debugITKContainer->Size(); - - if (groupEls == contEls && contEls == itkcontEls) - { - MITK_INFO << "[OK] .... Test1 passed. # of Fibers: " << groupEls << " \n ******************** "; - } else { - - MITK_INFO << "[FAIL]: Container and FiberGroup do not contain same amount of fibers! \n "; - // MITK_INFO << " Container # of Fibers: " << contEls << " | FiberBundle # of Fibers: " << groupEls << "\n"; - MITK_INFO << " # of Fibers m_Cont: " << contEls << " | GroupFibers: " << groupEls << " | ITKCont: " << itkcontEls << "\n"; - } - /* ######### TEST 1 END ######### */ - //*********************************** - - - - /* ######### TEST 2 START ######### */ - //************************************* - - /* iterate through itkcontainer*/ - itkStochTractContainerType::ConstIterator itITKCnt; - itITKCnt = m_debugITKContainer->Begin(); - - /* extract DTIFiberTracts of the GroupFiberBundle Object */ - // all smartPointers to fibers stored in in a ChildrenList - ChildrenListType * FiberList; - FiberList = m_GroupFiberBundle->GetChildren(); - /* iterate through container, itkcontainer groupFiberBundle in one iteration step */ - ChildrenListType::iterator itLst; //STL "list" itself provides no index output of current iteration step. - itLst = FiberList->begin(); - - - ContainerType::ConstIterator vecIter; - for ( vecIter = m_TractContainer->Begin(); - vecIter != m_TractContainer->End(); - vecIter++ ) - { - - unsigned int itIdx = vecIter->Index(); - MITK_INFO << "FiberIteration: " << itIdx << "\n" ; - - //get single tract of container - ContainerTractType::Pointer contTract = vecIter->Value(); - int contNrPnts = contTract->Size(); - - //get singel tract of itkContainer - itkStochTractType::Pointer itkcontTract = itITKCnt->Value(); - itkStochTractType::VertexListType::ConstPointer itkcontVrtx = itkcontTract->GetVertexList(); - int itkcontNrPnts = itkcontVrtx->Size(); - - /* lists output is SpatialObject, we know we have DTITubeSpacialObjects - dynamic cast only likes pointers, no smartpointers, so each dsmartpointer has membermethod .GetPointer() */ - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - DTITubeType::Pointer dtiTract = dynamic_cast (tmp_fbr.GetPointer()); - if (dtiTract.IsNull()) { - MITK_INFO << " ############### *** ERRROR *** ############### \n ############### *** ERRROR *** ############### \n ############### *** ERRROR *** ############### \n "; - return; } - - //get points of tract - int fibrNrPnts = dtiTract->GetNumberOfPoints(); - DTITubeType::PointListType dtiPntList = dtiTract->GetPoints(); - - MITK_INFO << " ############### \n *** TEST Equal Amount of Points in Tract *** \n "; - - if (contNrPnts == itkcontNrPnts && itkcontNrPnts == fibrNrPnts) { - MITK_INFO << "[OK] .... Test2 passed. # of Points in fiber: " << fibrNrPnts << " \n ******************** "; - - } else { - MITK_INFO << "[FAIL]: Tracts do not contain same amount of points! \n "; - MITK_INFO << " # of Points m_Cont: " << contNrPnts << " | GroupFibers: " << fibrNrPnts << " | ITKCont: " << itkcontNrPnts << "\n"; - } - - - - - //use for()loop with index instead of iterator cuz of accessing more elements, std vectors provide no index output - for(int ip=0; ipGetElement(ip); - - //get point from itkStochContainer - itkStochTractType::VertexType itkPnt = itkcontVrtx->GetElement(ip); - - //get point from dtiGroup - DTITubePointType tmpDtiPnt = dtiPntList.at(ip); - DTITubePointType::PointType dtiPoint = tmpDtiPnt.GetPosition(); - - - if (tmpcontPnt[0] == (float)itkPnt[0] && (float)itkPnt[0] == (float)dtiPoint[0]) { - MITK_INFO << "TractCont | ITKCont | DTIGroup X: " << tmpcontPnt[0] << "...TEST [OK] " << "\n"; - }else{ - MITK_INFO << "TractCont | ITKCont | DTIGroup X: " << tmpcontPnt[0] << " " << itkPnt[0] << " " << dtiPoint[0] << "...TEST ##### [FAIL] \n"; - } - - if (tmpcontPnt[1] == (float)itkPnt[1] && (float)itkPnt[1] == (float)dtiPoint[1]) { - MITK_INFO << "TractCont | ITKCont | DTIGroup Y: " << tmpcontPnt[1] << "...TEST [OK] " << "\n"; - }else{ - MITK_INFO << "TractCont | ITKCont | DTIGroup Y: " << tmpcontPnt[1] << " " << itkPnt[1] << " " << dtiPoint[1] << "\n"; - } - - if (tmpcontPnt[2] == (float)itkPnt[2] && (float)itkPnt[2] == (float)dtiPoint[2]) { - MITK_INFO << "TractCont | ITKCont | DTIGroup Z: " << tmpcontPnt[2] << "...TEST [OK] " << "\n"; - }else{ - MITK_INFO << "TractCont | ITKCont | DTIGroup Z: " << tmpcontPnt[2] << " " << itkPnt[2] << " " << dtiPoint[2] << "\n"; - } - - } - ++itITKCnt; - ++itLst; - } - -} - -vtkSmartPointer mitk::FiberBundle::GeneratePolydata() -{ - MITK_INFO << "writing polydata"; - //extractn single fibers - //in the groupFiberBundle all smartPointers to single fibers are stored in in a ChildrenList - mitk::FiberBundle::ChildrenListType * FiberList; - FiberList = this->m_GroupFiberBundle->GetChildren(); - - /* ######## FIBER PREPARATION END ######### */ - - /* ######## VTK FIBER REPRESENTATION ######## */ - //create a vtkPoints object and store the all the brainFiber points in it - vtkSmartPointer vtkpoints = vtkPoints::New(); - - //in vtkcells all polylines are stored, actually all id's of them are stored - vtkSmartPointer vtkcells = vtkCellArray::New(); - - //in some cases a fiber includes just 1 point, so put it in here - vtkSmartPointer vtkVrtxs = vtkCellArray::New(); - - //colors and alpha value for each single point, RGBA = 4 components - vtkSmartPointer colorsT = vtkUnsignedCharArray::New(); - colorsT->SetNumberOfComponents(4); - colorsT->SetName("ColorValues"); - - vtkSmartPointer faColors = vtkDoubleArray::New(); - faColors->SetName("FaColors"); - - //vtkDoubleArray *tubeRadius = vtkDoubleArray::New(); - //tubeRadius->SetName("TubeRadius"); - - - // iterate through FiberList - for(mitk::FiberBundle::ChildrenListType::iterator itLst = FiberList->begin(); - itLst != FiberList->end(); - ++itLst) - { - //all points are stored in one vtkpoints list, soooooooo that the lines find their point id to start and end we need some kind of helper index who monitors the current ids for a polyline - unsigned long pntIdxHelper = vtkpoints->GetNumberOfPoints(); - - // lists output is SpatialObject, we know we have DTITubeSpacialObjects - // dynamic cast only likes pointers, no smartpointers, so each dsmartpointer has membermethod .GetPointer() - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - mitk::FiberBundle::DTITubeType::Pointer dtiTract = dynamic_cast< mitk::FiberBundle::DTITubeType * > (tmp_fbr.GetPointer()); - if (dtiTract.IsNull()) { - return NULL; } - - //get list of points - int fibrNrPnts = dtiTract->GetNumberOfPoints(); - mitk::FiberBundle::DTITubeType::PointListType dtiPntList = dtiTract->GetPoints(); - - //create a new polyline for a dtiTract - //smartpointer - vtkSmartPointer polyLine = vtkPolyLine::New(); - polyLine->GetPointIds()->SetNumberOfIds(fibrNrPnts); - unsigned char rgba[4] = {255,255,255,255}; - - //tubeRadius->SetNumberOfTuples(fibrNrPnts); - //double tbradius = 1;//default value for radius - - if (fibrNrPnts <= 0) { //this should never occour! but who knows - MITK_INFO << "HyperERROR in fiberBundleMapper3D.cpp ...no point in fiberBundle!!! .. check ur trackingAlgorithm"; - continue; - } - - - for (int i=0; iGetGeometry()->IndexToWorld(indexPnt, worldPnt); - double worldFbrPnt[3] = {worldPnt[0], worldPnt[1], worldPnt[2]}; - vtkpoints->InsertNextPoint(worldFbrPnt); - - // tubeRadius->SetTuple1(i,tbradius); //tuple with 1 argument - - - if (fibrNrPnts == 1) { - // if there ist just 1 point in a fiber...wtf, but however represent it as a point - vtkSmartPointer vrtx = vtkVertex::New(); - vrtx->GetPointIds()->SetNumberOfIds(1); - vrtx->GetPointIds()->SetId(i,i+pntIdxHelper); - colorsT->InsertNextTupleValue(rgba); - vtkVrtxs->InsertNextCell(vrtx); - - } else { - - polyLine->GetPointIds()->SetId(i,i+pntIdxHelper); - - //colorcoding orientation based - if (i0) - { - //nimm nur diff1 - mitk::FiberBundle::DTITubePointType nxttmpFiberPntLst = dtiPntList.at(i+1); - mitk::FiberBundle::DTITubePointType::PointType nxttmpFiberPnt = nxttmpFiberPntLst.GetPosition(); - //double nxttmpvtkPnt[3] = {nxttmpFiberPnt[0], nxttmpFiberPnt[1], nxttmpFiberPnt[2]}; - - vnl_vector_fixed< double, 3 > tmpPntvtk((double)tmpvtkPnt[0], (double)tmpvtkPnt[1],(double)tmpvtkPnt[2]); - vnl_vector_fixed< double, 3 > nxttmpPntvtk(nxttmpFiberPnt[0], nxttmpFiberPnt[1], nxttmpFiberPnt[2]); - - vnl_vector_fixed< double, 3 > diff; - diff = tmpPntvtk - nxttmpPntvtk; - diff.normalize(); - - rgba[0] = (unsigned char) (255.0 * std::abs(diff[0])); - rgba[1] = (unsigned char) (255.0 * std::abs(diff[1])); - rgba[2] = (unsigned char) (255.0 * std::abs(diff[2])); - rgba[3] = (unsigned char) (255.0); - - - - } else if(i==0) { - //explicit handling of startpoint of line - - //nimm nur diff1 - mitk::FiberBundle::DTITubePointType nxttmpFiberPntLst = dtiPntList.at(i+1); - mitk::FiberBundle::DTITubePointType::PointType nxttmpFiberPnt = nxttmpFiberPntLst.GetPosition(); - //double nxttmpvtkPnt[3] = {nxttmpFiberPnt[0], nxttmpFiberPnt[1], nxttmpFiberPnt[2]}; - - vnl_vector_fixed< double, 3 > tmpPntvtk((double)tmpvtkPnt[0], (double)tmpvtkPnt[1],(double)tmpvtkPnt[2]); - vnl_vector_fixed< double, 3 > nxttmpPntvtk(nxttmpFiberPnt[0], nxttmpFiberPnt[1], nxttmpFiberPnt[2]); - - vnl_vector_fixed< double, 3 > diff; - diff = tmpPntvtk - nxttmpPntvtk; - diff.normalize(); - - rgba[0] = (unsigned char) (255.0 * std::abs(diff[0])); - rgba[1] = (unsigned char) (255.0 * std::abs(diff[1])); - rgba[2] = (unsigned char) (255.0 * std::abs(diff[2])); - rgba[3] = (unsigned char) (255.0); - - - - - } else if(i==fibrNrPnts) { - // nimm nur diff2 - mitk::FiberBundle::DTITubePointType nxttmpFiberPntLst = dtiPntList.at(i-1); - mitk::FiberBundle::DTITubePointType::PointType nxttmpFiberPnt = nxttmpFiberPntLst.GetPosition(); - - vnl_vector_fixed< double, 3 > tmpPntvtk((double)tmpvtkPnt[0], (double)tmpvtkPnt[1],(double)tmpvtkPnt[2]); - vnl_vector_fixed< double, 3 > nxttmpPntvtk(nxttmpFiberPnt[0], nxttmpFiberPnt[1], nxttmpFiberPnt[2]); - - vnl_vector_fixed< double, 3 > diff; - diff = tmpPntvtk - nxttmpPntvtk; - diff.normalize(); - - rgba[0] = (unsigned char) (255.0 * std::abs(diff[0])); - rgba[1] = (unsigned char) (255.0 * std::abs(diff[1])); - rgba[2] = (unsigned char) (255.0 * std::abs(diff[2])); - rgba[3] = (unsigned char) (255.0); - - - - - } - - colorsT->InsertNextTupleValue(rgba); - - //get FA value - float faVal = tmpFiberPntLst.GetField(mitk::FiberBundle::DTITubePointType::FA); - //use insertNextValue cuz FA Values are reperesented as a single number (1 Tuple containing 1 parameter) - faColors->InsertNextValue((double) faVal); - - - } - } - vtkcells->InsertNextCell(polyLine); - - } - - //vtkcells->InitTraversal(); - - // Put points and lines together in one polyData structure - m_PolyData = vtkPolyData::New(); - m_PolyData->SetPoints(vtkpoints); - m_PolyData->SetLines(vtkcells); - if (vtkVrtxs->GetSize() > 0) { - m_PolyData->SetVerts(vtkVrtxs); - } - m_PolyData->GetPointData()->AddArray(colorsT); - m_PolyData->GetPointData()->AddArray(faColors); - return m_PolyData; -} - -/* NECESSARY IMPLEMENTATION OF SUPERCLASS METHODS */ -void mitk::FiberBundle::UpdateOutputInformation() -{ - -} -void mitk::FiberBundle::SetRequestedRegionToLargestPossibleRegion() -{ - -} -bool mitk::FiberBundle::RequestedRegionIsOutsideOfTheBufferedRegion() -{ - return false; -} -bool mitk::FiberBundle::VerifyRequestedRegion() -{ - return true; -} -void mitk::FiberBundle::SetRequestedRegion( itk::DataObject *data ) -{ - -} - - -/* TUTORIAL INSERT POINTS / FIBERS to TRACTCONTAINER */ -// points and vectors do not need to be initiated but itkVectorContainer -/*ContainerPointType pnt1; - pnt1[0] = 1.0; - pnt1[1] = 2.0; - pnt1[2] = 3.0; - - ContainerPointType pnt2; - pnt2[0] = 4.0; - pnt2[1] = 5.0; - pnt2[2] = 6.0; - - ContainerTractType tract1; - tract1.push_back(pnt1); - tract1.push_back(pnt2); - - ContainerType::Pointer testContainer = ContainerType::New(); - unsigned int freeIdx = testContainer->Size(); - MITK_INFO << freeIdx << "\n"; - testContainer->InsertElement(freeIdx, tract1); - - //iterate through all fibers stored in container - for(ContainerType::ConstIterator itCont = testContainer->Begin(); - itCont != testContainer->End(); - itCont++) - { - //get single tract - ContainerTractType tmp_fiber = itCont->Value(); - // MITK_INFO << tmp_fiber << "\n"; - - //iterate through all points within a fibertract - for(ContainerTractType::iterator itPnt = tmp_fiber.begin(); - itPnt != tmp_fiber.end(); - ++itPnt) - { - // get single point with its coordinates - ContainerPointType tmp_pntEx = *itPnt; - MITK_INFO << tmp_pntEx[0] << "\n"; - MITK_INFO << tmp_pntEx[1] << "\n"; - MITK_INFO << tmp_pntEx[2] << "\n"; - } - - } - ################### DTI FIBERs TUTORIAL ########################### - TUTORIAL HOW TO READ POINTS / FIBERS from DTIGroupSpatialObjectContainer - assume our dti fibers are stored in m_GroupFiberBundle - - // all smartPointers to fibers stored in in a ChildrenList - ChildrenListType * FiberList; - FiberList = m_GroupFiberBundle->GetChildren(); - - // iterate through container, itkcontainer groupFiberBundle in one iteration step - for(ChildrenListType::iterator itLst = FiberList->begin(); - itLst != FiberList->end(); - ++FiberList) - { - // lists output is SpatialObject, we know we have DTITubeSpacialObjects - // dynamic cast only likes pointers, no smartpointers, so each dsmartpointer has membermethod .GetPointer() - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - DTITubeType::Pointer dtiTract = dynamic_cast (tmp_fbr.GetPointer()); - if (dtiTract.IsNull()) { - return; } - - //get list of points - int fibrNrPnts = dtiTract->GetNumberOfPoints(); - DTITubeType::PointListType dtiPntList = dtiTract->GetPoints(); - - } - - - */ - diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundle.h b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundle.h deleted file mode 100644 index 345de3a1de..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundle.h +++ /dev/null @@ -1,196 +0,0 @@ - -/*========================================================================= - - Program: Medical Imaging & Interaction Toolkit - Module: $RCSfile$ - Language: C++ - Date: $Date$ - Version: $Revision: 11989 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ - - -#ifndef _MITK_FiberBundle_H -#define _MITK_FiberBundle_H - -//includes for MITK datastructure -#include "mitkBaseData.h" -#include - -//=======modernized================ -//includes storing fiberdata -#include //may be replaced by class precompile argument -#include // may be replaced by class -#include // my be replaced by class - - -//includes processing of fibers -// -//=========modernized end=========== - - -#include - -/* This Class represents a bunch of FiberTracts as a Bundle. - A Bundle is represented by a GroupSpatialObject */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include - -namespace mitk { - - /** - * \brief Base Class for Fiber Bundles; */ - class MitkDiffusionImaging_EXPORT FiberBundle : public BaseData - { - public: - - /* friend classes wanna access typedefs - ContainerPointType, ContainerTractType, ContainerType */ - friend class FiberBundleWriter; - friend class FiberBundleReader; - // friend class itkTractsToDWIImageFilter; - - /** Types for the standardized TractContainer **/ - typedef itk::Point ContainerPointType; //no need to init, is no smartpointer - typedef itk::VectorContainer ContainerTractType; - typedef itk::VectorContainer< unsigned int, ContainerTractType::Pointer > ContainerType; //init via smartpointer - - - - /** Types for the ITK Stochastic TractContainer **/ - typedef itk::SlowPolyLineParametricPath< 3 > itkStochTractType; - typedef itk::VectorContainer< unsigned int, itkStochTractType::Pointer > itkStochTractContainerType; - - - // virtual methods that need to be implemented - virtual void UpdateOutputInformation(); - virtual void SetRequestedRegionToLargestPossibleRegion(); - virtual bool RequestedRegionIsOutsideOfTheBufferedRegion(); - virtual bool VerifyRequestedRegion(); - virtual void SetRequestedRegion( itk::DataObject *data ); - - static const int TRACTPOINT_BACKFACE; - static const int TRACTPOINT_ON_PLANE; - static const int TRACTPOINT_FRNTFACE; - - - /* DTITubeSpatialObject Definitions */ - typedef itk::GroupSpatialObject<3> FiberGroupType; - typedef FiberGroupType::ChildrenListType ChildrenListType; - - typedef itk::DTITubeSpatialObject<3> DTITubeType; - typedef itk::DTITubeSpatialObjectPoint<3> DTITubePointType; - - mitkClassMacro( FiberBundle, BaseData ); - itkNewMacro( Self ); - - - /* Handle Output Type of ITK Stochastic Tractography Fiber Tracking */ - void addTractContainer( ContainerType::Pointer ); - void additkStochTractContainer(itkStochTractContainerType::Pointer); - void initFiberGroup(); - void addSingleDTITract(mitk::FiberBundle::DTITubeType::Pointer); - DTITubeType::Pointer copySingleDTITract(DTITubeType::Pointer); - - /* Methods for PlanarFigure ROIs */ - //mitk::FiberBundle::Pointer extractFibersPF(mitk::PlanarFigure::Pointer); - std::vector extractFibersByPF(mitk::PlanarFigure::Pointer, std::vector* set=0); - mitk::FiberBundle::Pointer extractFibersById(std::vector ); - std::vector getAllIDsInFiberBundle(); - - - mitk::Point3D calculateCrossingPoint(mitk::Point3D , mitk::Point3D , mitk::PlanarFigure::Pointer ); //depricated - bool checkForGap(int, int); //depricated - /*********************************/ - - - void debug_members(); - - void SetBounds(float* b); - void SetBounds(double* b); - float* GetBounds(); - - - -//**** REALTIME MONITOR CONTAINER METHOD ****// - //flag overwrite existing bundle - void addContainer4speedDisplay( ContainerType::Pointer ); - - itkGetMacro(GroupFiberBundle, FiberGroupType::Pointer); - itkGetMacro(TractContainer, ContainerType::Pointer); - - //** explicit handling of FiberBundleDataStructure contents *// - void PushPoint(int fiberIndex, ContainerPointType point); - void PushTract(ContainerTractType::Pointer tract); - ContainerPointType GetPoint(int tractIndex, int pointIndex); - ContainerTractType::Pointer GetTract(int tractIndex); - int GetNumTracts(); - int GetNumPoints(int tractIndex); - FiberGroupType::Pointer getGroupFiberBundle(); - - mitk::FiberBundle::Pointer JoinBundle(mitk::FiberBundle::Pointer bundle); - int FindTractByEndpoints(mitk::FiberBundle::DTITubeType::Pointer searchTract); - mitk::FiberBundle::Pointer SubstractBundle(mitk::FiberBundle::Pointer bundle); - void InsertBundle(mitk::FiberBundle::Pointer bundle); - vtkSmartPointer GeneratePolydata(); - -// int SearchFiber(worldPoint, tolerance, resultDistance); - - protected: - FiberBundle(); - virtual ~FiberBundle(); - - private: -// =========MODERNIZED========== -// The following polydata variables are used for fiber- and pointbased representation of the tractography results. As VTK suggests, one vtkPolyData is used to manage vertices and the other for polylines. -// FiberPolyData stores all brain fibers using polylines (in world coordinates) - vtkSmartPointer m_FiberPolyData; - -// VertexPolyData stores all original points as vertices computed by tracking algorithms - vtkSmartPointer m_VertexPolyData; - vtkSmartPointer m_Particles; - -// ===============Moedernized end===== - FiberGroupType::Pointer m_GroupFiberBundle; - ContainerType::Pointer m_TractContainer; - itkStochTractContainerType::Pointer m_debugITKContainer; - - void fiberPostprocessing_FA( DTITubePointType* ); - void fiberPostprocessing_setPoint(DTITubePointType* , ContainerPointType ); - void fiberPostprocessing_setTensorMatrix(DTITubePointType*); - - int debug_PrototypeCounter; - float m_boundsFB[3]; - - /* Methods for PlanarFigure ROIs */ - bool isPointInSelection(mitk::Point3D, mitk::PlanarFigure::Pointer); - vtkSmartPointer m_PolyData; - - }; - -} // namespace mitk - -#endif /* _MITK_FiberBundle_H */ diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleIOFactory.cpp b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleIOFactory.cpp deleted file mode 100644 index c4134a9c20..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleIOFactory.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2007-12-11 14:46:19 +0100 (Di, 11 Dez 2007) $ -Version: $Revision: 6607 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - -#include "mitkFiberBundleIOFactory.h" -#include "mitkIOAdapter.h" -#include "mitkFiberBundleReader.h" - -#include "itkVersion.h" - -//NOTE>umbenennen in FBReaderType - - -namespace mitk -{ - -FiberBundleIOFactory::FiberBundleIOFactory() -{ - typedef FiberBundleReader FiberBundleReaderType; - this->RegisterOverride("mitkIOAdapter", //beibehalten - "mitkFiberBundleReader", //umbenennen - "Fiber Bundle IO", //angezeigter name - 1, - itk::CreateObjectFunction >::New()); -} - -FiberBundleIOFactory::~FiberBundleIOFactory() -{ -} - -const char* FiberBundleIOFactory::GetITKSourceVersion() const -{ - return ITK_SOURCE_VERSION; -} - -const char* FiberBundleIOFactory::GetDescription() const -{ - return "FibreBundleIOFactory, allows the loading of FibreBundles"; -} - -} // end namespace mitk diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleIOFactory.h b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleIOFactory.h deleted file mode 100644 index 6fb8a2f5a7..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleIOFactory.h +++ /dev/null @@ -1,76 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-13 18:06:46 +0200 (Mi, 13 Mai 2009) $ -Version: $Revision: 6590 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ -#ifndef __MITK_FIBER_BUNDLE_IO_FACTORY_H_HEADER__ -#define __MITK_FIBER_BUNDLE_IO_FACTORY_H_HEADER__ - -#ifdef _MSC_VER -#pragma warning ( disable : 4786 ) -#endif - -#include "itkObjectFactoryBase.h" -#include "mitkBaseData.h" -#include "MitkDiffusionImagingExports.h" - -//NOTE>umbenennen in internal FiberBundleIOFactory - - -namespace mitk -{ -//##Documentation -//## @brief Create instances of NrrdQBallImageReader objects using an object factory. -//## -//## @ingroup IO -class MitkDiffusionImaging_EXPORT FiberBundleIOFactory : public itk::ObjectFactoryBase -{ -public: - /** Standard class typedefs. */ - typedef FiberBundleIOFactory Self; - typedef itk::ObjectFactoryBase Superclass; - typedef itk::SmartPointer Pointer; - typedef itk::SmartPointer ConstPointer; - - /** Class methods used to interface with the registered factories. */ - virtual const char* GetITKSourceVersion(void) const; - virtual const char* GetDescription(void) const; - - /** Method for class instantiation. */ - itkFactorylessNewMacro(Self); - static FiberBundleIOFactory* FactoryNew() { return new FiberBundleIOFactory;} - /** Run-time type information (and related methods). */ - itkTypeMacro(FiberBundleIOFactory, ObjectFactoryBase); - - /** Register one factory of this type */ - static void RegisterOneFactory(void) - { - FiberBundleIOFactory::Pointer FiberBundleIOFactory = FiberBundleIOFactory::New(); - ObjectFactoryBase::RegisterFactory(FiberBundleIOFactory); - } - -protected: - FiberBundleIOFactory(); - ~FiberBundleIOFactory(); - -private: - FiberBundleIOFactory(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - -}; - - -} // end namespace mitk - -#endif // __MITK_FIBER_BUNDLE_IO_FACTORY_H_HEADER__ diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleReader.cpp b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleReader.cpp deleted file mode 100644 index fb892104ad..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleReader.cpp +++ /dev/null @@ -1,427 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - -#include "mitkFiberBundleReader.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -const char* mitk::FiberBundleReader::XML_GEOMETRY = "geometry"; - -const char* mitk::FiberBundleReader::XML_MATRIX_XX = "xx"; - -const char* mitk::FiberBundleReader::XML_MATRIX_XY = "xy"; - -const char* mitk::FiberBundleReader::XML_MATRIX_XZ = "xz"; - -const char* mitk::FiberBundleReader::XML_MATRIX_YX = "yx"; - -const char* mitk::FiberBundleReader::XML_MATRIX_YY = "yy"; - -const char* mitk::FiberBundleReader::XML_MATRIX_YZ = "yz"; - -const char* mitk::FiberBundleReader::XML_MATRIX_ZX = "zx"; - -const char* mitk::FiberBundleReader::XML_MATRIX_ZY = "zy"; - -const char* mitk::FiberBundleReader::XML_MATRIX_ZZ = "zz"; - -const char* mitk::FiberBundleReader::XML_ORIGIN_X = "origin_x"; - -const char* mitk::FiberBundleReader::XML_ORIGIN_Y = "origin_y"; - -const char* mitk::FiberBundleReader::XML_ORIGIN_Z = "origin_z"; - -const char* mitk::FiberBundleReader::XML_SPACING_X = "spacing_x"; - -const char* mitk::FiberBundleReader::XML_SPACING_Y = "spacing_y"; - -const char* mitk::FiberBundleReader::XML_SPACING_Z = "spacing_z"; - -const char* mitk::FiberBundleReader::XML_SIZE_X = "size_x"; - -const char* mitk::FiberBundleReader::XML_SIZE_Y = "size_y"; - -const char* mitk::FiberBundleReader::XML_SIZE_Z = "size_z"; - -const char* mitk::FiberBundleReader::XML_FIBER_BUNDLE = "fiber_bundle"; - -const char* mitk::FiberBundleReader::XML_FIBER = "fiber"; - -const char* mitk::FiberBundleReader::XML_PARTICLE = "particle"; - -const char* mitk::FiberBundleReader::XML_ID = "id"; - -const char* mitk::FiberBundleReader::XML_POS_X = "pos_x"; - -const char* mitk::FiberBundleReader::XML_POS_Y = "pos_y"; - -const char* mitk::FiberBundleReader::XML_POS_Z = "pos_z"; - -const char* mitk::FiberBundleReader::XML_NUM_FIBERS = "num_fibers"; - -const char* mitk::FiberBundleReader::XML_NUM_PARTICLES = "num_particles"; - -const char* mitk::FiberBundleReader::XML_FIBER_BUNDLE_FILE = "fiber_bundle_file" ; - -const char* mitk::FiberBundleReader::XML_FILE_VERSION = "file_version" ; - -const char* mitk::FiberBundleReader::VERSION_STRING = "0.1" ; - -namespace mitk -{ - - void FiberBundleReader - ::GenerateData() - { - MITK_INFO << "Reading fiber bundle"; - if ( ( ! m_OutputCache ) ) - { - Superclass::SetNumberOfRequiredOutputs(0); - this->GenerateOutputInformation(); - } - - if (!m_OutputCache) - { - itkWarningMacro("Tree cache is empty!"); - } - - - Superclass::SetNumberOfRequiredOutputs(1); - Superclass::SetNthOutput(0, m_OutputCache.GetPointer()); - } - - void FiberBundleReader::GenerateOutputInformation() - { - m_OutputCache = OutputType::New(); - - std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); - ext = itksys::SystemTools::LowerCase(ext); - - const std::string& locale = "C"; - const std::string& currLocale = setlocale( LC_ALL, NULL ); - - if ( locale.compare(currLocale)!=0 ) - { - try - { - setlocale(LC_ALL, locale.c_str()); - } - catch(...) - { - MITK_INFO << "Could not set locale " << locale; - } - } - - if ( m_FileName == "") - { - - } - else if (ext == ".fib") - { - try - { - TiXmlDocument doc( m_FileName ); - doc.LoadFile(); - - TiXmlHandle hDoc(&doc); - TiXmlElement* pElem; - TiXmlHandle hRoot(0); - - pElem = hDoc.FirstChildElement().Element(); - - // save this for later - hRoot = TiXmlHandle(pElem); - - pElem = hRoot.FirstChildElement(FiberBundleReader::XML_GEOMETRY).Element(); - - // read geometry - mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); - - // read origin - mitk::Point3D origin; - double temp = 0; - pElem->Attribute(FiberBundleReader::XML_ORIGIN_X, &temp); - origin[0] = temp; - pElem->Attribute(FiberBundleReader::XML_ORIGIN_Y, &temp); - origin[1] = temp; - pElem->Attribute(FiberBundleReader::XML_ORIGIN_Z, &temp); - origin[2] = temp; - geometry->SetOrigin(origin); - - // read spacing - float spacing[3]; - pElem->Attribute(FiberBundleReader::XML_SPACING_X, &temp); - spacing[0] = temp; - pElem->Attribute(FiberBundleReader::XML_SPACING_Y, &temp); - spacing[1] = temp; - pElem->Attribute(FiberBundleReader::XML_SPACING_Z, &temp); - spacing[2] = temp; - geometry->SetSpacing(spacing); - - // read transform - vtkMatrix4x4* m = vtkMatrix4x4::New(); - pElem->Attribute(FiberBundleReader::XML_MATRIX_XX, &temp); - m->SetElement(0,0,temp); - pElem->Attribute(FiberBundleReader::XML_MATRIX_XY, &temp); - m->SetElement(1,0,temp); - pElem->Attribute(FiberBundleReader::XML_MATRIX_XZ, &temp); - m->SetElement(2,0,temp); - pElem->Attribute(FiberBundleReader::XML_MATRIX_YX, &temp); - m->SetElement(0,1,temp); - pElem->Attribute(FiberBundleReader::XML_MATRIX_YY, &temp); - m->SetElement(1,1,temp); - pElem->Attribute(FiberBundleReader::XML_MATRIX_YZ, &temp); - m->SetElement(2,1,temp); - pElem->Attribute(FiberBundleReader::XML_MATRIX_ZX, &temp); - m->SetElement(0,2,temp); - pElem->Attribute(FiberBundleReader::XML_MATRIX_ZY, &temp); - m->SetElement(1,2,temp); - pElem->Attribute(FiberBundleReader::XML_MATRIX_ZZ, &temp); - m->SetElement(2,2,temp); - - m->SetElement(0,3,origin[0]); - m->SetElement(1,3,origin[1]); - m->SetElement(2,3,origin[2]); - m->SetElement(3,3,1); - geometry->SetIndexToWorldTransformByVtkMatrix(m); - - // read bounds - float bounds[] = {0, 0, 0, 0, 0, 0}; - pElem->Attribute(FiberBundleReader::XML_SIZE_X, &temp); - bounds[1] = temp; - pElem->Attribute(FiberBundleReader::XML_SIZE_Y, &temp); - bounds[3] = temp; - pElem->Attribute(FiberBundleReader::XML_SIZE_Z, &temp); - bounds[5] = temp; - geometry->SetFloatBounds(bounds); - - // read bounds - float bounds2[] = {0, 0, 0}; - bounds2[0] = bounds[1]; - bounds2[1] = bounds[3]; - bounds2[2] = bounds[5]; - m_OutputCache->SetBounds(bounds2); - - geometry->SetImageGeometry(true); - m_OutputCache->SetGeometry(geometry); - - // generate tract container - ContainerType::Pointer tractContainer = ContainerType::New(); - - int fiberID = 0; - pElem = hRoot.FirstChildElement(FiberBundleReader::XML_FIBER_BUNDLE).FirstChild().Element(); - for( pElem; pElem; pElem=pElem->NextSiblingElement()) - { - TiXmlElement* pElem2 = pElem->FirstChildElement(); - ContainerTractType::Pointer tract = ContainerTractType::New(); - for( pElem2; pElem2; pElem2=pElem2->NextSiblingElement()) - { - ContainerPointType point; - pElem2->Attribute(FiberBundleReader::XML_POS_X, &temp); - point[0] = temp; - pElem2->Attribute(FiberBundleReader::XML_POS_Y, &temp); - point[1] = temp; - pElem2->Attribute(FiberBundleReader::XML_POS_Z, &temp); - point[2] = temp; - - tract->InsertElement(tract->Size(), point); - - } - pElem->Attribute(FiberBundleReader::XML_ID, &fiberID); - tractContainer->CreateIndex(fiberID); - tractContainer->SetElement(fiberID, tract); - - } - m_OutputCache->addTractContainer(tractContainer); - m_OutputCache->initFiberGroup(); - - MITK_INFO << "Fiber bundle read"; - } - catch(...) - { - MITK_INFO << "Could not read file "; - } - } - else if (ext == ".vfib") - { - // generate tract container - ContainerType::Pointer tractContainer = ContainerType::New(); - mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); - - ///We create a Generic Reader to test de .vtk/ - vtkDataReader *chooser=vtkDataReader::New(); - chooser->SetFileName(m_FileName.c_str() ); - if( chooser->IsFilePolyData()) - { - vtkPolyDataReader *reader = vtkPolyDataReader::New(); - reader->SetFileName( m_FileName.c_str() ); - reader->Update(); - - if ( reader->GetOutput() != NULL ) - { - vtkPolyData* output = reader->GetOutput(); - double* center = output->GetCenter(); - MITK_INFO << "center: " << center[0] << ", " << center[1] << ", " << center[2]; - - float min = itk::NumericTraits::min(); - float max = itk::NumericTraits::max(); - float b[] = {max, min, max, min, max, min}; - - vtkCellArray* cells = output->GetLines(); - cells->InitTraversal(); - for (int i=0; iGetNumberOfCells(); i++) - { - ContainerTractType::Pointer tract = ContainerTractType::New(); - vtkCell* cell = output->GetCell(i); - int p = cell->GetNumberOfPoints(); - vtkPoints* points = cell->GetPoints(); - for (int j=0; jGetPoint(j, p); - ContainerPointType point; - point[0] = p[0]; - point[1] = p[1]; - point[2] = p[2]; - - if (point[0]b[1]) - b[1]=point[0]; - - if (point[1]b[3]) - b[3]=point[1]; - - if (point[2]b[5]) - b[5]=point[2]; - - tract->InsertElement(tract->Size(), point); - } - tractContainer->InsertElement(i, tract); - } - - float bounds[] = {0, 0, 0}; - bounds[0] = b[1]; - bounds[1] = b[3]; - bounds[2] = b[5]; - m_OutputCache->SetBounds(bounds); - - geometry->SetImageGeometry(true); - geometry->SetFloatBounds(b); - m_OutputCache->SetGeometry(geometry); - } - reader->Delete(); - } - chooser->Delete(); - - m_OutputCache->addTractContainer(tractContainer); - m_OutputCache->initFiberGroup(); - MITK_INFO << "Fiber bundle read"; - } - - try - { - setlocale(LC_ALL, currLocale.c_str()); - } - catch(...) - { - MITK_INFO << "Could not reset locale " << currLocale; - } - } - - void FiberBundleReader::Update() - { - this->GenerateData(); - } - - const char* FiberBundleReader - ::GetFileName() const - { - return m_FileName.c_str(); - } - - - void FiberBundleReader - ::SetFileName(const char* aFileName) - { - m_FileName = aFileName; - } - - - const char* FiberBundleReader - ::GetFilePrefix() const - { - return m_FilePrefix.c_str(); - } - - - void FiberBundleReader - ::SetFilePrefix(const char* aFilePrefix) - { - m_FilePrefix = aFilePrefix; - } - - - const char* FiberBundleReader - ::GetFilePattern() const - { - return m_FilePattern.c_str(); - } - - - void FiberBundleReader - ::SetFilePattern(const char* aFilePattern) - { - m_FilePattern = aFilePattern; - } - - - bool FiberBundleReader - ::CanReadFile(const std::string filename, const std::string /*filePrefix*/, const std::string /*filePattern*/) - { - // First check the extension - if( filename == "" ) - { - return false; - } - std::string ext = itksys::SystemTools::GetFilenameLastExtension(filename); - ext = itksys::SystemTools::LowerCase(ext); - - if (ext == ".fib" || ext == ".vfib") - { - return true; - } - - return false; - } - -} //namespace MITK diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleReader.h b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleReader.h deleted file mode 100644 index 09b32561a9..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleReader.h +++ /dev/null @@ -1,147 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ -Version: $Revision: 18127 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - -#ifndef __mitkFiberBundleReader_h -#define __mitkFiberBundleReader_h - -#include "mitkCommon.h" -#include "itkVectorContainer.h" -#include "mitkFileReader.h" -#include "mitkFiberBundle.h" -#include "itkSlowPolyLineParametricPath.h" - -//NOTE>umbenennen in FiberBundleSource - -namespace mitk -{ - - /** \brief - */ - - class FiberBundleReader : public FileReader, public BaseProcess - { - public: - - /** Types for the standardized TractContainer **/ - /* direct linked includes of mitkFiberBundle DataStructure */ - typedef mitk::FiberBundle::ContainerPointType ContainerPointType; - typedef mitk::FiberBundle::ContainerTractType ContainerTractType; - typedef mitk::FiberBundle::ContainerType ContainerType; - - - typedef mitk::FiberBundle OutputType; - - mitkClassMacro( FiberBundleReader, BaseProcess ); - itkNewMacro(Self); - - const char* GetFileName() const; - void SetFileName(const char* aFileName); - const char* GetFilePrefix() const; - void SetFilePrefix(const char* aFilePrefix); - const char* GetFilePattern() const; - void SetFilePattern(const char* aFilePattern); - - static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); - -// itkGetMacro(GroupFiberBundle, FiberGroupType::Pointer); -// itkGetMacro(TractContainer, ContainerType::Pointer); - - virtual void Update(); - - - static const char* XML_GEOMETRY; - - static const char* XML_MATRIX_XX; - - static const char* XML_MATRIX_XY; - - static const char* XML_MATRIX_XZ; - - static const char* XML_MATRIX_YX; - - static const char* XML_MATRIX_YY; - - static const char* XML_MATRIX_YZ; - - static const char* XML_MATRIX_ZX; - - static const char* XML_MATRIX_ZY; - - static const char* XML_MATRIX_ZZ; - - static const char* XML_ORIGIN_X; - - static const char* XML_ORIGIN_Y; - - static const char* XML_ORIGIN_Z; - - static const char* XML_SPACING_X; - - static const char* XML_SPACING_Y; - - static const char* XML_SPACING_Z; - - static const char* XML_SIZE_X; - - static const char* XML_SIZE_Y; - - static const char* XML_SIZE_Z; - - static const char* XML_FIBER_BUNDLE; - - static const char* XML_FIBER; - - static const char* XML_PARTICLE; - - static const char* XML_ID; - - static const char* XML_POS_X; - - static const char* XML_POS_Y; - - static const char* XML_POS_Z; - - static const char* VERSION_STRING; - - static const char* XML_FIBER_BUNDLE_FILE; - - static const char* XML_FILE_VERSION; - - static const char* XML_NUM_FIBERS; - - static const char* XML_NUM_PARTICLES; - - protected: - - /** Does the real work. */ - virtual void GenerateData(); - virtual void GenerateOutputInformation(); - - OutputType::Pointer m_OutputCache; - - std::string m_FileName; - std::string m_FilePrefix; - std::string m_FilePattern; - ContainerType::Pointer m_TractContainer; - - private: - void operator=(const Self&); //purposely not implemented - }; - -} //namespace MITK - -#endif // __mitkFiberBundleReader_h diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSerializer.cpp b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSerializer.cpp deleted file mode 100644 index d78fe3b912..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSerializer.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 1.12 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - -#include "mitkFiberBundleSerializer.h" -#include "mitkFiberBundle.h" -#include "mitkFiberBundleWriter.h" - -#include - - -MITK_REGISTER_SERIALIZER(FiberBundleSerializer) - - -mitk::FiberBundleSerializer::FiberBundleSerializer() -{ -} - - -mitk::FiberBundleSerializer::~FiberBundleSerializer() -{ -} - - -std::string mitk::FiberBundleSerializer::Serialize() -{ - const FiberBundle* fb = dynamic_cast( m_Data.GetPointer() ); - if (fb == NULL) - { - MITK_ERROR << " Object at " << (const void*) this->m_Data - << " is not an mitk::FiberBundle. Cannot serialize as FiberBundle."; - return ""; - } - - std::string filename( this->GetUniqueFilenameInWorkingDirectory() ); - filename += "_"; - filename += m_FilenameHint; - filename += ".fib"; - - std::string fullname(m_WorkingDirectory); - fullname += "/"; - fullname += itksys::SystemTools::ConvertToOutputPath(filename.c_str()); - - try - { - FiberBundleWriter::Pointer writer = FiberBundleWriter::New(); - writer->SetFileName(fullname); - writer->SetInputFiberBundle(const_cast(fb)); - writer->Write(); - } - catch (std::exception& e) - { - MITK_ERROR << " Error serializing object at " << (const void*) this->m_Data - << " to " - << fullname - << ": " - << e.what(); - return ""; - } - return filename; -} - diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSerializer.h b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSerializer.h deleted file mode 100644 index 820aef2fb7..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSerializer.h +++ /dev/null @@ -1,40 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date$ -Version: $Revision: 1.12 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - -#ifndef mitkFiberBundleSerializer_h_included -#define mitkFiberBundleSerializer_h_included - -#include "MitkDiffusionImagingExports.h" -#include "mitkBaseDataSerializer.h" - -namespace mitk -{ -/** - \brief Serializes mitk::Surface for mitk::SceneIO -*/ -class MitkDiffusionImaging_EXPORT FiberBundleSerializer : public BaseDataSerializer -{ - public: - mitkClassMacro( FiberBundleSerializer, BaseDataSerializer ); - itkNewMacro(Self); - virtual std::string Serialize(); - protected: - FiberBundleSerializer(); - virtual ~FiberBundleSerializer(); -}; -} // namespace -#endif diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSource.cpp b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSource.cpp deleted file mode 100644 index 0c780e249f..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSource.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $ -Version: $Revision: 17179 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - - -#include "mitkQBallImageSource.h" - - -mitk::QBallImageSource::QBallImageSource() -{ - // Create the output. We use static_cast<> here because we know the default - // output must be of type TOutputImage - OutputImageType::Pointer output - = static_cast(this->MakeOutput(0).GetPointer()); - Superclass::SetNumberOfRequiredOutputs(1); - Superclass::SetNthOutput(0, output.GetPointer()); -} - -mitk::QBallImageSource::DataObjectPointer mitk::QBallImageSource::MakeOutput( unsigned int /*idx*/ ) -{ - return static_cast(OutputImageType::New().GetPointer()); -} diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSource.h b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSource.h deleted file mode 100644 index ce50970b88..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleSource.h +++ /dev/null @@ -1,52 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $ -Version: $Revision: 17179 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - - -#ifndef QBallImageSource_H_HEADER_INCLUDED_C1E7D6EC -#define QBallImageSource_H_HEADER_INCLUDED_C1E7D6EC - -#include "mitkImageSource.h" -#include "mitkQBallImage.h" - -//NOTE>umbenennen .. ableiten von DataSource - - -namespace mitk { - -class QBallImageSource : public ImageSource -{ -public: - - typedef mitk::QBallImage OutputImageType; - typedef OutputImageType::Pointer OutputImagePointer; - typedef SlicedData::RegionType OutputImageRegionType; - typedef itk::DataObject::Pointer DataObjectPointer; - - mitkClassMacro(QBallImageSource,ImageSource); - itkNewMacro(Self); - - virtual DataObjectPointer MakeOutput(unsigned int idx); - -protected: - QBallImageSource(); - virtual ~QBallImageSource() {} - -}; - -} // namespace mitk - -#endif /* QBallImageSource_H_HEADER_INCLUDED_C1E7D6EC */ diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriter.cpp b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriter.cpp deleted file mode 100644 index 41f24ed4a5..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriter.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2008-12-10 18:05:13 +0100 (Mi, 10 Dez 2008) $ -Version: $Revision: 15922 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - -#include "mitkFiberBundleWriter.h" -#include - -const char* mitk::FiberBundleWriter::XML_GEOMETRY = "geometry"; - -const char* mitk::FiberBundleWriter::XML_MATRIX_XX = "xx"; - -const char* mitk::FiberBundleWriter::XML_MATRIX_XY = "xy"; - -const char* mitk::FiberBundleWriter::XML_MATRIX_XZ = "xz"; - -const char* mitk::FiberBundleWriter::XML_MATRIX_YX = "yx"; - -const char* mitk::FiberBundleWriter::XML_MATRIX_YY = "yy"; - -const char* mitk::FiberBundleWriter::XML_MATRIX_YZ = "yz"; - -const char* mitk::FiberBundleWriter::XML_MATRIX_ZX = "zx"; - -const char* mitk::FiberBundleWriter::XML_MATRIX_ZY = "zy"; - -const char* mitk::FiberBundleWriter::XML_MATRIX_ZZ = "zz"; - -const char* mitk::FiberBundleWriter::XML_ORIGIN_X = "origin_x"; - -const char* mitk::FiberBundleWriter::XML_ORIGIN_Y = "origin_y"; - -const char* mitk::FiberBundleWriter::XML_ORIGIN_Z = "origin_z"; - -const char* mitk::FiberBundleWriter::XML_SPACING_X = "spacing_x"; - -const char* mitk::FiberBundleWriter::XML_SPACING_Y = "spacing_y"; - -const char* mitk::FiberBundleWriter::XML_SPACING_Z = "spacing_z"; - -const char* mitk::FiberBundleWriter::XML_SIZE_X = "size_x"; - -const char* mitk::FiberBundleWriter::XML_SIZE_Y = "size_y"; - -const char* mitk::FiberBundleWriter::XML_SIZE_Z = "size_z"; - -const char* mitk::FiberBundleWriter::XML_FIBER_BUNDLE = "fiber_bundle"; - -const char* mitk::FiberBundleWriter::XML_FIBER = "fiber"; - -const char* mitk::FiberBundleWriter::XML_PARTICLE = "particle"; - -const char* mitk::FiberBundleWriter::XML_ID = "id"; - -const char* mitk::FiberBundleWriter::XML_POS_X = "pos_x"; - -const char* mitk::FiberBundleWriter::XML_POS_Y = "pos_y"; - -const char* mitk::FiberBundleWriter::XML_POS_Z = "pos_z"; - -const char* mitk::FiberBundleWriter::XML_NUM_FIBERS = "num_fibers"; - -const char* mitk::FiberBundleWriter::XML_NUM_PARTICLES = "num_particles"; - -const char* mitk::FiberBundleWriter::XML_FIBER_BUNDLE_FILE = "fiber_bundle_file" ; - -const char* mitk::FiberBundleWriter::XML_FILE_VERSION = "file_version" ; - -const char* mitk::FiberBundleWriter::VERSION_STRING = "0.1" ; - -const char* mitk::FiberBundleWriter::ASCII_FILE = "ascii_file" ; - -const char* mitk::FiberBundleWriter::FILE_NAME = "file_name" ; - -mitk::FiberBundleWriter::FiberBundleWriter() - : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) -{ - this->SetNumberOfRequiredInputs( 1 ); -} - - -mitk::FiberBundleWriter::~FiberBundleWriter() -{} - - -void mitk::FiberBundleWriter::GenerateData() -{ - try - { - MITK_INFO << "Writing fiber bundle"; - m_Success = false; - InputType* input = this->GetInput(); - if (input == NULL) - { - itkWarningMacro(<<"Sorry, input to FiberBundleWriter is NULL!"); - return; - } - if ( m_FileName == "" ) - { - itkWarningMacro( << "Sorry, filename has not been set!" ); - return ; - } - - const std::string& locale = "C"; - const std::string& currLocale = setlocale( LC_ALL, NULL ); - - if ( locale.compare(currLocale)!=0 ) - { - try - { - setlocale(LC_ALL, locale.c_str()); - } - catch(...) - { - MITK_INFO << "Could not set locale " << locale; - } - } - - std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); - ext = itksys::SystemTools::LowerCase(ext); - - if (ext == ".fib") - { - /* direct linked includes of mitkFiberBundle DataStructure */ - typedef mitk::FiberBundle::ContainerPointType ContainerPointType; - typedef mitk::FiberBundle::ContainerTractType ContainerTractType; - typedef mitk::FiberBundle::ContainerType ContainerType; - - ContainerType::Pointer tractContainer = input->GetTractContainer(); - mitk::Geometry3D* geometry = input->GetGeometry(); - - TiXmlDocument documentXML; - TiXmlDeclaration* declXML = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc.... - documentXML.LinkEndChild( declXML ); - - TiXmlElement* mainXML = new TiXmlElement(mitk::FiberBundleWriter::XML_FIBER_BUNDLE_FILE); - mainXML->SetAttribute(mitk::FiberBundleWriter::XML_FILE_VERSION, mitk::FiberBundleWriter::VERSION_STRING); - documentXML.LinkEndChild(mainXML); - - TiXmlElement* geometryXML = new TiXmlElement(mitk::FiberBundleWriter::XML_GEOMETRY); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_MATRIX_XX, geometry->GetMatrixColumn(0)[0]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_MATRIX_XY, geometry->GetMatrixColumn(0)[1]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_MATRIX_XZ, geometry->GetMatrixColumn(0)[2]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_MATRIX_YX, geometry->GetMatrixColumn(1)[0]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_MATRIX_YY, geometry->GetMatrixColumn(1)[1]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_MATRIX_YZ, geometry->GetMatrixColumn(1)[2]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_MATRIX_ZX, geometry->GetMatrixColumn(2)[0]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_MATRIX_ZY, geometry->GetMatrixColumn(2)[1]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_MATRIX_ZZ, geometry->GetMatrixColumn(2)[2]); - - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_ORIGIN_X, geometry->GetOrigin()[0]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_ORIGIN_Y, geometry->GetOrigin()[1]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_ORIGIN_Z, geometry->GetOrigin()[2]); - - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_SPACING_X, geometry->GetSpacing()[0]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_SPACING_Y, geometry->GetSpacing()[1]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_SPACING_Z, geometry->GetSpacing()[2]); - - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_SIZE_X, input->GetBounds()[0]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_SIZE_Y, input->GetBounds()[1]); - geometryXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_SIZE_Z, input->GetBounds()[2]); - - mainXML->LinkEndChild(geometryXML); - - TiXmlElement* fiberBundleXML = new TiXmlElement(mitk::FiberBundleWriter::XML_FIBER_BUNDLE); - fiberBundleXML->SetAttribute(mitk::FiberBundleWriter::XML_NUM_FIBERS, tractContainer->size()); - int numParticles = 0; - for (int i=0; iSize(); i++) - { - ContainerTractType::Pointer tract = tractContainer->GetElement(i); - TiXmlElement* fiberXML = new TiXmlElement(mitk::FiberBundleWriter::XML_FIBER); - fiberXML->SetAttribute(mitk::FiberBundleWriter::XML_ID, i); - fiberXML->SetAttribute(mitk::FiberBundleWriter::XML_NUM_PARTICLES, tract->Size()); - numParticles += tract->Size(); - for (int j=0; jSize(); j++) - { - TiXmlElement* particleXML = new TiXmlElement(mitk::FiberBundleWriter::XML_PARTICLE); - ContainerPointType p = tract->GetElement(j); - particleXML->SetAttribute(mitk::FiberBundleWriter::XML_ID, j); - particleXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_POS_X, p[0]); - particleXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_POS_Y, p[1]); - particleXML->SetDoubleAttribute(mitk::FiberBundleWriter::XML_POS_Z, p[2]); - fiberXML->LinkEndChild(particleXML); - } - fiberBundleXML->LinkEndChild(fiberXML); - } - fiberBundleXML->SetAttribute(mitk::FiberBundleWriter::XML_NUM_PARTICLES, numParticles); - mainXML->LinkEndChild(fiberBundleXML); - - documentXML.SaveFile( m_FileName ); - - m_Success = true; - - MITK_INFO << "Fiber bundle written"; - - }else if (ext == ".vfib" || ext == ".vtk") { - vtkPolyDataWriter* writer = vtkPolyDataWriter::New(); - writer->SetInput(input->GeneratePolydata()); - writer->SetFileName(m_FileName.c_str()); - writer->SetFileTypeToASCII(); - writer->Write(); - - m_Success = true; - MITK_INFO << "Fiber bundle written as polydata"; - } - try - { - setlocale(LC_ALL, currLocale.c_str()); - } - catch(...) - { - MITK_INFO << "Could not reset locale " << currLocale; - } - } - catch(...) - { - throw; - } -} - - -void mitk::FiberBundleWriter::SetInputFiberBundle( InputType* diffVolumes ) -{ - this->ProcessObject::SetNthInput( 0, diffVolumes ); -} - - -mitk::FiberBundle* mitk::FiberBundleWriter::GetInput() -{ - if ( this->GetNumberOfInputs() < 1 ) - { - return NULL; - } - else - { - return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); - } -} - - -std::vector mitk::FiberBundleWriter::GetPossibleFileExtensions() -{ - std::vector possibleFileExtensions; - possibleFileExtensions.push_back(".fib"); - possibleFileExtensions.push_back(".vfib"); - possibleFileExtensions.push_back(".vtk"); - return possibleFileExtensions; -} diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriter.h b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriter.h deleted file mode 100644 index da7bef49c7..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriter.h +++ /dev/null @@ -1,216 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2008-08-27 17:18:46 +0200 (Mi, 27 Aug 2008) $ -Version: $Revision: 15096 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - -#ifndef __mitkFiberBundleWriter_h -#define __mitkFiberBundleWriter_h - -#include -#include -#include "mitkFiberBundle.h" -#include - - -namespace mitk -{ - -/** - * Writes fiber bundles to a file - * @ingroup Process - */ -class FiberBundleWriter : public mitk::FileWriterWithInformation -{ -public: - - mitkClassMacro( FiberBundleWriter, mitk::FileWriterWithInformation ); - - //mitkWriterMacro; - - virtual void Write() - { - if ( this->GetInput() == NULL ) - { - itkExceptionMacro(<<"Write:Please specify an input!"); - return; - } - /* Fill in image information.*/ - this->UpdateOutputInformation(); - (*(this->GetInputs().begin()))->SetRequestedRegionToLargestPossibleRegion(); - this->PropagateRequestedRegion(NULL); - this->UpdateOutputData(NULL); - } - - virtual void Update() - { - Write(); - } - - itkNewMacro( Self ); - - typedef mitk::FiberBundle InputType; - - /** - * Sets the filename of the file to write. - * @param FileName the name of the file to write. - */ - itkSetStringMacro( FileName ); - - /** - * @returns the name of the file to be written to disk. - */ - itkGetStringMacro( FileName ); - - /** - * @warning multiple write not (yet) supported - */ - itkSetStringMacro( FilePrefix ); - - /** - * @warning multiple write not (yet) supported - */ - itkGetStringMacro( FilePrefix ); - - /** - * @warning multiple write not (yet) supported - */ - itkSetStringMacro( FilePattern ); - - /** - * @warning multiple write not (yet) supported - */ - itkGetStringMacro( FilePattern ); - - /** - * Sets the input object for the filter. - * @param input the diffusion volumes to write to file. - */ - void SetInputFiberBundle( InputType* input ); - - /** - * @returns the 0'th input object of the filter. - */ - InputType* GetInput(); - - /** - * Returns false if an error happened during writing - */ - itkGetMacro( Success, bool ); - - /** - * @return possible file extensions for the data type associated with the writer - */ - virtual std::vector GetPossibleFileExtensions(); - - // FileWriterWithInformation methods - virtual const char * GetDefaultFilename() { return "FiberBundle.fib"; } - virtual const char * GetFileDialogPattern() { return "Fiber Bundle (*.fib *.vfib *.vtk)"; } - virtual const char * GetDefaultExtension() { return ".fib"; } - virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); }; - virtual void DoWrite(BaseData::Pointer data) { - if (CanWriteBaseDataType(data)) { - this->SetInputFiberBundle(dynamic_cast(data.GetPointer())); - this->Update(); - } - }; - - static const char* XML_GEOMETRY; - - static const char* XML_MATRIX_XX; - - static const char* XML_MATRIX_XY; - - static const char* XML_MATRIX_XZ; - - static const char* XML_MATRIX_YX; - - static const char* XML_MATRIX_YY; - - static const char* XML_MATRIX_YZ; - - static const char* XML_MATRIX_ZX; - - static const char* XML_MATRIX_ZY; - - static const char* XML_MATRIX_ZZ; - - static const char* XML_ORIGIN_X; - - static const char* XML_ORIGIN_Y; - - static const char* XML_ORIGIN_Z; - - static const char* XML_SPACING_X; - - static const char* XML_SPACING_Y; - - static const char* XML_SPACING_Z; - - static const char* XML_SIZE_X; - - static const char* XML_SIZE_Y; - - static const char* XML_SIZE_Z; - - static const char* XML_FIBER_BUNDLE; - - static const char* XML_FIBER; - - static const char* XML_PARTICLE; - - static const char* XML_ID; - - static const char* XML_POS_X; - - static const char* XML_POS_Y; - - static const char* XML_POS_Z; - - static const char* VERSION_STRING; - - static const char* XML_FIBER_BUNDLE_FILE; - - static const char* XML_FILE_VERSION; - - static const char* XML_NUM_FIBERS; - - static const char* XML_NUM_PARTICLES; - - static const char* ASCII_FILE; - - static const char* FILE_NAME; - -protected: - - FiberBundleWriter(); - - virtual ~FiberBundleWriter(); - - virtual void GenerateData(); - - std::string m_FileName; - - std::string m_FilePrefix; - - std::string m_FilePattern; - - bool m_Success; - -}; - - -} // end of namespace mitk - -#endif //__mitkFiberBundleWriter_h diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriterFactory.cpp b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriterFactory.cpp deleted file mode 100644 index 0b4bc55c37..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriterFactory.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2007-12-11 14:46:19 +0100 (Di, 11 Dez 2007) $ -Version: $Revision: 11215 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - -#include "mitkFiberBundleWriterFactory.h" - -#include "itkCreateObjectFunction.h" -#include "itkVersion.h" - -#include "mitkFiberBundleWriter.h" - -namespace mitk -{ - -template -class CreateFiberBundleWriter : public itk::CreateObjectFunctionBase -{ -public: - - /** Standard class typedefs. */ - typedef CreateFiberBundleWriter Self; - typedef itk::SmartPointer Pointer; - - /** Methods from itk:LightObject. */ - itkFactorylessNewMacro(Self); - LightObject::Pointer CreateObject() { typename T::Pointer p = T::New(); - p->Register(); - return p.GetPointer(); - } - -protected: - CreateFiberBundleWriter() {} - ~CreateFiberBundleWriter() {} - -private: - CreateFiberBundleWriter(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented -}; - -FiberBundleWriterFactory::FiberBundleWriterFactory() -{ - this->RegisterOverride("IOWriter", - "FiberBundleWriter", - "FiberBundle Writer", - 1, - mitk::CreateFiberBundleWriter< mitk::FiberBundleWriter >::New()); -} - -FiberBundleWriterFactory::~FiberBundleWriterFactory() -{ -} - -const char* FiberBundleWriterFactory::GetITKSourceVersion() const -{ - return ITK_SOURCE_VERSION; -} - -const char* FiberBundleWriterFactory::GetDescription() const -{ - return "FiberBundleWriterFactory"; -} - -} // end namespace mitk diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriterFactory.h b/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriterFactory.h deleted file mode 100644 index 15459f7ef1..0000000000 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkFiberBundleWriterFactory.h +++ /dev/null @@ -1,68 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-13 18:06:46 +0200 (Mi, 13 Mai 2009) $ -Version: $Revision: 11215 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - -#ifndef FIBERBUNDLE_WRITERFACTORY_H_HEADER_INCLUDED -#define FIBERBUNDLE_WRITERFACTORY_H_HEADER_INCLUDED - -#include "itkObjectFactoryBase.h" -#include "mitkBaseData.h" -#include "MitkDiffusionImagingExports.h" - -namespace mitk -{ - -class MitkDiffusionImaging_EXPORT FiberBundleWriterFactory : public itk::ObjectFactoryBase -{ -public: - - mitkClassMacro( mitk::FiberBundleWriterFactory, itk::ObjectFactoryBase ) - - /** Class methods used to interface with the registered factories. */ - virtual const char* GetITKSourceVersion(void) const; - virtual const char* GetDescription(void) const; - - /** Method for class instantiation. */ - itkFactorylessNewMacro(Self); - - /** Register one factory of this type */ - static void RegisterOneFactory(void) - { - static bool IsRegistered = false; - if ( !IsRegistered ) - { - FiberBundleWriterFactory::Pointer ugVtkWriterFactory = FiberBundleWriterFactory::New(); - ObjectFactoryBase::RegisterFactory( ugVtkWriterFactory ); - IsRegistered = true; - } - } - -protected: - FiberBundleWriterFactory(); - ~FiberBundleWriterFactory(); - -private: - FiberBundleWriterFactory(const Self&); //purposely not implemented - void operator=(const Self&); //purposely not implemented - -}; - -} // end namespace mitk - -#endif // FIBERBUNDLE_WRITERFACTORY_H_HEADER_INCLUDED - - - diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.cpp b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.cpp index f1c42d9c31..125d95d04f 100644 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.cpp +++ b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.cpp @@ -1,363 +1,1162 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ Version: $Revision: 21975 $ - + Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - + This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. - + =========================================================================*/ #include "mitkFiberBundleX.h" -/* musthave */ -//#include // without geometry, fibers are not rendered +#include +#include +#include + #include +#include #include #include #include +#include #include +#include +#include +#include + -// baptize array names const char* mitk::FiberBundleX::COLORCODING_ORIENTATION_BASED = "Color_Orient"; -const char* mitk::FiberBundleX::COLORCODING_FA_BASED = "Color_FA"; +//const char* mitk::FiberBundleX::COLORCODING_FA_AS_OPACITY = "Color_Orient_FA_Opacity"; +const char* mitk::FiberBundleX::FA_VALUE_ARRAY = "FA_Values"; +const char* mitk::FiberBundleX::COLORCODING_CUSTOM = "custom"; const char* mitk::FiberBundleX::FIBER_ID_ARRAY = "Fiber_IDs"; - - -mitk::FiberBundleX::FiberBundleX(vtkSmartPointer fiberPolyData ) +mitk::FiberBundleX::FiberBundleX( vtkPolyData* fiberPolyData ) : m_currentColorCoding(NULL) - , m_isModified(false) + , m_NumFibers(0) { - //generate geometry of passed polydata if (fiberPolyData == NULL) - this->m_FiberPolyData = vtkSmartPointer::New(); + m_FiberPolyData = vtkSmartPointer::New(); else - this->m_FiberPolyData = fiberPolyData; + m_FiberPolyData = fiberPolyData; + + m_NumFibers = m_FiberPolyData->GetNumberOfLines(); this->UpdateFiberGeometry(); + //generate colorcoding + this->DoColorCodingOrientationbased(); + this->SetColorCoding(COLORCODING_ORIENTATION_BASED); + this->DoGenerateFiberIds(); -} +} mitk::FiberBundleX::~FiberBundleX() { - // Memory Management - m_FiberPolyData->Delete(); + +} + +mitk::FiberBundleX::Pointer mitk::FiberBundleX::GetDeepCopy() +{ + mitk::FiberBundleX::Pointer newFib = mitk::FiberBundleX::New(); + + // newFib->m_FiberIdDataSet = vtkSmartPointer::New(); + newFib->m_FiberIdDataSet->DeepCopy(m_FiberIdDataSet); + newFib->m_FiberPolyData = vtkSmartPointer::New(); + newFib->m_FiberPolyData->DeepCopy(m_FiberPolyData); + newFib->SetColorCoding(m_currentColorCoding); + newFib->m_NumFibers = m_NumFibers; + newFib->UpdateFiberGeometry(); + + return newFib; +} + +vtkSmartPointer mitk::FiberBundleX::GenerateNewFiberBundleByIds(std::vector fiberIds) +{ + MITK_INFO << "\n=====FINAL RESULT: fib_id ======\n"; + MITK_INFO << "Number of new Fibers: " << fiberIds.size(); + // iterate through the vectorcontainer hosting all desired fiber Ids + + vtkSmartPointer newFiberPolyData = vtkSmartPointer::New(); + vtkSmartPointer newLineSet = vtkSmartPointer::New(); + vtkSmartPointer newPointSet = vtkSmartPointer::New(); + + // if FA array available, initialize fa double array + // if color orient array is available init color array + vtkSmartPointer faValueArray; + vtkSmartPointer colorsT; + //colors and alpha value for each single point, RGBA = 4 components + unsigned char rgba[4] = {0,0,0,0}; + int componentSize = sizeof(rgba); + + if (m_FiberIdDataSet->GetPointData()->HasArray(FA_VALUE_ARRAY)){ + MITK_INFO << "FA VALUES AVAILABLE, init array for new fiberbundle"; + faValueArray = vtkSmartPointer::New(); + } + + if (m_FiberIdDataSet->GetPointData()->HasArray(COLORCODING_ORIENTATION_BASED)){ + MITK_INFO << "colorValues available, init array for new fiberbundle"; + colorsT = vtkUnsignedCharArray::New(); + colorsT->SetNumberOfComponents(componentSize); + colorsT->SetName(COLORCODING_ORIENTATION_BASED); + } + + + + std::vector::iterator finIt = fiberIds.begin(); + while ( finIt != fiberIds.end() ) + { + if (*finIt < 0){ + MITK_INFO << "!!!!!! ERROR !!!!!! ERROR !!!!!\n=======================\nERROR, fiberID can not be negative!!! check id Extraction!" << *finIt; + break; + } + vtkSmartPointer fiber = m_FiberIdDataSet->GetCell(*finIt);//->DeepCopy(fiber); + vtkSmartPointer fibPoints = fiber->GetPoints(); + + vtkSmartPointer newFiber = vtkSmartPointer::New(); + newFiber->GetPointIds()->SetNumberOfIds( fibPoints->GetNumberOfPoints() ); + + for(int i=0; iGetNumberOfPoints(); i++) + { + // MITK_INFO << "id: " << fiber->GetPointId(i); + // MITK_INFO << fibPoints->GetPoint(i)[0] << " | " << fibPoints->GetPoint(i)[1] << " | " << fibPoints->GetPoint(i)[2]; + newFiber->GetPointIds()->SetId(i, newPointSet->GetNumberOfPoints()); + newPointSet->InsertNextPoint(fibPoints->GetPoint(i)[0], fibPoints->GetPoint(i)[1], fibPoints->GetPoint(i)[2]); + + + if (m_FiberIdDataSet->GetPointData()->HasArray(FA_VALUE_ARRAY)){ + // MITK_INFO << m_FiberIdDataSet->GetPointData()->GetArray(FA_VALUE_ARRAY)->GetTuple(fiber->GetPointId(i)); + } + + if (m_FiberIdDataSet->GetPointData()->HasArray(COLORCODING_ORIENTATION_BASED)){ + // MITK_INFO << "ColorValue: " << m_FiberIdDataSet->GetPointData()->GetArray(COLORCODING_ORIENTATION_BASED)->GetTuple(fiber->GetPointId(i))[0]; + } + } + + newLineSet->InsertNextCell(newFiber); + ++finIt; + } + + newFiberPolyData->SetPoints(newPointSet); + newFiberPolyData->SetLines(newLineSet); + MITK_INFO << "new fiberbundle polydata points: " << newFiberPolyData->GetNumberOfPoints(); + MITK_INFO << "new fiberbundle polydata lines: " << newFiberPolyData->GetNumberOfLines(); + MITK_INFO << "=====================\n"; + + // mitk::FiberBundleX::Pointer newFib = mitk::FiberBundleX::New(newFiberPolyData); + return newFiberPolyData; +} + +// merge two fiber bundles +mitk::FiberBundleX::Pointer mitk::FiberBundleX::operator+(mitk::FiberBundleX* fib) +{ + + vtkSmartPointer vNewPolyData = vtkSmartPointer::New(); + vtkSmartPointer vNewLines = vtkSmartPointer::New(); + vtkSmartPointer vNewPoints = vtkSmartPointer::New(); + + vtkSmartPointer vLines = m_FiberPolyData->GetLines(); + vLines->InitTraversal(); + + // add current fiber bundle + int numFibers = GetNumFibers(); + for( int i=0; iGetNextCell ( numPoints, points ); + + vtkSmartPointer container = vtkSmartPointer::New(); + for( int j=0; jInsertNextPoint(m_FiberPolyData->GetPoint(points[j])); + container->GetPointIds()->InsertNextId(id); + } + vNewLines->InsertNextCell(container); + } + + vLines = fib->m_FiberPolyData->GetLines(); + vLines->InitTraversal(); + + // add new fiber bundle + numFibers = fib->GetNumFibers(); + for( int i=0; iGetNextCell ( numPoints, points ); + + vtkSmartPointer container = vtkSmartPointer::New(); + for( int j=0; jInsertNextPoint(fib->m_FiberPolyData->GetPoint(points[j])); + container->GetPointIds()->InsertNextId(id); + } + vNewLines->InsertNextCell(container); + } + + // initialize polydata + vNewPolyData->SetPoints(vNewPoints); + vNewPolyData->SetLines(vNewLines); + + // initialize fiber bundle + mitk::FiberBundleX::Pointer newFib = mitk::FiberBundleX::New(vNewPolyData); + return newFib; +} + +// subtract two fiber bundles +mitk::FiberBundleX::Pointer mitk::FiberBundleX::operator-(mitk::FiberBundleX* fib) +{ + + vtkSmartPointer vNewPolyData = vtkSmartPointer::New(); + vtkSmartPointer vNewLines = vtkSmartPointer::New(); + vtkSmartPointer vNewPoints = vtkSmartPointer::New(); + + vtkSmartPointer vLines = m_FiberPolyData->GetLines(); + vLines->InitTraversal(); + + // iterate over current fibers + int numFibers = GetNumFibers(); + for( int i=0; iGetNextCell ( numPoints, points ); + + vtkSmartPointer vLines2 = fib->m_FiberPolyData->GetLines(); + vLines2->InitTraversal(); + int numFibers2 = fib->GetNumFibers(); + bool contained = false; + for( int i2=0; i2GetNextCell ( numPoints2, points2 ); + + // check endpoints + itk::Point point_start = GetItkPoint(m_FiberPolyData->GetPoint(points[0])); + itk::Point point_end = GetItkPoint(m_FiberPolyData->GetPoint(points[numPoints-1])); + itk::Point point2_start = GetItkPoint(fib->m_FiberPolyData->GetPoint(points2[0])); + itk::Point point2_end = GetItkPoint(fib->m_FiberPolyData->GetPoint(points2[numPoints2-1])); + + if (point_start.SquaredEuclideanDistanceTo(point2_start)<=mitk::eps && point_end.SquaredEuclideanDistanceTo(point2_end)<=mitk::eps || + point_start.SquaredEuclideanDistanceTo(point2_end)<=mitk::eps && point_end.SquaredEuclideanDistanceTo(point2_start)<=mitk::eps) + { + // further checking ??? + contained = true; + } + } + + // add to result because fiber is not subtracted + if (!contained) + { + vtkSmartPointer container = vtkSmartPointer::New(); + for( int j=0; jInsertNextPoint(m_FiberPolyData->GetPoint(points[j])); + container->GetPointIds()->InsertNextId(id); + } + vNewLines->InsertNextCell(container); + } + } + + // initialize polydata + vNewPolyData->SetPoints(vNewPoints); + vNewPolyData->SetLines(vNewLines); + + // initialize fiber bundle + mitk::FiberBundleX::Pointer newFib = mitk::FiberBundleX::New(vNewPolyData); + return newFib; +} + +itk::Point mitk::FiberBundleX::GetItkPoint(double point[3]) +{ + itk::Point itkPoint; + itkPoint[0] = point[0]; + itkPoint[1] = point[1]; + itkPoint[2] = point[2]; + return itkPoint; } -/* === main input method ==== - * set computed fibers from tractography algorithms +/* + * set polydata (additional flag to recompute fiber geometry, default = true) */ -void mitk::FiberBundleX::SetFiberPolyData(vtkSmartPointer fiberPD) -{ +void mitk::FiberBundleX::SetFiberPolyData(vtkSmartPointer fiberPD, bool updateGeometry) +{ if (fiberPD == NULL) this->m_FiberPolyData = vtkSmartPointer::New(); else this->m_FiberPolyData = fiberPD; - m_isModified = true; -} + if (updateGeometry) + UpdateFiberGeometry(); + m_NumFibers = m_FiberPolyData->GetNumberOfLines(); -/* === main output method === - * return fiberbundle as vtkPolyData - * Depending on processing of input fibers, this method returns - * the latest processed fibers. + // m_isModified = true; +} + +/* + * return vtkPolyData */ vtkSmartPointer mitk::FiberBundleX::GetFiberPolyData() { return m_FiberPolyData; } - - - -/*============================================== - *++++ PROCESSING WITH FIBER INFORMATION +++++++ - =============================================*/ - void mitk::FiberBundleX::DoColorCodingOrientationbased() { //===== FOR WRITING A TEST ======================== // colorT size == tupelComponents * tupelElements // compare color results // to cover this code 100% also polydata needed, where colorarray already exists // + one fiber with exactly 1 point // + one fiber with 0 points //================================================= /* make sure that processing colorcoding is only called when necessary */ if ( m_FiberPolyData->GetPointData()->HasArray(COLORCODING_ORIENTATION_BASED) && m_FiberPolyData->GetNumberOfPoints() == m_FiberPolyData->GetPointData()->GetArray(COLORCODING_ORIENTATION_BASED)->GetNumberOfTuples() ) { // fiberstructure is already colorcoded - MITK_INFO << " NO NEED TO REGENERATE COLORCODING!"; + MITK_INFO << " NO NEED TO REGENERATE COLORCODING! " ; + this->ResetFiberColorOpacity(); + this->SetColorCoding(COLORCODING_ORIENTATION_BASED); return; } - /* Finally, execute color calculation */ vtkPoints* extrPoints = m_FiberPolyData->GetPoints(); int numOfPoints = extrPoints->GetNumberOfPoints(); //colors and alpha value for each single point, RGBA = 4 components unsigned char rgba[4] = {0,0,0,0}; - int componentSize = sizeof(rgba); + // int componentSize = sizeof(rgba); + int componentSize = 4; - vtkUnsignedCharArray *colorsT = vtkUnsignedCharArray::New(); + vtkSmartPointer colorsT = vtkUnsignedCharArray::New(); colorsT->Allocate(numOfPoints * componentSize); colorsT->SetNumberOfComponents(componentSize); colorsT->SetName(COLORCODING_ORIENTATION_BASED); /* checkpoint: does polydata contain any fibers */ int numOfFibers = m_FiberPolyData->GetNumberOfLines(); if (numOfFibers < 1) { - MITK_INFO << "\n ========= Number of Fibers is below 1 ========= \n"; + MITK_INFO << "\n ========= Number of Fibers is 0 and below ========= \n"; return; } /* extract single fibers of fiberBundle */ vtkCellArray* fiberList = m_FiberPolyData->GetLines(); + fiberList->InitTraversal(); for (int fi=0; fiGetNextCell(numOfPoints, idList); + vtkIdType pointsPerFiber; // number of points for current line + fiberList->GetNextCell(pointsPerFiber, idList); + + // MITK_INFO << "Fib#: " << fi << " of " << numOfFibers << " pnts in fiber: " << pointsPerFiber ; /* single fiber checkpoints: is number of points valid */ - if (numOfPoints > 1) + if (pointsPerFiber > 1) { /* operate on points of single fiber */ - for (int i=0; i 0) + if (i 0) { /* The color value of the current point is influenced by the previous point and next point. */ vnl_vector_fixed< double, 3 > currentPntvtk(extrPoints->GetPoint(idList[i])[0], extrPoints->GetPoint(idList[i])[1],extrPoints->GetPoint(idList[i])[2]); vnl_vector_fixed< double, 3 > nextPntvtk(extrPoints->GetPoint(idList[i+1])[0], extrPoints->GetPoint(idList[i+1])[1], extrPoints->GetPoint(idList[i+1])[2]); vnl_vector_fixed< double, 3 > prevPntvtk(extrPoints->GetPoint(idList[i-1])[0], extrPoints->GetPoint(idList[i-1])[1], extrPoints->GetPoint(idList[i-1])[2]); vnl_vector_fixed< double, 3 > diff1; diff1 = currentPntvtk - nextPntvtk; - diff1.normalize(); vnl_vector_fixed< double, 3 > diff2; diff2 = currentPntvtk - prevPntvtk; - diff2.normalize(); vnl_vector_fixed< double, 3 > diff; diff = (diff1 - diff2) / 2.0; + diff.normalize(); - rgba[0] = (unsigned char) (255.0 * std::abs(diff[0])); - rgba[1] = (unsigned char) (255.0 * std::abs(diff[1])); - rgba[2] = (unsigned char) (255.0 * std::abs(diff[2])); + rgba[0] = (unsigned char) (255.0 * std::fabs(diff[0])); + rgba[1] = (unsigned char) (255.0 * std::fabs(diff[1])); + rgba[2] = (unsigned char) (255.0 * std::fabs(diff[2])); rgba[3] = (unsigned char) (255.0); } else if (i==0) { /* First point has no previous point, therefore only diff1 is taken */ vnl_vector_fixed< double, 3 > currentPntvtk(extrPoints->GetPoint(idList[i])[0], extrPoints->GetPoint(idList[i])[1],extrPoints->GetPoint(idList[i])[2]); vnl_vector_fixed< double, 3 > nextPntvtk(extrPoints->GetPoint(idList[i+1])[0], extrPoints->GetPoint(idList[i+1])[1], extrPoints->GetPoint(idList[i+1])[2]); vnl_vector_fixed< double, 3 > diff1; diff1 = currentPntvtk - nextPntvtk; diff1.normalize(); - rgba[0] = (unsigned char) (255.0 * std::abs(diff1[0])); - rgba[1] = (unsigned char) (255.0 * std::abs(diff1[1])); - rgba[2] = (unsigned char) (255.0 * std::abs(diff1[2])); + rgba[0] = (unsigned char) (255.0 * std::fabs(diff1[0])); + rgba[1] = (unsigned char) (255.0 * std::fabs(diff1[1])); + rgba[2] = (unsigned char) (255.0 * std::fabs(diff1[2])); rgba[3] = (unsigned char) (255.0); - } else if (i==numOfPoints-1) { + + } else if (i==pointsPerFiber-1) { /* Last point has no next point, therefore only diff2 is taken */ vnl_vector_fixed< double, 3 > currentPntvtk(extrPoints->GetPoint(idList[i])[0], extrPoints->GetPoint(idList[i])[1],extrPoints->GetPoint(idList[i])[2]); vnl_vector_fixed< double, 3 > prevPntvtk(extrPoints->GetPoint(idList[i-1])[0], extrPoints->GetPoint(idList[i-1])[1], extrPoints->GetPoint(idList[i-1])[2]); vnl_vector_fixed< double, 3 > diff2; diff2 = currentPntvtk - prevPntvtk; diff2.normalize(); - rgba[0] = (unsigned char) (255.0 * std::abs(diff2[0])); - rgba[1] = (unsigned char) (255.0 * std::abs(diff2[1])); - rgba[2] = (unsigned char) (255.0 * std::abs(diff2[2])); + rgba[0] = (unsigned char) (255.0 * std::fabs(diff2[0])); + rgba[1] = (unsigned char) (255.0 * std::fabs(diff2[1])); + rgba[2] = (unsigned char) (255.0 * std::fabs(diff2[2])); rgba[3] = (unsigned char) (255.0); } colorsT->InsertTupleValue(idList[i], rgba); + } //end for loop - } else if (numOfPoints == 1) { + } else if (pointsPerFiber == 1) { /* a single point does not define a fiber (use vertex mechanisms instead */ continue; // colorsT->InsertTupleValue(0, rgba); } else { MITK_INFO << "Fiber with 0 points detected... please check your tractography algorithm!" ; continue; } }//end for loop - - m_FiberPolyData->GetPointData()->AddArray(colorsT); - m_currentColorCoding = (char*) COLORCODING_ORIENTATION_BASED; - m_isModified = true; + + /*========================= + - this is more relevant for renderer than for fiberbundleX datastructure + - think about sourcing this to a explicit method which coordinates colorcoding */ + this->SetColorCoding(COLORCODING_ORIENTATION_BASED); + // =========================== //mini test, shall be ported to MITK TESTINGS! - if (colorsT->GetSize() != numOfPoints*componentSize) { + if (colorsT->GetSize() != numOfPoints*componentSize) MITK_INFO << "ALLOCATION ERROR IN INITIATING COLOR ARRAY"; + + +} + +void mitk::FiberBundleX::DoColorCodingFAbased() +{ + if(m_FiberPolyData->GetPointData()->HasArray(FA_VALUE_ARRAY) != 1 ) + return; + + this->SetColorCoding(FA_VALUE_ARRAY); + MITK_INFO << "FBX: done CC FA based"; + this->DoGenerateFiberIds(); +} + +void mitk::FiberBundleX::DoUseFAasColorOpacity() +{ + if(m_FiberPolyData->GetPointData()->HasArray(FA_VALUE_ARRAY) != 1 ) + return; + + if(m_FiberPolyData->GetPointData()->HasArray(COLORCODING_ORIENTATION_BASED) != 1 ) + return; + + vtkDoubleArray* FAValArray = (vtkDoubleArray*) m_FiberPolyData->GetPointData()->GetArray(FA_VALUE_ARRAY); + vtkUnsignedCharArray* ColorArray = dynamic_cast (m_FiberPolyData->GetPointData()->GetArray(COLORCODING_ORIENTATION_BASED)); + + for(long i=0; iGetNumberOfTuples(); i++) { + double faValue = FAValArray->GetValue(i); + faValue = faValue * 255.0; + ColorArray->SetComponent(i,3, (unsigned char) faValue ); + } + + this->SetColorCoding(COLORCODING_ORIENTATION_BASED); + MITK_INFO << "FBX: done CC OPACITY"; + this->DoGenerateFiberIds(); +} + +void mitk::FiberBundleX::ResetFiberColorOpacity() { + vtkUnsignedCharArray* ColorArray = dynamic_cast (m_FiberPolyData->GetPointData()->GetArray(COLORCODING_ORIENTATION_BASED)); + for(long i=0; iGetNumberOfTuples(); i++) { + ColorArray->SetComponent(i,3, 255.0 ); + } +} + +void mitk::FiberBundleX::SetFAMap(mitk::Image::Pointer FAimage) +{ + MITK_INFO << "SetFAMap"; + vtkSmartPointer faValues = vtkDoubleArray::New(); + faValues->SetName(FA_VALUE_ARRAY); + faValues->Allocate(m_FiberPolyData->GetNumberOfPoints()); + // MITK_INFO << faValues->GetNumberOfTuples(); + // MITK_INFO << faValues->GetSize(); + + faValues->SetNumberOfValues(m_FiberPolyData->GetNumberOfPoints()); + // MITK_INFO << faValues->GetNumberOfTuples(); + // MITK_INFO << faValues->GetSize(); + + vtkPoints* pointSet = m_FiberPolyData->GetPoints(); + for(long i=0; iGetNumberOfPoints(); ++i) + { + Point3D px; + px[0] = pointSet->GetPoint(i)[0]; + px[1] = pointSet->GetPoint(i)[1]; + px[2] = pointSet->GetPoint(i)[2]; + double faPixelValue = FAimage->GetPixelValueByWorldCoordinate(px) * 0.01; + // faValues->InsertNextTuple1(faPixelValue); + faValues->InsertValue(i, faPixelValue); + // MITK_INFO << faPixelValue; + // MITK_INFO << faValues->GetValue(i); + } + m_FiberPolyData->GetPointData()->AddArray(faValues); + this->DoGenerateFiberIds(); - //===== clean memory ===== - colorsT->Delete(); + if(m_FiberPolyData->GetPointData()->HasArray(FA_VALUE_ARRAY)) + MITK_INFO << "FA VALUE ARRAY SET"; - //======================== + // vtkDoubleArray* valueArray = (vtkDoubleArray*) m_FiberPolyData->GetPointData()->GetArray(FA_VALUE_ARRAY); + // for(long i=0; iGetNumberOfPoints(); i++) + // { + // MITK_INFO << "value at pos "<< i << ": " << valueArray->GetValue(i); + // } } void mitk::FiberBundleX::DoGenerateFiberIds() { if (m_FiberPolyData == NULL) return; - // for (int i=0; i<10000000; ++i) - // { - // if(i%500 == 0) - // MITK_INFO << i; - // } - // MITK_INFO << "Generating Fiber Ids"; vtkSmartPointer idFiberFilter = vtkSmartPointer::New(); idFiberFilter->SetInput(m_FiberPolyData); idFiberFilter->CellIdsOn(); // idFiberFilter->PointIdsOn(); // point id's are not needed idFiberFilter->SetIdsArrayName(FIBER_ID_ARRAY); idFiberFilter->FieldDataOn(); idFiberFilter->Update(); m_FiberIdDataSet = idFiberFilter->GetOutput(); MITK_INFO << "Generating Fiber Ids...[done] | " << m_FiberIdDataSet->GetNumberOfCells(); } -void mitk::FiberBundleX::UpdateFiberGeometry() +//========================== +std::vector mitk::FiberBundleX::DoExtractFiberIds(mitk::PlanarFigure::Pointer pf) { + MITK_INFO << "Extracting fibers!"; + // vector which is returned, contains all extracted FiberIds + std::vector FibersInROI; + + /* Handle type of planarfigure */ + // if incoming pf is a pfc + mitk::PlanarFigureComposite::Pointer pfcomp= dynamic_cast(pf.GetPointer()); + if (!pfcomp.IsNull()) { + // process requested boolean operation of PFC + switch (pfcomp->getOperationType()) { + case 0: + { + MITK_INFO << "AND PROCESSING"; + //AND + //temporarly store results of the child in this vector, we need that to accumulate the + std::vector childResults = this->DoExtractFiberIds(pfcomp->getChildAt(0)); + MITK_INFO << "first roi got fibers in ROI: " << childResults.size(); + MITK_INFO << "sorting..."; + std::sort(childResults.begin(), childResults.end()); + MITK_INFO << "sorting done"; + std::vector AND_Assamblage(childResults.size()); + //std::vector AND_Assamblage; + fill(AND_Assamblage.begin(), AND_Assamblage.end(), -1); + //AND_Assamblage.reserve(childResults.size()); //max size AND can reach anyway + + std::vector::iterator it; + for (int i=1; igetNumberOfChildren(); ++i) + { + std::vector tmpChild = this->DoExtractFiberIds(pfcomp->getChildAt(i)); + MITK_INFO << "ROI " << i << " has fibers in ROI: " << tmpChild.size(); + sort(tmpChild.begin(), tmpChild.end()); + + it = std::set_intersection(childResults.begin(), childResults.end(), + tmpChild.begin(), tmpChild.end(), + AND_Assamblage.begin() ); + } + + MITK_INFO << "resize Vector"; + long i=0; + while (i < AND_Assamblage.size() && AND_Assamblage[i] != -1){ //-1 represents a placeholder in the array + ++i; + } + AND_Assamblage.resize(i); + + MITK_INFO << "returning AND vector, size: " << AND_Assamblage.size(); + return AND_Assamblage; + // break; + + } + case 1: + { + //OR + std::vector OR_Assamblage = this->DoExtractFiberIds(pfcomp->getChildAt(0)); + std::vector::iterator it; + MITK_INFO << OR_Assamblage.size(); + + for (int i=1; igetNumberOfChildren(); ++i) { + it = OR_Assamblage.end(); + std::vector tmpChild = this->DoExtractFiberIds(pfcomp->getChildAt(i)); + OR_Assamblage.insert(it, tmpChild.begin(), tmpChild.end()); + MITK_INFO << "ROI " << i << " has fibers in ROI: " << tmpChild.size() << " OR Assamblage: " << OR_Assamblage.size(); + } + + sort(OR_Assamblage.begin(), OR_Assamblage.end()); + it = unique(OR_Assamblage.begin(), OR_Assamblage.end()); + OR_Assamblage.resize( it - OR_Assamblage.begin() ); + MITK_INFO << "returning OR vector, size: " << OR_Assamblage.size(); + + return OR_Assamblage; + } + case 2: + { + //NOT + //get IDs of all fibers + std::vector childResults; + childResults.reserve(this->GetNumFibers()); + vtkSmartPointer idSet = m_FiberIdDataSet->GetCellData()->GetArray(FIBER_ID_ARRAY); + MITK_INFO << "m_NumOfFib: " << this->GetNumFibers() << " cellIdNum: " << idSet->GetNumberOfTuples(); + for(long i=0; iGetNumFibers(); i++) + { + MITK_INFO << "i: " << i << " idset: " << idSet->GetTuple(i)[0]; + childResults.push_back(idSet->GetTuple(i)[0]); + } + + std::sort(childResults.begin(), childResults.end()); + std::vector NOT_Assamblage(childResults.size()); + //fill it with -1, otherwise 0 will be stored and 0 can also be an ID of fiber! + fill(NOT_Assamblage.begin(), NOT_Assamblage.end(), -1); + std::vector::iterator it; + + for (long i=0; igetNumberOfChildren(); ++i) + { + std::vector tmpChild = DoExtractFiberIds(pfcomp->getChildAt(i)); + sort(tmpChild.begin(), tmpChild.end()); + + it = std::set_difference(childResults.begin(), childResults.end(), + tmpChild.begin(), tmpChild.end(), + NOT_Assamblage.begin() ); + + } + + MITK_INFO << "resize Vector"; + long i=0; + while (NOT_Assamblage[i] != -1){ //-1 represents a placeholder in the array + ++i; + } + NOT_Assamblage.resize(i); + + return NOT_Assamblage; + } + default: + MITK_INFO << "we have an UNDEFINED composition... ERROR" ; + break; + + } + } else + { + + mitk::Geometry2D::ConstPointer pfgeometry = pf->GetGeometry2D(); + const mitk::PlaneGeometry* planeGeometry = dynamic_cast (pfgeometry.GetPointer()); + Vector3D planeNormal = planeGeometry->GetNormal(); + planeNormal.Normalize(); + Point3D planeOrigin = planeGeometry->GetOrigin(); + + MITK_INFO << "planeOrigin: " << planeOrigin[0] << " | " << planeOrigin[1] << " | " << planeOrigin[2] << endl; + MITK_INFO << "planeNormal: " << planeNormal[0] << " | " << planeNormal[1] << " | " << planeNormal[2] << endl; + + + /* init necessary vectors hosting pointIds and FiberIds */ + // contains all pointIds which are crossing the cutting plane + std::vector PointsOnPlane; + + // based on PointsOnPlane, all ROI relevant point IDs are stored here + std::vector PointsInROI; + + + /* Define cutting plane by ROI (PlanarFigure) */ + vtkSmartPointer plane = vtkSmartPointer::New(); + plane->SetOrigin(planeOrigin[0],planeOrigin[1],planeOrigin[2]); + plane->SetNormal(planeNormal[0],planeNormal[1],planeNormal[2]); + + //same plane but opposite normal direction. so point cloud will be reduced -> better performance + // vtkSmartPointer planeR = vtkSmartPointer::New(); + + //define new origin along the normal but close to the original one + // OriginNew = OriginOld + 1*Normal + // Vector3D extendedNormal; + // int multiplyFactor = 1; + // extendedNormal[0] = planeNormal[0] * multiplyFactor; + // extendedNormal[1] = planeNormal[1] * multiplyFactor; + // extendedNormal[2] = planeNormal[2] * multiplyFactor; + // Point3D RplaneOrigin = planeOrigin - extendedNormal; + // planeR->SetOrigin(RplaneOrigin[0],RplaneOrigin[1],RplaneOrigin[2]); + // planeR->SetNormal(-planeNormal[0],-planeNormal[1],-planeNormal[2]); + // MITK_INFO << "RPlaneOrigin: " << RplaneOrigin[0] << " | " << RplaneOrigin[1] + // << " | " << RplaneOrigin[2]; + + /* get all points/fibers cutting the plane */ + MITK_INFO << "start clipping"; + vtkSmartPointer clipper = vtkSmartPointer::New(); + clipper->SetInput(m_FiberIdDataSet); + clipper->SetClipFunction(plane); + clipper->GenerateClipScalarsOn(); + clipper->GenerateClippedOutputOn(); + vtkSmartPointer clipperout = clipper->GetClippedOutput(); + MITK_INFO << "end clipping"; + + /* for some reason clipperoutput is not initialized for futher processing + * so far only writing out clipped polydata provides requested + */ + // MITK_INFO << "writing clipper output"; + // vtkSmartPointer writerC = vtkSmartPointer::New(); + // writerC->SetInput(clipperout1); + // writerC->SetFileName("/vtkOutput/Clipping.vtk"); + // writerC->SetFileTypeToASCII(); + // writerC->Write(); + // MITK_INFO << "writing done"; + + MITK_INFO << "init and update clipperoutput"; + clipperout->GetPointData()->Initialize(); + clipperout->Update(); + MITK_INFO << "init and update clipperoutput completed"; + + // MITK_INFO << "start clippingRecursive"; + // vtkSmartPointer Rclipper = vtkSmartPointer::New(); + // Rclipper->SetInput(clipperout1); + // Rclipper->SetClipFunction(planeR); + // Rclipper->GenerateClipScalarsOn(); + // Rclipper->GenerateClippedOutputOn(); + // vtkSmartPointer clipperout = Rclipper->GetClippedOutput(); + // MITK_INFO << "end clipping recursive"; + + // MITK_INFO << "writing clipper output 2"; + // vtkSmartPointer writerC1 = vtkSmartPointer::New(); + // writerC1->SetInput(clipperout); + // writerC1->SetFileName("/vtkOutput/RClipping.vtk"); + // writerC1->SetFileTypeToASCII(); + // writerC1->Write(); + // MITK_INFO << "init and update clipperoutput"; + // clipperout->GetPointData()->Initialize(); + // clipperout->Update(); + // MITK_INFO << "init and update clipperoutput completed"; + + MITK_INFO << "STEP 1: find all points which have distance 0 to the given plane"; + /*======STEP 1====== + * extract all points, which are crossing the plane */ + // Scalar values describe the distance between each remaining point to the given plane. Values sorted by point index + vtkSmartPointer distanceList = clipperout->GetPointData()->GetScalars(); + vtkIdType sizeOfList = distanceList->GetNumberOfTuples(); + PointsOnPlane.reserve(sizeOfList); /* use reserve for high-performant push_back, no hidden copy procedures are processed then! + * size of list can be optimized by reducing allocation, but be aware of iterator and vector size*/ + + for (int i=0; iGetTuple(i); + //std::cout << "distance of point " << i << " : " << distance[0] << std::endl; + + // check if point is on plane. + // 0.01 due to some approximation errors when calculating distance + if (distance[0] >= -0.01 && distance[0] <= 0.01) + { + //std::cout << "adding " << i << endl; + PointsOnPlane.push_back(i); //push back in combination with reserve is fastest way to fill vector with various values + + } + + } + + // DEBUG print out all interesting points, stop where array starts with value -1. after -1 no more interesting idx are set! + // std::vector::iterator rit = PointsOnPlane.begin(); + // while (rit != PointsOnPlane.end() ) { + // std::cout << "interesting point: " << *rit << " coord: " << clipperout->GetPoint(*rit)[0] << " | " << clipperout->GetPoint(*rit)[1] << " | " << clipperout->GetPoint(*rit)[2] << endl; + // rit++; + // } + + + MITK_INFO << "Num Of points on plane: " << PointsOnPlane.size(); + + MITK_INFO << "Step 2: extract Interesting points with respect to given extraction planarFigure"; + + PointsInROI.reserve(PointsOnPlane.size()); + /*=======STEP 2===== + * extract ROI relevant pointIds */ + + mitk::PlanarCircle::Pointer circleName = mitk::PlanarCircle::New(); + mitk::PlanarPolygon::Pointer polyName = mitk::PlanarPolygon::New(); + if (pf->GetNameOfClass() == circleName->GetNameOfClass() ) + { + + //calculate circle radius + mitk::Point3D V1w = pf->GetWorldControlPoint(0); //centerPoint + mitk::Point3D V2w = pf->GetWorldControlPoint(1); //radiusPoint + + //calculate distance between those 2 and + double distPF; + distPF = sqrt((double) (V2w[0] - V1w[0]) * (V2w[0] - V1w[0]) + + (V2w[1] - V1w[1]) * (V2w[1] - V1w[1]) + + (V2w[2] - V1w[2]) * (V2w[2] - V1w[2])); + + //MITK_INFO << "Circle Radius: " << distPF; + + for (int i=0; iGetPoint(PointsOnPlane[i])[0] << " - " << V1w[0]; + // MITK_INFO << clipperout->GetPoint(PointsOnPlane[i])[1] << " - " << V1w[1]; + // MITK_INFO << clipperout->GetPoint(PointsOnPlane[i])[2] << " - " << V1w[2]; + + //distance between circle radius and given point + double XdistPnt = sqrt((double) (clipperout->GetPoint(PointsOnPlane[i])[0] - V1w[0]) * (clipperout->GetPoint(PointsOnPlane[i])[0] - V1w[0]) + + (clipperout->GetPoint(PointsOnPlane[i])[1] - V1w[1]) * (clipperout->GetPoint(PointsOnPlane[i])[1] - V1w[1]) + + (clipperout->GetPoint(PointsOnPlane[i])[2] - V1w[2]) * (clipperout->GetPoint(PointsOnPlane[i])[2] - V1w[2])) ; + + // MITK_INFO << "PntDistance to Radius: " << XdistPnt; + if( XdistPnt <= distPF) + { + // MITK_INFO << "point in Circle"; + PointsInROI.push_back(PointsOnPlane[i]); + } + + }//end for(i) + // MITK_INFO << "Points inside circle radius: " << PointsInROI.size(); + } + + MITK_INFO << "Step3: Identify fibers"; + + /*======STEP 3======= + * identify fiberIds for points in ROI */ + + // we need to access the fiberId Array, so make sure that this array is available + if (!clipperout->GetCellData()->HasArray(FIBER_ID_ARRAY)) + { + MITK_INFO << "ERROR: FiberID array does not exist, no correlation between points and fiberIds possible! Make sure calling GenerateFiberIds()"; + return FibersInROI; // FibersInRoi is empty then + } + + // prepare a structure where each point id is represented as an indexId. + // vector looks like: | pntId | fiberIdx | + std::vector< long > pointindexFiberMap; + + // walk through the whole subline section and create an vector sorted by point index + vtkCellArray *clipperlines = clipperout->GetLines(); + clipperlines->InitTraversal(); + long numOfLineCells = clipperlines->GetNumberOfCells(); + long numofClippedPoints = clipperout->GetNumberOfPoints(); + pointindexFiberMap.reserve(numofClippedPoints); + + + //prepare resulting vector + FibersInROI.reserve(PointsInROI.size()); + + MITK_INFO << "\n===== Pointindex based structure initialized ======\n"; + + // go through resulting "sub"lines which are stored as cells, "i" corresponds to current line id. + for (int i=0, ic=0 ; iGetCell(ic, npts, pts); + + // go through point ids in hosting subline, "j" corresponds to current pointindex in current line i. eg. idx[0]=45; idx[1]=46 + for (long j=0; jGetCellData()->GetArray(FIBER_ID_ARRAY)->GetTuple(i)[0] << " to pointId: " << pts[j]; + pointindexFiberMap[ pts[j] ] = clipperout->GetCellData()->GetArray(FIBER_ID_ARRAY)->GetTuple(i)[0]; + // MITK_INFO << "in array: " << pointindexFiberMap[ pts[j] ]; + } + + } + + MITK_INFO << "\n===== Pointindex based structure finalized ======\n"; + + // get all Points in ROI with according fiberID + for (long k = 0; k < PointsInROI.size(); k++) + { + //MITK_INFO << "point " << PointsInROI[k] << " belongs to fiber " << pointindexFiberMap[ PointsInROI[k] ]; + FibersInROI.push_back(pointindexFiberMap[ PointsInROI[k] ]); + } + + } + + // detecting fiberId duplicates + MITK_INFO << "check for duplicates"; + + sort(FibersInROI.begin(), FibersInROI.end()); + bool hasDuplicats = false; + for(long i=0; i::iterator it; + it = unique (FibersInROI.begin(), FibersInROI.end()); + FibersInROI.resize( it - FibersInROI.begin() ); + } + + return FibersInROI; +} +void mitk::FiberBundleX::UpdateFiberGeometry() +{ + if (m_NumFibers<=0) + { + mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); + geometry->SetImageGeometry(true); + float b[] = {0, 1, 0, 1, 0, 1}; + geometry->SetFloatBounds(b); + SetGeometry(geometry); + return; + } float min = itk::NumericTraits::min(); float max = itk::NumericTraits::max(); float b[] = {max, min, max, min, max, min}; vtkCellArray* cells = m_FiberPolyData->GetLines(); cells->InitTraversal(); for (int i=0; iGetNumberOfCells(); i++) { - vtkCell* cell = m_FiberPolyData->GetCell(i); int p = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); for (int j=0; jGetPoint(j, p); if (p[0]b[1]) b[1]=p[0]; if (p[1]b[3]) b[3]=p[1]; if (p[2]b[5]) b[5]=p[2]; - - } - } - // provide some buffer space at borders - - for(int i=0; i<=4; i+=2){ + // provide some border margin + for(int i=0; i<=4; i+=2) b[i] -=10; - } - - for(int i=1; i<=5; i+=2){ + for(int i=1; i<=5; i+=2) b[i] +=10; - } mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); geometry->SetImageGeometry(true); geometry->SetFloatBounds(b); this->SetGeometry(geometry); +} +QStringList mitk::FiberBundleX::GetAvailableColorCodings() +{ + QStringList availableColorCodings; + int numColors = m_FiberPolyData->GetPointData()->GetNumberOfArrays(); + for(int i=0; iGetPointData()->GetArrayName(i)); + } + //this controlstructure shall be implemented by the calling method + if (availableColorCodings.isEmpty()) + MITK_INFO << "no colorcodings available in fiberbundleX"; + // for(int i=0; im_currentColorCoding = (char*) COLORCODING_ORIENTATION_BASED; + + } else if( strcmp (FA_VALUE_ARRAY,requestedColorCoding) == 0 ) { + this->m_currentColorCoding = (char*) FA_VALUE_ARRAY; + + } else if( strcmp (COLORCODING_CUSTOM,requestedColorCoding) == 0 ) { + this->m_currentColorCoding = (char*) COLORCODING_CUSTOM; + + } else { + MITK_INFO << "FIBERBUNDLE X: UNKNOWN COLORCODING in FIBERBUNDLEX Datastructure"; + this->m_currentColorCoding = (char*) COLORCODING_CUSTOM; //will cause blank colorcoding of fibers + } } -void mitk::FiberBundleX::setFBXModificationDone() + + +void mitk::FiberBundleX::ResampleFibers() { - m_isModified = false; + mitk::Geometry3D::Pointer geometry = GetGeometry(); + mitk::Vector3D spacing = geometry->GetSpacing(); + + float minSpacing = 1; + if(spacing[0] newPoly = vtkSmartPointer::New(); + vtkSmartPointer newCellArray = vtkSmartPointer::New(); + vtkSmartPointer newPoints = vtkSmartPointer::New(); + + vtkSmartPointer vLines = m_FiberPolyData->GetLines(); + vLines->InitTraversal(); + int numberOfLines = m_NumFibers; + + for (int i=0; iGetNextCell ( numPoints, points ); + + vtkSmartPointer container = vtkSmartPointer::New(); + + double* point = m_FiberPolyData->GetPoint(points[0]); + vtkIdType pointId = newPoints->InsertNextPoint(point); + container->GetPointIds()->InsertNextId(pointId); + + float dtau = 0; + int cur_p = 1; + itk::Vector dR; + float normdR = 0; + + for (;;) + { + while (dtau <= len && cur_p < numPoints) + { + itk::Vector v1; + point = m_FiberPolyData->GetPoint(points[cur_p-1]); + v1[0] = point[0]; + v1[1] = point[1]; + v1[2] = point[2]; + itk::Vector v2; + point = m_FiberPolyData->GetPoint(points[cur_p]); + v2[0] = point[0]; + v2[1] = point[1]; + v2[2] = point[2]; + + dR = v2 - v1; + normdR = std::sqrt(dR.GetSquaredNorm()); + dtau += normdR; + cur_p++; + } + + if (dtau >= len) + { + itk::Vector v1; + point = m_FiberPolyData->GetPoint(points[cur_p-1]); + v1[0] = point[0]; + v1[1] = point[1]; + v1[2] = point[2]; + + itk::Vector v2 = v1 - dR*( (dtau-len)/normdR ); + pointId = newPoints->InsertNextPoint(v2.GetDataPointer()); + container->GetPointIds()->InsertNextId(pointId); + } + else + { + point = m_FiberPolyData->GetPoint(points[numPoints-1]); + pointId = newPoints->InsertNextPoint(point); + container->GetPointIds()->InsertNextId(pointId); + break; + } + dtau = dtau-len; + } + + newCellArray->InsertNextCell(container); + } + + newPoly->SetPoints(newPoints); + newPoly->SetLines(newCellArray); + m_FiberPolyData = newPoly; + UpdateFiberGeometry(); +} + + /* ESSENTIAL IMPLEMENTATION OF SUPERCLASS METHODS */ void mitk::FiberBundleX::UpdateOutputInformation() { } void mitk::FiberBundleX::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::FiberBundleX::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::FiberBundleX::VerifyRequestedRegion() { return true; } void mitk::FiberBundleX::SetRequestedRegion( itk::DataObject *data ) { } diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.cpp.orig b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.cpp.orig new file mode 100644 index 0000000000..2a98af7d51 --- /dev/null +++ b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.cpp.orig @@ -0,0 +1,922 @@ +/*========================================================================= + + Program: Medical Imaging & Interaction Toolkit + Language: C++ + Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $ + Version: $Revision: 21975 $ + + Copyright (c) German Cancer Research Center, Division of Medical and + Biological Informatics. All rights reserved. + See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. + + =========================================================================*/ + + +#include "mitkFiberBundleX.h" + +#include +#include +#include + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +const char* mitk::FiberBundleX::COLORCODING_ORIENTATION_BASED = "Color_Orient"; +const char* mitk::FiberBundleX::COLORCODING_FA_BASED = "Color_FA"; +const char* mitk::FiberBundleX::FIBER_ID_ARRAY = "Fiber_IDs"; + +<<<<<<< HEAD + + + +mitk::FiberBundleX::FiberBundleX(vtkSmartPointer fiberPolyData ) + : m_currentColorCoding(NULL) + , m_isModified(false) +{ + //generate geometry of passed polydata + if (fiberPolyData == NULL) + this->m_FiberPolyData = vtkSmartPointer::New(); + else + this->m_FiberPolyData = fiberPolyData; + + this->UpdateFiberGeometry(); +} +======= +mitk::FiberBundleX::FiberBundleX( vtkPolyData* fiberPolyData ) + : m_currentColorCoding(NULL) + , m_isModified(false) + , m_NumFibers(0) +{ + if (fiberPolyData == NULL) + m_FiberPolyData = vtkSmartPointer::New(); + else + m_FiberPolyData = fiberPolyData; + + m_NumFibers = m_FiberPolyData->GetNumberOfLines(); +>>>>>>> bug-10211-FiberProcessingX + + UpdateFiberGeometry(); +} + +mitk::FiberBundleX::~FiberBundleX() +{ + +} + +mitk::FiberBundleX::Pointer mitk::FiberBundleX::GetDeepCopy() +{ + mitk::FiberBundleX::Pointer newFib = mitk::FiberBundleX::New(); + +// newFib->m_FiberIdDataSet = vtkSmartPointer::New(); +// newFib->m_FiberIdDataSet->DeepCopy(m_FiberIdDataSet); + newFib->m_FiberPolyData = vtkSmartPointer::New(); + newFib->m_FiberPolyData->DeepCopy(m_FiberPolyData); + newFib->SetColorCoding(m_currentColorCoding); + newFib->m_isModified = m_isModified; + newFib->m_NumFibers = m_NumFibers; + newFib->UpdateFiberGeometry(); + + return newFib; +} + +// merge two fiber bundles +mitk::FiberBundleX::Pointer mitk::FiberBundleX::operator+(mitk::FiberBundleX* fib) +{ + + vtkSmartPointer vNewPolyData = vtkSmartPointer::New(); + vtkSmartPointer vNewLines = vtkSmartPointer::New(); + vtkSmartPointer vNewPoints = vtkSmartPointer::New(); + + vtkSmartPointer vLines = m_FiberPolyData->GetLines(); + vLines->InitTraversal(); + + // add current fiber bundle + int numFibers = GetNumFibers(); + for( int i=0; iGetNextCell ( numPoints, points ); + + vtkSmartPointer container = vtkSmartPointer::New(); + for( int j=0; jInsertNextPoint(m_FiberPolyData->GetPoint(points[j])); + container->GetPointIds()->InsertNextId(id); + } + vNewLines->InsertNextCell(container); + } + + vLines = fib->m_FiberPolyData->GetLines(); + vLines->InitTraversal(); + + // add new fiber bundle + numFibers = fib->GetNumFibers(); + for( int i=0; iGetNextCell ( numPoints, points ); + + vtkSmartPointer container = vtkSmartPointer::New(); + for( int j=0; jInsertNextPoint(fib->m_FiberPolyData->GetPoint(points[j])); + container->GetPointIds()->InsertNextId(id); + } + vNewLines->InsertNextCell(container); + } + + // initialize polydata + vNewPolyData->SetPoints(vNewPoints); + vNewPolyData->SetLines(vNewLines); + + // initialize fiber bundle + mitk::FiberBundleX::Pointer newFib = mitk::FiberBundleX::New(vNewPolyData); + return newFib; +} + +// subtract two fiber bundles +mitk::FiberBundleX::Pointer mitk::FiberBundleX::operator-(mitk::FiberBundleX* fib) +{ + + vtkSmartPointer vNewPolyData = vtkSmartPointer::New(); + vtkSmartPointer vNewLines = vtkSmartPointer::New(); + vtkSmartPointer vNewPoints = vtkSmartPointer::New(); + + vtkSmartPointer vLines = m_FiberPolyData->GetLines(); + vLines->InitTraversal(); + + // iterate over current fibers + int numFibers = GetNumFibers(); + for( int i=0; iGetNextCell ( numPoints, points ); + + vtkSmartPointer vLines2 = fib->m_FiberPolyData->GetLines(); + vLines2->InitTraversal(); + int numFibers2 = fib->GetNumFibers(); + bool contained = false; + for( int i2=0; i2GetNextCell ( numPoints2, points2 ); + + // check endpoints + itk::Point point_start = GetItkPoint(m_FiberPolyData->GetPoint(points[0])); + itk::Point point_end = GetItkPoint(m_FiberPolyData->GetPoint(points[numPoints-1])); + itk::Point point2_start = GetItkPoint(fib->m_FiberPolyData->GetPoint(points2[0])); + itk::Point point2_end = GetItkPoint(fib->m_FiberPolyData->GetPoint(points2[numPoints2-1])); + + if (point_start.SquaredEuclideanDistanceTo(point2_start)<=mitk::eps && point_end.SquaredEuclideanDistanceTo(point2_end)<=mitk::eps || + point_start.SquaredEuclideanDistanceTo(point2_end)<=mitk::eps && point_end.SquaredEuclideanDistanceTo(point2_start)<=mitk::eps) + { + // further checking ??? + contained = true; + } + } + + // add to result because fiber is not subtracted + if (!contained) + { + vtkSmartPointer container = vtkSmartPointer::New(); + for( int j=0; jInsertNextPoint(m_FiberPolyData->GetPoint(points[j])); + container->GetPointIds()->InsertNextId(id); + } + vNewLines->InsertNextCell(container); + } + } + + // initialize polydata + vNewPolyData->SetPoints(vNewPoints); + vNewPolyData->SetLines(vNewLines); + + // initialize fiber bundle + mitk::FiberBundleX::Pointer newFib = mitk::FiberBundleX::New(vNewPolyData); + return newFib; +} + +itk::Point mitk::FiberBundleX::GetItkPoint(double point[3]) +{ + itk::Point itkPoint; + itkPoint[0] = point[0]; + itkPoint[1] = point[1]; + itkPoint[2] = point[2]; + return itkPoint; +} + +/* + * set polydata (additional flag to recompute fiber geometry, default = true) + */ +void mitk::FiberBundleX::SetFiberPolyData(vtkSmartPointer fiberPD, bool updateGeometry) +{ + if (fiberPD == NULL) + this->m_FiberPolyData = vtkSmartPointer::New(); + else + this->m_FiberPolyData = fiberPD; + +<<<<<<< HEAD + m_isModified = true; +======= + if (updateGeometry) + UpdateFiberGeometry(); + + m_NumFibers = m_FiberPolyData->GetNumberOfLines(); + + m_isModified = true; +>>>>>>> bug-10211-FiberProcessingX +} + +/* + * return vtkPolyData + */ +vtkSmartPointer mitk::FiberBundleX::GetFiberPolyData() +{ + return m_FiberPolyData; +} + +void mitk::FiberBundleX::DoColorCodingOrientationbased() +{ + //===== FOR WRITING A TEST ======================== + // colorT size == tupelComponents * tupelElements + // compare color results + // to cover this code 100% also polydata needed, where colorarray already exists + // + one fiber with exactly 1 point + // + one fiber with 0 points + //================================================= + + + /* make sure that processing colorcoding is only called when necessary */ + if ( m_FiberPolyData->GetPointData()->HasArray(COLORCODING_ORIENTATION_BASED) && + m_FiberPolyData->GetNumberOfPoints() == + m_FiberPolyData->GetPointData()->GetArray(COLORCODING_ORIENTATION_BASED)->GetNumberOfTuples() ) + { + // fiberstructure is already colorcoded + MITK_INFO << " NO NEED TO REGENERATE COLORCODING! " ; + return; + } + + /* Finally, execute color calculation */ + vtkPoints* extrPoints = m_FiberPolyData->GetPoints(); + int numOfPoints = extrPoints->GetNumberOfPoints(); + + //colors and alpha value for each single point, RGBA = 4 components + unsigned char rgba[4] = {0,0,0,0}; + int componentSize = sizeof(rgba); + + vtkUnsignedCharArray * colorsT = vtkUnsignedCharArray::New(); + colorsT->Allocate(numOfPoints * componentSize); + colorsT->SetNumberOfComponents(componentSize); + colorsT->SetName(COLORCODING_ORIENTATION_BASED); + + + + /* checkpoint: does polydata contain any fibers */ + int numOfFibers = m_FiberPolyData->GetNumberOfLines(); + if (numOfFibers < 1) { + MITK_INFO << "\n ========= Number of Fibers is 0 and below ========= \n"; + return; + } + + + /* extract single fibers of fiberBundle */ + vtkCellArray* fiberList = m_FiberPolyData->GetLines(); + fiberList->InitTraversal(); + for (int fi=0; fiGetNextCell(pointsPerFiber, idList); + + // MITK_INFO << "Fib#: " << fi << " of " << numOfFibers << " pnts in fiber: " << pointsPerFiber ; + + /* single fiber checkpoints: is number of points valid */ + if (pointsPerFiber > 1) + { + /* operate on points of single fiber */ + for (int i=0; i 0) + { + /* The color value of the current point is influenced by the previous point and next point. */ + vnl_vector_fixed< double, 3 > currentPntvtk(extrPoints->GetPoint(idList[i])[0], extrPoints->GetPoint(idList[i])[1],extrPoints->GetPoint(idList[i])[2]); + vnl_vector_fixed< double, 3 > nextPntvtk(extrPoints->GetPoint(idList[i+1])[0], extrPoints->GetPoint(idList[i+1])[1], extrPoints->GetPoint(idList[i+1])[2]); + vnl_vector_fixed< double, 3 > prevPntvtk(extrPoints->GetPoint(idList[i-1])[0], extrPoints->GetPoint(idList[i-1])[1], extrPoints->GetPoint(idList[i-1])[2]); + + vnl_vector_fixed< double, 3 > diff1; + diff1 = currentPntvtk - nextPntvtk; + + vnl_vector_fixed< double, 3 > diff2; + diff2 = currentPntvtk - prevPntvtk; + + vnl_vector_fixed< double, 3 > diff; + diff = (diff1 - diff2) / 2.0; + diff.normalize(); + + rgba[0] = (unsigned char) (255.0 * std::abs(diff[0])); + rgba[1] = (unsigned char) (255.0 * std::abs(diff[1])); + rgba[2] = (unsigned char) (255.0 * std::abs(diff[2])); + rgba[3] = (unsigned char) (255.0); + + + } else if (i==0) { + /* First point has no previous point, therefore only diff1 is taken */ + + vnl_vector_fixed< double, 3 > currentPntvtk(extrPoints->GetPoint(idList[i])[0], extrPoints->GetPoint(idList[i])[1],extrPoints->GetPoint(idList[i])[2]); + vnl_vector_fixed< double, 3 > nextPntvtk(extrPoints->GetPoint(idList[i+1])[0], extrPoints->GetPoint(idList[i+1])[1], extrPoints->GetPoint(idList[i+1])[2]); + + vnl_vector_fixed< double, 3 > diff1; + diff1 = currentPntvtk - nextPntvtk; + diff1.normalize(); + + rgba[0] = (unsigned char) (255.0 * std::abs(diff1[0])); + rgba[1] = (unsigned char) (255.0 * std::abs(diff1[1])); + rgba[2] = (unsigned char) (255.0 * std::abs(diff1[2])); + rgba[3] = (unsigned char) (255.0); + + + } else if (i==pointsPerFiber-1) { + /* Last point has no next point, therefore only diff2 is taken */ + vnl_vector_fixed< double, 3 > currentPntvtk(extrPoints->GetPoint(idList[i])[0], extrPoints->GetPoint(idList[i])[1],extrPoints->GetPoint(idList[i])[2]); + vnl_vector_fixed< double, 3 > prevPntvtk(extrPoints->GetPoint(idList[i-1])[0], extrPoints->GetPoint(idList[i-1])[1], extrPoints->GetPoint(idList[i-1])[2]); + + vnl_vector_fixed< double, 3 > diff2; + diff2 = currentPntvtk - prevPntvtk; + diff2.normalize(); + + rgba[0] = (unsigned char) (255.0 * std::abs(diff2[0])); + rgba[1] = (unsigned char) (255.0 * std::abs(diff2[1])); + rgba[2] = (unsigned char) (255.0 * std::abs(diff2[2])); + rgba[3] = (unsigned char) (255.0); + + } + + colorsT->InsertTupleValue(idList[i], rgba); + + } //end for loop + + } else if (pointsPerFiber == 1) { + /* a single point does not define a fiber (use vertex mechanisms instead */ + continue; + // colorsT->InsertTupleValue(0, rgba); + + } else { + MITK_INFO << "Fiber with 0 points detected... please check your tractography algorithm!" ; + continue; + + } + + + }//end for loop + + m_FiberPolyData->GetPointData()->AddArray(colorsT); + + /*========================= + - this is more relevant for renderer than for fiberbundleX datastructure + - think about sourcing this to a explicit method which coordinates colorcoding */ + this->SetColorCoding(COLORCODING_ORIENTATION_BASED); + m_isModified = true; + // =========================== + + //mini test, shall be ported to MITK TESTINGS! + if (colorsT->GetSize() != numOfPoints*componentSize) { + MITK_INFO << "ALLOCATION ERROR IN INITIATING COLOR ARRAY"; + } + +} + +void mitk::FiberBundleX::DoGenerateFiberIds() +{ + if (m_FiberPolyData == NULL) + return; + + // for (int i=0; i<10000000; ++i) + // { + // if(i%500 == 0) + // MITK_INFO << i; + // } + // MITK_INFO << "Generating Fiber Ids"; + vtkSmartPointer idFiberFilter = vtkSmartPointer::New(); + idFiberFilter->SetInput(m_FiberPolyData); + idFiberFilter->CellIdsOn(); + // idFiberFilter->PointIdsOn(); // point id's are not needed + idFiberFilter->SetIdsArrayName(FIBER_ID_ARRAY); + idFiberFilter->FieldDataOn(); + idFiberFilter->Update(); + + m_FiberIdDataSet = idFiberFilter->GetOutput(); + + MITK_INFO << "Generating Fiber Ids...[done] | " << m_FiberIdDataSet->GetNumberOfCells(); + +} + + +//temporarely include only +#include +//========================== +std::vector mitk::FiberBundleX::DoExtractFiberIds(mitk::PlanarFigure::Pointer pf) +{ + + MITK_INFO << "Extracting fiber!"; + /* Handle type of planarfigure */ + // if incoming pf is a pfc + mitk::PlanarFigureComposite::Pointer pfcomp= dynamic_cast(pf.GetPointer()); + if (!pfcomp.IsNull()) { + // process requested boolean operation of PFC + } else + { + + + + mitk::Geometry2D::ConstPointer pfgeometry = pf->GetGeometry2D(); + const mitk::PlaneGeometry* planeGeometry = dynamic_cast (pfgeometry.GetPointer()); + Vector3D planeNormal = planeGeometry->GetNormal(); + planeNormal.Normalize(); + Point3D planeOrigin = planeGeometry->GetOrigin(); + + MITK_INFO << "planeOrigin: " << planeOrigin[0] << " | " << planeOrigin[1] << " | " << planeOrigin[2] << endl; + MITK_INFO << "planeNormal: " << planeNormal[0] << " | " << planeNormal[1] << " | " << planeNormal[2] << endl; + + + /* init necessary vectors hosting pointIds and FiberIds */ + // contains all pointIds which are crossing the cutting plane + std::vector PointsOnPlane; + + // based on PointsOnPlane, all ROI relevant point IDs are stored here + std::vector PointsInROI; + + // vector which is returned, contains all extracted FiberIds + std::vector FibersInROI; + + + /* Define cutting plane by ROI (PlanarFigure) */ + vtkSmartPointer plane = vtkSmartPointer::New(); + plane->SetOrigin(planeOrigin[0],planeOrigin[1],planeOrigin[2]); + plane->SetNormal(planeNormal[0],planeNormal[1],planeNormal[2]); + + //same plane but opposite normal direction. so point cloud will be reduced -> better performance + vtkSmartPointer planeR = vtkSmartPointer::New(); + planeR->SetOrigin(10.0,5.0,0.0); + planeR->SetNormal(0.0,-1.0,0.0); + + + /* get all points/fibers cutting the plane */ + vtkSmartPointer clipper = vtkSmartPointer::New(); + clipper->SetInput(m_FiberIdDataSet); + clipper->SetClipFunction(plane); + clipper->GenerateClipScalarsOn(); + clipper->GenerateClippedOutputOn(); + vtkSmartPointer clipperout1 = clipper->GetClippedOutput(); + + /* for some reason clipperoutput is not initialized for futher processing + * so far only writing out clipped polydata provides requested + */ + vtkSmartPointer writerC = vtkSmartPointer::New(); + writerC->SetInput(clipperout1); + writerC->SetFileName("/vtkOutput/Cout1_FbId_clipLineId0+1+2-tests.vtk"); + writerC->SetFileTypeToASCII(); + writerC->Write(); + + + vtkSmartPointer Rclipper = vtkSmartPointer::New(); + Rclipper->SetInput(clipperout1); + Rclipper->SetClipFunction(planeR); + Rclipper->GenerateClipScalarsOn(); + Rclipper->GenerateClippedOutputOn(); + vtkSmartPointer clipperout = Rclipper->GetClippedOutput(); + + + vtkSmartPointer writerC1 = vtkSmartPointer::New(); + writerC1->SetInput(clipperout); + writerC1->SetFileName("/vtkOutput/FbId_clipLineId0+1+2-tests.vtk"); + writerC1->SetFileTypeToASCII(); + writerC1->Write(); + + + /*======STEP 1====== + * extract all points, which are crossing the plane */ + // Scalar values describe the distance between each remaining point to the given plane. Values sorted by point index + vtkSmartPointer distanceList = clipperout->GetPointData()->GetScalars(); + vtkIdType sizeOfList = distanceList->GetNumberOfTuples(); + PointsOnPlane.reserve(sizeOfList); /* use reserve for high-performant push_back, no hidden copy procedures are processed then! + * size of list can be optimized by reducing allocation, but be aware of iterator and vector size*/ + for (int i=0; iGetTuple(i); + std::cout << "distance of point " << i << " : " << distance[0] << std::endl; + + // check if point is on plane. + // 0.01 due to some approximation errors when calculating distance + if (distance[0] >= -0.01 && distance[0] <= 0.01) + { + std::cout << "adding " << i << endl; + PointsOnPlane.push_back(i); //push back in combination with reserve is fastest way to fill vector with various values + } + + } + + // DEBUG print out all interesting points, stop where array starts with value -1. after -1 no more interesting idx are set! + std::vector::iterator rit = PointsOnPlane.begin(); + while (rit != PointsOnPlane.end() ) { + std::cout << "interesting point: " << *rit << " coord: " << clipperout->GetPoint(*rit)[0] << " | " << clipperout->GetPoint(*rit)[1] << " | " << clipperout->GetPoint(*rit)[2] << endl; + rit++; + } + + + + + + /*=======STEP 2===== + * extract ROI relevant pointIds */ + //ToDo + + mitk::PlanarCircle::Pointer circleName = mitk::PlanarCircle::New(); + mitk::PlanarPolygon::Pointer polyName = mitk::PlanarPolygon::New(); + if (pf->GetNameOfClass() == circleName->GetNameOfClass() ) + { + + if( true /*point in ROI*/) + { + PointsInROI = PointsOnPlane; + } + } + + + + /*======STEP 3======= + * identify fiberIds for points in ROI */ + //prepare resulting vector + FibersInROI.reserve(PointsInROI.size()); + + vtkCellArray *clipperlines = clipperout->GetLines(); + clipperlines->InitTraversal(); + long numOfLineCells = clipperlines->GetNumberOfCells(); + + // go through resulting "sub"lines which are stored as cells, "i" corresponds to current line id. + for (int i=0, ic=0 ; iGetCell(ic, npts, pts); + + // go through point ids in hosting subline, "j" corresponds to current pointindex in current line i. + for (long j=0; jGetCellData()->HasArray("FB_IDs")) + { + int originalFibId = clipperout->GetCellData()->GetArray("FB_IDs")->GetTuple(i)[0]; + std::cout << "found pointid " << PointsInROI[k] << ": " << clipperout->GetPoint(PointsInROI[k])[0] << " | " << clipperout->GetPoint(PointsInROI[k])[1] << " | " << clipperout->GetPoint(PointsInROI[k])[2] << " in subline: " << i << " which belongs to fiber id: " << originalFibId << "\n" << endl; + + // do something to avoid duplicates + int oldFibInRoiSize = FibersInROI.size(); + if (oldFibInRoiSize != 0) { + + + for (int f=0; f::iterator finIt = FibersInROI.begin(); + while ( finIt != FibersInROI.end() ) + { + std::cout << *finIt << endl; + ++finIt; + } + std::cout << "=====================\n"; + + } +} + +void mitk::FiberBundleX::UpdateFiberGeometry() +{ +<<<<<<< HEAD + + + float min = itk::NumericTraits::min(); + float max = itk::NumericTraits::max(); + float b[] = {max, min, max, min, max, min}; + + vtkCellArray* cells = m_FiberPolyData->GetLines(); + cells->InitTraversal(); + for (int i=0; iGetNumberOfCells(); i++) +======= + if (m_NumFibers<=0) + { + mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); + geometry->SetImageGeometry(true); + float b[] = {0, 1, 0, 1, 0, 1}; + geometry->SetFloatBounds(b); + SetGeometry(geometry); + return; + } + float min = itk::NumericTraits::min(); + float max = itk::NumericTraits::max(); + float b[] = {max, min, max, min, max, min}; + + vtkCellArray* cells = m_FiberPolyData->GetLines(); + cells->InitTraversal(); + for (int i=0; iGetNumberOfCells(); i++) + { + vtkCell* cell = m_FiberPolyData->GetCell(i); + int p = cell->GetNumberOfPoints(); + vtkPoints* points = cell->GetPoints(); + for (int j=0; j>>>>>> bug-10211-FiberProcessingX + { + +<<<<<<< HEAD + vtkCell* cell = m_FiberPolyData->GetCell(i); + int p = cell->GetNumberOfPoints(); + vtkPoints* points = cell->GetPoints(); + for (int j=0; jGetPoint(j, p); + + if (p[0]b[1]) + b[1]=p[0]; + + if (p[1]b[3]) + b[3]=p[1]; + + if (p[2]b[5]) + b[5]=p[2]; + + + } + + } + + // provide some buffer space at borders + + for(int i=0; i<=4; i+=2){ + b[i] -=10; + } + + for(int i=1; i<=5; i+=2){ + b[i] +=10; + } + + mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); + geometry->SetImageGeometry(true); + geometry->SetFloatBounds(b); + this->SetGeometry(geometry); + +======= + if (p[2]b[5]) + b[5]=p[2]; + } + } + + // provide some border margin + for(int i=0; i<=4; i+=2) + b[i] -=10; + for(int i=1; i<=5; i+=2) + b[i] +=10; + + mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); + geometry->SetImageGeometry(true); + geometry->SetFloatBounds(b); + this->SetGeometry(geometry); +>>>>>>> bug-10211-FiberProcessingX +} + +QStringList mitk::FiberBundleX::GetAvailableColorCodings() +{ + QStringList availableColorCodings; + int numColors = m_FiberPolyData->GetPointData()->GetNumberOfArrays(); + for(int i=0; iGetPointData()->GetArrayName(i)); + } + + //this controlstructure shall be implemented by the calling method + if (availableColorCodings.isEmpty()) + MITK_INFO << "no colorcodings available in fiberbundleX"; + + // for(int i=0; im_currentColorCoding = (char*) COLORCODING_ORIENTATION_BASED; + this->m_isModified = true; + + } else if(strcmp (COLORCODING_FA_BASED,requestedColorCoding) == 0 ) { + this->m_currentColorCoding = (char*) COLORCODING_FA_BASED; + this->m_isModified = true; + } else { + MITK_INFO << "FIBERBUNDLE X: UNKNOWN COLORCODING in FIBERBUNDLEX Datastructure"; + this->m_currentColorCoding = "---"; //will cause blank colorcoding of fibers + this->m_isModified = true; + } +} + +bool mitk::FiberBundleX::isFiberBundleXModified() +{ + return m_isModified; +} +void mitk::FiberBundleX::setFBXModificationDone() +{ + m_isModified = false; +} + +void mitk::FiberBundleX::ResampleFibers() +{ + mitk::Geometry3D::Pointer geometry = GetGeometry(); + mitk::Vector3D spacing = geometry->GetSpacing(); + + float minSpacing = 1; + if(spacing[0] newPoly = vtkSmartPointer::New(); + vtkSmartPointer newCellArray = vtkSmartPointer::New(); + vtkSmartPointer newPoints = vtkSmartPointer::New(); + +<<<<<<< HEAD + vtkSmartPointer vLines = m_FiberPolyData->GetLines(); + vLines->InitTraversal(); + int numberOfLines = vLines->GetNumberOfCells(); +======= + vtkSmartPointer vLines = m_FiberPolyData->GetLines(); + vLines->InitTraversal(); + int numberOfLines = m_NumFibers; +>>>>>>> bug-10211-FiberProcessingX + + for (int i=0; iGetNextCell ( numPoints, points ); + + vtkSmartPointer container = vtkSmartPointer::New(); + + double* point = m_FiberPolyData->GetPoint(points[0]); + vtkIdType pointId = newPoints->InsertNextPoint(point); + container->GetPointIds()->InsertNextId(pointId); + + float dtau = 0; + int cur_p = 1; + itk::Vector dR; + float normdR = 0; + + for (;;) + { + while (dtau <= len && cur_p < numPoints) + { + itk::Vector v1; + point = m_FiberPolyData->GetPoint(points[cur_p-1]); + v1[0] = point[0]; + v1[1] = point[1]; + v1[2] = point[2]; + itk::Vector v2; + point = m_FiberPolyData->GetPoint(points[cur_p]); + v2[0] = point[0]; + v2[1] = point[1]; + v2[2] = point[2]; + + dR = v2 - v1; + normdR = std::sqrt(dR.GetSquaredNorm()); + dtau += normdR; + cur_p++; + } + + if (dtau >= len) + { + itk::Vector v1; + point = m_FiberPolyData->GetPoint(points[cur_p-1]); + v1[0] = point[0]; + v1[1] = point[1]; + v1[2] = point[2]; + + itk::Vector v2 = v1 - dR*( (dtau-len)/normdR ); + pointId = newPoints->InsertNextPoint(v2.GetDataPointer()); + container->GetPointIds()->InsertNextId(pointId); + } + else + { + point = m_FiberPolyData->GetPoint(points[numPoints-1]); + pointId = newPoints->InsertNextPoint(point); + container->GetPointIds()->InsertNextId(pointId); + break; + } + dtau = dtau-len; + } + + newCellArray->InsertNextCell(container); + } + + newPoly->SetPoints(newPoints); + newPoly->SetLines(newCellArray); + m_FiberPolyData = newPoly; + UpdateFiberGeometry(); +} + + +/* ESSENTIAL IMPLEMENTATION OF SUPERCLASS METHODS */ +void mitk::FiberBundleX::UpdateOutputInformation() +{ + +} +void mitk::FiberBundleX::SetRequestedRegionToLargestPossibleRegion() +{ + +} +bool mitk::FiberBundleX::RequestedRegionIsOutsideOfTheBufferedRegion() +{ + return false; +} +bool mitk::FiberBundleX::VerifyRequestedRegion() +{ + return true; +} +void mitk::FiberBundleX::SetRequestedRegion( itk::DataObject *data ) +{ + +} diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.h b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.h index 27e73f62c8..eaed71e733 100644 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.h +++ b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleX.h @@ -1,125 +1,110 @@ - /*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision: 11989 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -/* =============== IMPORTANT TODO =================== - * ==== USE vtkSmartPointer<> when necessary ONLY!!!! - */ #ifndef _MITK_FiberBundleX_H #define _MITK_FiberBundleX_H //includes for MITK datastructure -#include "mitkBaseData.h" +#include #include "MitkDiffusionImagingExports.h" +#include //includes storing fiberdata #include //may be replaced by class precompile argument #include // may be replaced by class #include // my be replaced by class #include +#include + +#include + namespace mitk { /** * \brief Base Class for Fiber Bundles; */ class MitkDiffusionImaging_EXPORT FiberBundleX : public BaseData { public: - - // names of certain arrays (e.g colorcodings, etc.) + static const char* COLORCODING_ORIENTATION_BASED; - static const char* COLORCODING_FA_BASED; +// static const char* COLORCODING_FA_AS_OPACITY; + static const char* FA_VALUE_ARRAY; + static const char* COLORCODING_CUSTOM; static const char* FIBER_ID_ARRAY; - - /* friend classes wanna access typedefs - ContainerPointType, ContainerTractType, ContainerType */ - friend class FiberBundleXWriter; - friend class FiberBundleXReader; - - - // ======virtual methods must have====== + virtual void UpdateOutputInformation(); virtual void SetRequestedRegionToLargestPossibleRegion(); virtual bool RequestedRegionIsOutsideOfTheBufferedRegion(); virtual bool VerifyRequestedRegion(); virtual void SetRequestedRegion( itk::DataObject *data ); - //======================================= - - mitkClassMacro( FiberBundleX, BaseData ); - itkNewMacro( Self ); - - //custom constructor with passing argument - mitkNewMacro1Param(Self, vtkSmartPointer) + mitkClassMacro( FiberBundleX, BaseData ) + itkNewMacro( Self ) + mitkNewMacro1Param(Self, vtkSmartPointer) // custom constructor - - - - /*====FIBERBUNDLE I/O METHODS====*/ - void SetFiberPolyData(vtkSmartPointer); //set result of tractography algorithm in vtkPolyData format using vtkPolyLines + // set/get vtkPolyData + void SetFiberPolyData(vtkSmartPointer, bool updateGeometry = true); vtkSmartPointer GetFiberPolyData(); - char* getCurrentColorCoding(); - bool isFiberBundleXModified(); - void setFBXModificationDone(); - void UpdateFiberGeometry(); - - /*===FIBERBUNDLE PROCESSING METHODS====*/ + + mitk::FiberBundleX::Pointer operator+(mitk::FiberBundleX* fib); + mitk::FiberBundleX::Pointer operator-(mitk::FiberBundleX* fib); + + char* GetCurrentColorCoding(); + void SetColorCoding(const char*); + void SetFAMap(mitk::Image::Pointer); + + QStringList GetAvailableColorCodings(); void DoColorCodingOrientationbased(); + void DoColorCodingFAbased(); + void DoUseFAasColorOpacity(); + void ResetFiberColorOpacity(); void DoGenerateFiberIds(); - - /*===FIBERBUNDLE ASSESSMENT METHODS====*/ - + void ResampleFibers(float len); + void ResampleFibers(); + std::vector DoExtractFiberIds(mitk::PlanarFigure::Pointer ); + vtkSmartPointer GenerateNewFiberBundleByIds( std::vector ); itkGetMacro(NumFibers, int); + mitk::FiberBundleX::Pointer GetDeepCopy(); + protected: - FiberBundleX( vtkSmartPointer fiberPolyData = NULL ); + FiberBundleX( vtkPolyData* fiberPolyData = NULL ); virtual ~FiberBundleX(); - - + void UpdateFiberGeometry(); + itk::Point GetItkPoint(double point[3]); private: - - // The following polydata variables are used for fiber- and pointbased representation of the tractography results. As VTK suggests, one vtkPolyData is used to manage vertices and the other for polylines. - // FiberPolyData stores all brain fibers using polylines (in world coordinates) - // this variable hosts the smoothed fiber data, this data we generate, therefore a smartpointer structure is recommended -// vtkSmartPointer m_FiberPolyData; is depricated -// - // this variable hosts the original fiber data, no smartpointer needed because who or whatever passes this data to FiberBundleX should use vtkSmartPointer structure - - vtkSmartPointer m_FiberPolyData; //this is a common pointer because fiberDataStructure gets passed to this class. m_FiberStructureData is destroyed in the destructor then. - - // this variable contains all additional IDs of Fibers which are needed for efficient fiber manipulation such as extracting etc. - vtkSmartPointer m_FiberIdDataSet; - char* m_currentColorCoding; - - //this flag conzerns only visual representation. - bool m_isModified; + // actual fiber container + vtkSmartPointer m_FiberPolyData; + // contains all additional IDs of Fibers which are needed for efficient fiber manipulation such as extracting etc. + vtkSmartPointer m_FiberIdDataSet; + char* m_currentColorCoding; int m_NumFibers; - - + }; } // namespace mitk #endif /* _MITK_FiberBundleX_H */ diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp index af9a8b5f33..ac295f0d52 100644 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp +++ b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp @@ -1,385 +1,269 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ Version: $Revision: 18127 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkFiberBundleXReader.h" #include -#include -#include -#include -#include -#include -#include #include #include #include +#include +#include #include -#include - -const char* mitk::FiberBundleXReader::XML_GEOMETRY = "geometry"; - -const char* mitk::FiberBundleXReader::XML_MATRIX_XX = "xx"; - -const char* mitk::FiberBundleXReader::XML_MATRIX_XY = "xy"; - -const char* mitk::FiberBundleXReader::XML_MATRIX_XZ = "xz"; - -const char* mitk::FiberBundleXReader::XML_MATRIX_YX = "yx"; - -const char* mitk::FiberBundleXReader::XML_MATRIX_YY = "yy"; - -const char* mitk::FiberBundleXReader::XML_MATRIX_YZ = "yz"; - -const char* mitk::FiberBundleXReader::XML_MATRIX_ZX = "zx"; - -const char* mitk::FiberBundleXReader::XML_MATRIX_ZY = "zy"; - -const char* mitk::FiberBundleXReader::XML_MATRIX_ZZ = "zz"; - -const char* mitk::FiberBundleXReader::XML_ORIGIN_X = "origin_x"; - -const char* mitk::FiberBundleXReader::XML_ORIGIN_Y = "origin_y"; - -const char* mitk::FiberBundleXReader::XML_ORIGIN_Z = "origin_z"; - -const char* mitk::FiberBundleXReader::XML_SPACING_X = "spacing_x"; - -const char* mitk::FiberBundleXReader::XML_SPACING_Y = "spacing_y"; - -const char* mitk::FiberBundleXReader::XML_SPACING_Z = "spacing_z"; - -const char* mitk::FiberBundleXReader::XML_SIZE_X = "size_x"; - -const char* mitk::FiberBundleXReader::XML_SIZE_Y = "size_y"; - -const char* mitk::FiberBundleXReader::XML_SIZE_Z = "size_z"; - -const char* mitk::FiberBundleXReader::XML_FIBER_BUNDLE = "fiber_bundle"; - -const char* mitk::FiberBundleXReader::XML_FIBER = "fiber"; - -const char* mitk::FiberBundleXReader::XML_PARTICLE = "particle"; - -const char* mitk::FiberBundleXReader::XML_ID = "id"; - -const char* mitk::FiberBundleXReader::XML_POS_X = "pos_x"; - -const char* mitk::FiberBundleXReader::XML_POS_Y = "pos_y"; - -const char* mitk::FiberBundleXReader::XML_POS_Z = "pos_z"; - -const char* mitk::FiberBundleXReader::XML_NUM_FIBERS = "num_fibers"; - -const char* mitk::FiberBundleXReader::XML_NUM_PARTICLES = "num_particles"; - -const char* mitk::FiberBundleXReader::XML_FIBER_BUNDLE_FILE = "fiber_bundle_file" ; - -const char* mitk::FiberBundleXReader::XML_FILE_VERSION = "file_version" ; - -const char* mitk::FiberBundleXReader::VERSION_STRING = "0.1" ; +#include +#include namespace mitk { void FiberBundleXReader ::GenerateData() { - MITK_INFO << "Reading fiber bundle"; if ( ( ! m_OutputCache ) ) { Superclass::SetNumberOfRequiredOutputs(0); this->GenerateOutputInformation(); } if (!m_OutputCache) { - itkWarningMacro("Tree cache is empty!"); + itkWarningMacro("Output cache is empty!"); } Superclass::SetNumberOfRequiredOutputs(1); Superclass::SetNthOutput(0, m_OutputCache.GetPointer()); } void FiberBundleXReader::GenerateOutputInformation() { - m_OutputCache = OutputType::New(); - -// std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); -// ext = itksys::SystemTools::LowerCase(ext); - - if ( m_FileName == "") + try { - + const std::string& locale = "C"; + const std::string& currLocale = setlocale( LC_ALL, NULL ); + setlocale(LC_ALL, locale.c_str()); + + std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); + ext = itksys::SystemTools::LowerCase(ext); + + vtkSmartPointer chooser=vtkDataReader::New(); + chooser->SetFileName(m_FileName.c_str() ); + if( chooser->IsFilePolyData()) + { + MITK_INFO << "Reading vtk fiber bundle"; + vtkSmartPointer reader = vtkPolyDataReader::New(); + reader->SetFileName( m_FileName.c_str() ); + reader->Update(); + + if ( reader->GetOutput() != NULL ) + { + vtkSmartPointer fiberPolyData = reader->GetOutput(); + m_OutputCache = OutputType::New(fiberPolyData); + } + } + else // try to read deprecated fiber bundle file format + { + MITK_INFO << "Reading xml fiber bundle"; + + vtkSmartPointer fiberPolyData = vtkSmartPointer::New(); + vtkSmartPointer cellArray = vtkSmartPointer::New(); + vtkSmartPointer points = vtkSmartPointer::New(); + TiXmlDocument doc( m_FileName ); + if(doc.LoadFile()) + { + TiXmlHandle hDoc(&doc); + TiXmlElement* pElem; + TiXmlHandle hRoot(0); + + pElem = hDoc.FirstChildElement().Element(); + + // save this for later + hRoot = TiXmlHandle(pElem); + + pElem = hRoot.FirstChildElement("geometry").Element(); + + // read geometry + mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); + + // read origin + mitk::Point3D origin; + double temp = 0; + pElem->Attribute("origin_x", &temp); + origin[0] = temp; + pElem->Attribute("origin_y", &temp); + origin[1] = temp; + pElem->Attribute("origin_z", &temp); + origin[2] = temp; + geometry->SetOrigin(origin); + + // read spacing + float spacing[3]; + pElem->Attribute("spacing_x", &temp); + spacing[0] = temp; + pElem->Attribute("spacing_y", &temp); + spacing[1] = temp; + pElem->Attribute("spacing_z", &temp); + spacing[2] = temp; + geometry->SetSpacing(spacing); + + // read transform + vtkMatrix4x4* m = vtkMatrix4x4::New(); + pElem->Attribute("xx", &temp); + m->SetElement(0,0,temp); + pElem->Attribute("xy", &temp); + m->SetElement(1,0,temp); + pElem->Attribute("xz", &temp); + m->SetElement(2,0,temp); + pElem->Attribute("yx", &temp); + m->SetElement(0,1,temp); + pElem->Attribute("yy", &temp); + m->SetElement(1,1,temp); + pElem->Attribute("yz", &temp); + m->SetElement(2,1,temp); + pElem->Attribute("zx", &temp); + m->SetElement(0,2,temp); + pElem->Attribute("zy", &temp); + m->SetElement(1,2,temp); + pElem->Attribute("zz", &temp); + m->SetElement(2,2,temp); + + m->SetElement(0,3,origin[0]); + m->SetElement(1,3,origin[1]); + m->SetElement(2,3,origin[2]); + m->SetElement(3,3,1); + geometry->SetIndexToWorldTransformByVtkMatrix(m); + + // read bounds + float bounds[] = {0, 0, 0, 0, 0, 0}; + pElem->Attribute("size_x", &temp); + bounds[1] = temp; + pElem->Attribute("size_y", &temp); + bounds[3] = temp; + pElem->Attribute("size_z", &temp); + bounds[5] = temp; + geometry->SetFloatBounds(bounds); + geometry->SetImageGeometry(true); + + pElem = hRoot.FirstChildElement("fiber_bundle").FirstChild().Element(); + for( pElem; pElem; pElem=pElem->NextSiblingElement()) + { + TiXmlElement* pElem2 = pElem->FirstChildElement(); + + vtkSmartPointer container = vtkSmartPointer::New(); + + for( pElem2; pElem2; pElem2=pElem2->NextSiblingElement()) + { + itk::Point point; + pElem2->Attribute("pos_x", &temp); + point[0] = temp; + pElem2->Attribute("pos_y", &temp); + point[1] = temp; + pElem2->Attribute("pos_z", &temp); + point[2] = temp; + + geometry->IndexToWorld(point, point); + vtkIdType id = points->InsertNextPoint(point.GetDataPointer()); + container->GetPointIds()->InsertNextId(id); + + } + cellArray->InsertNextCell(container); + } + fiberPolyData->SetPoints(points); + fiberPolyData->SetLines(cellArray); + m_OutputCache = OutputType::New(fiberPolyData); + } + else + { + MITK_INFO << "could not open xml file"; + throw "could not open xml file"; + } + } + setlocale(LC_ALL, currLocale.c_str()); + MITK_INFO << "Fiber bundle read"; + } + catch(...) + { + throw; } -// else if (ext == ".fib") -// { -// try -// { -// TiXmlDocument doc( m_FileName ); -// doc.LoadFile(); -// -// TiXmlHandle hDoc(&doc); -// TiXmlElement* pElem; -// TiXmlHandle hRoot(0); -// -// pElem = hDoc.FirstChildElement().Element(); -// -// // save this for later -// hRoot = TiXmlHandle(pElem); -// -// pElem = hRoot.FirstChildElement(FiberBundleXReader::XML_GEOMETRY).Element(); -// -// // read geometry -// mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); -// -// // read origin -// mitk::Point3D origin; -// double temp = 0; -// pElem->Attribute(FiberBundleXReader::XML_ORIGIN_X, &temp); -// origin[0] = temp; -// pElem->Attribute(FiberBundleXReader::XML_ORIGIN_Y, &temp); -// origin[1] = temp; -// pElem->Attribute(FiberBundleXReader::XML_ORIGIN_Z, &temp); -// origin[2] = temp; -// geometry->SetOrigin(origin); -// -// // read spacing -// float spacing[3]; -// pElem->Attribute(FiberBundleXReader::XML_SPACING_X, &temp); -// spacing[0] = temp; -// pElem->Attribute(FiberBundleXReader::XML_SPACING_Y, &temp); -// spacing[1] = temp; -// pElem->Attribute(FiberBundleXReader::XML_SPACING_Z, &temp); -// spacing[2] = temp; -// geometry->SetSpacing(spacing); -// -// // read transform -// vtkMatrix4x4* m = vtkMatrix4x4::New(); -// pElem->Attribute(FiberBundleXReader::XML_MATRIX_XX, &temp); -// m->SetElement(0,0,temp); -// pElem->Attribute(FiberBundleXReader::XML_MATRIX_XY, &temp); -// m->SetElement(1,0,temp); -// pElem->Attribute(FiberBundleXReader::XML_MATRIX_XZ, &temp); -// m->SetElement(2,0,temp); -// pElem->Attribute(FiberBundleXReader::XML_MATRIX_YX, &temp); -// m->SetElement(0,1,temp); -// pElem->Attribute(FiberBundleXReader::XML_MATRIX_YY, &temp); -// m->SetElement(1,1,temp); -// pElem->Attribute(FiberBundleXReader::XML_MATRIX_YZ, &temp); -// m->SetElement(2,1,temp); -// pElem->Attribute(FiberBundleXReader::XML_MATRIX_ZX, &temp); -// m->SetElement(0,2,temp); -// pElem->Attribute(FiberBundleXReader::XML_MATRIX_ZY, &temp); -// m->SetElement(1,2,temp); -// pElem->Attribute(FiberBundleXReader::XML_MATRIX_ZZ, &temp); -// m->SetElement(2,2,temp); -// -// m->SetElement(0,3,origin[0]); -// m->SetElement(1,3,origin[1]); -// m->SetElement(2,3,origin[2]); -// m->SetElement(3,3,1); -// geometry->SetIndexToWorldTransformByVtkMatrix(m); -// -// // read bounds -// float bounds[] = {0, 0, 0, 0, 0, 0}; -// pElem->Attribute(FiberBundleXReader::XML_SIZE_X, &temp); -// bounds[1] = temp; -// pElem->Attribute(FiberBundleXReader::XML_SIZE_Y, &temp); -// bounds[3] = temp; -// pElem->Attribute(FiberBundleXReader::XML_SIZE_Z, &temp); -// bounds[5] = temp; -// geometry->SetFloatBounds(bounds); -// -// // read bounds -// float bounds2[] = {0, 0, 0}; -// bounds2[0] = bounds[1]; -// bounds2[1] = bounds[3]; -// bounds2[2] = bounds[5]; -// m_OutputCache->SetBounds(bounds2); -// -// geometry->SetImageGeometry(true); -// m_OutputCache->SetGeometry(geometry); -// -// // generate tract container -// ContainerType::Pointer tractContainer = ContainerType::New(); -// -// int fiberID = 0; -// pElem = hRoot.FirstChildElement(FiberBundleXReader::XML_FIBER_BUNDLE).FirstChild().Element(); -// for( pElem; pElem; pElem=pElem->NextSiblingElement()) -// { -// TiXmlElement* pElem2 = pElem->FirstChildElement(); -// ContainerTractType::Pointer tract = ContainerTractType::New(); -// for( pElem2; pElem2; pElem2=pElem2->NextSiblingElement()) -// { -// ContainerPointType point; -// pElem2->Attribute(FiberBundleXReader::XML_POS_X, &temp); -// point[0] = temp; -// pElem2->Attribute(FiberBundleXReader::XML_POS_Y, &temp); -// point[1] = temp; -// pElem2->Attribute(FiberBundleXReader::XML_POS_Z, &temp); -// point[2] = temp; -// -// tract->InsertElement(tract->Size(), point); -// -// } -// pElem->Attribute(FiberBundleXReader::XML_ID, &fiberID); -// tractContainer->CreateIndex(fiberID); -// tractContainer->SetElement(fiberID, tract); -// -// } -// m_OutputCache->addTractContainer(tractContainer); -// m_OutputCache->initFiberGroup(); -// -// MITK_INFO << "Fiber bundle read"; -// } -// catch(...) -// { -// MITK_INFO << "Could not read file "; -// } -// } -// else if (ext == ".vfib") -// { -// // generate tract container -// ContainerType::Pointer tractContainer = ContainerType::New(); -// mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); -// -// ///We create a Generic Reader to test de .vtk/ -// vtkDataReader *chooser=vtkDataReader::New(); -// chooser->SetFileName(m_FileName.c_str() ); -// if( chooser->IsFilePolyData()) -// { -// vtkPolyDataReader *reader = vtkPolyDataReader::New(); -// reader->SetFileName( m_FileName.c_str() ); -// reader->Update(); -// -// if ( reader->GetOutput() != NULL ) -// { -// vtkPolyData* output = reader->GetOutput(); -// output->ComputeBounds(); -// double bounds[3]; -// output->GetBounds(bounds); -// double center[3]; -// output->GetCenter(center); -// Point3D origin; -// origin.SetElement(0, -center[0]); -// origin.SetElement(1, -center[1]); -// origin.SetElement(2, -center[2]); -// MITK_INFO << origin; -// -// mitk::Surface::Pointer surf = mitk::Surface::New(); -// surf->SetVtkPolyData(output); -// mitk::Geometry3D* geom = surf->GetGeometry(); -// //geom->SetOrigin(origin); -// geom->SetImageGeometry(true); -// m_OutputCache->SetBounds(bounds); -// m_OutputCache->SetGeometry(geom); -// vtkCellArray* cells = output->GetLines(); -// -// cells->InitTraversal(); -// -// for (int i=0; iGetNumberOfCells(); i++) -// { -// ContainerTractType::Pointer tract = ContainerTractType::New(); -// vtkCell* cell = output->GetCell(i); -// int p = cell->GetNumberOfPoints(); -// vtkPoints* points = cell->GetPoints(); -// for (int j=0; jGetPoint(j, p); -// ContainerPointType point; -// point[0] = p[0]; -// point[1] = p[1]; -// point[2] = p[2]; -// tract->InsertElement(tract->Size(), point); -// } -// tractContainer->InsertElement(i, tract); -// } -// } -// reader->Delete(); -// } -// chooser->Delete(); -// -// m_OutputCache->addTractContainer(tractContainer); -// m_OutputCache->initFiberGroup(); -// MITK_INFO << "Fiber bundle read"; -// } } void FiberBundleXReader::Update() { this->GenerateData(); } const char* FiberBundleXReader ::GetFileName() const { return m_FileName.c_str(); } void FiberBundleXReader ::SetFileName(const char* aFileName) { m_FileName = aFileName; } const char* FiberBundleXReader ::GetFilePrefix() const { return m_FilePrefix.c_str(); } void FiberBundleXReader ::SetFilePrefix(const char* aFilePrefix) { m_FilePrefix = aFilePrefix; } const char* FiberBundleXReader ::GetFilePattern() const { return m_FilePattern.c_str(); } void FiberBundleXReader ::SetFilePattern(const char* aFilePattern) { m_FilePattern = aFilePattern; } bool FiberBundleXReader ::CanReadFile(const std::string filename, const std::string /*filePrefix*/, const std::string /*filePattern*/) { // First check the extension if( filename == "" ) { return false; } -// std::string ext = itksys::SystemTools::GetFilenameLastExtension(filename); -// ext = itksys::SystemTools::LowerCase(ext); + std::string ext = itksys::SystemTools::GetFilenameLastExtension(filename); + ext = itksys::SystemTools::LowerCase(ext); + if (ext == ".fib") + { + return true; + } return false; } } //namespace MITK diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXReader.h b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXReader.h index e2a5c10ba5..fe53bea830 100644 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXReader.h +++ b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXReader.h @@ -1,143 +1,77 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-07-14 19:11:20 +0200 (Tue, 14 Jul 2009) $ Version: $Revision: 18127 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __mitkFiberBundleXReader_h #define __mitkFiberBundleXReader_h -#include "mitkCommon.h" -#include "itkVectorContainer.h" -#include "mitkFileReader.h" -#include "mitkFiberBundleX.h" -#include "itkSlowPolyLineParametricPath.h" - -//NOTE>umbenennen in FiberBundleXSource +#include +#include +#include +#include namespace mitk { - /** \brief + /** \brief */ class FiberBundleXReader : public FileReader, public BaseProcess { public: /** Types for the standardized TractContainer **/ /* direct linked includes of mitkFiberBundleX DataStructure */ - + typedef mitk::FiberBundleX OutputType; - + mitkClassMacro( FiberBundleXReader, BaseProcess ); itkNewMacro(Self); const char* GetFileName() const; void SetFileName(const char* aFileName); const char* GetFilePrefix() const; void SetFilePrefix(const char* aFilePrefix); const char* GetFilePattern() const; void SetFilePattern(const char* aFilePattern); static bool CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern); // itkGetMacro(GroupFiberBundleX, FiberGroupType::Pointer); // itkGetMacro(TractContainer, ContainerType::Pointer); virtual void Update(); - - static const char* XML_GEOMETRY; - - static const char* XML_MATRIX_XX; - - static const char* XML_MATRIX_XY; - - static const char* XML_MATRIX_XZ; - - static const char* XML_MATRIX_YX; - - static const char* XML_MATRIX_YY; - - static const char* XML_MATRIX_YZ; - - static const char* XML_MATRIX_ZX; - - static const char* XML_MATRIX_ZY; - - static const char* XML_MATRIX_ZZ; - - static const char* XML_ORIGIN_X; - - static const char* XML_ORIGIN_Y; - - static const char* XML_ORIGIN_Z; - - static const char* XML_SPACING_X; - - static const char* XML_SPACING_Y; - - static const char* XML_SPACING_Z; - - static const char* XML_SIZE_X; - - static const char* XML_SIZE_Y; - - static const char* XML_SIZE_Z; - - static const char* XML_FIBER_BUNDLE; - - static const char* XML_FIBER; - - static const char* XML_PARTICLE; - - static const char* XML_ID; - - static const char* XML_POS_X; - - static const char* XML_POS_Y; - - static const char* XML_POS_Z; - - static const char* VERSION_STRING; - - static const char* XML_FIBER_BUNDLE_FILE; - - static const char* XML_FILE_VERSION; - - static const char* XML_NUM_FIBERS; - - static const char* XML_NUM_PARTICLES; - protected: /** Does the real work. */ virtual void GenerateData(); virtual void GenerateOutputInformation(); OutputType::Pointer m_OutputCache; std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; private: void operator=(const Self&); //purposely not implemented }; } //namespace MITK #endif // __mitkFiberBundleXReader_h diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp index c6d31cad5d..9093c9496c 100644 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp +++ b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp @@ -1,227 +1,95 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-12-10 18:05:13 +0100 (Mi, 10 Dez 2008) $ Version: $Revision: 15922 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkFiberBundleXWriter.h" -#include - -const char* mitk::FiberBundleXWriter::XML_GEOMETRY = "geometry"; - -const char* mitk::FiberBundleXWriter::XML_MATRIX_XX = "xx"; - -const char* mitk::FiberBundleXWriter::XML_MATRIX_XY = "xy"; - -const char* mitk::FiberBundleXWriter::XML_MATRIX_XZ = "xz"; - -const char* mitk::FiberBundleXWriter::XML_MATRIX_YX = "yx"; - -const char* mitk::FiberBundleXWriter::XML_MATRIX_YY = "yy"; - -const char* mitk::FiberBundleXWriter::XML_MATRIX_YZ = "yz"; - -const char* mitk::FiberBundleXWriter::XML_MATRIX_ZX = "zx"; - -const char* mitk::FiberBundleXWriter::XML_MATRIX_ZY = "zy"; - -const char* mitk::FiberBundleXWriter::XML_MATRIX_ZZ = "zz"; - -const char* mitk::FiberBundleXWriter::XML_ORIGIN_X = "origin_x"; - -const char* mitk::FiberBundleXWriter::XML_ORIGIN_Y = "origin_y"; - -const char* mitk::FiberBundleXWriter::XML_ORIGIN_Z = "origin_z"; - -const char* mitk::FiberBundleXWriter::XML_SPACING_X = "spacing_x"; - -const char* mitk::FiberBundleXWriter::XML_SPACING_Y = "spacing_y"; - -const char* mitk::FiberBundleXWriter::XML_SPACING_Z = "spacing_z"; - -const char* mitk::FiberBundleXWriter::XML_SIZE_X = "size_x"; - -const char* mitk::FiberBundleXWriter::XML_SIZE_Y = "size_y"; - -const char* mitk::FiberBundleXWriter::XML_SIZE_Z = "size_z"; - -const char* mitk::FiberBundleXWriter::XML_FIBER_BUNDLE = "fiber_bundle"; - -const char* mitk::FiberBundleXWriter::XML_FIBER = "fiber"; - -const char* mitk::FiberBundleXWriter::XML_PARTICLE = "particle"; - -const char* mitk::FiberBundleXWriter::XML_ID = "id"; - -const char* mitk::FiberBundleXWriter::XML_POS_X = "pos_x"; - -const char* mitk::FiberBundleXWriter::XML_POS_Y = "pos_y"; - -const char* mitk::FiberBundleXWriter::XML_POS_Z = "pos_z"; - -const char* mitk::FiberBundleXWriter::XML_NUM_FIBERS = "num_fibers"; - -const char* mitk::FiberBundleXWriter::XML_NUM_PARTICLES = "num_particles"; - -const char* mitk::FiberBundleXWriter::XML_FIBER_BUNDLE_FILE = "fiber_bundle_file" ; - -const char* mitk::FiberBundleXWriter::XML_FILE_VERSION = "file_version" ; - -const char* mitk::FiberBundleXWriter::VERSION_STRING = "0.1" ; - -const char* mitk::FiberBundleXWriter::ASCII_FILE = "ascii_file" ; - -const char* mitk::FiberBundleXWriter::FILE_NAME = "file_name" ; +#include mitk::FiberBundleXWriter::FiberBundleXWriter() : m_FileName(""), m_FilePrefix(""), m_FilePattern(""), m_Success(false) { this->SetNumberOfRequiredInputs( 1 ); } mitk::FiberBundleXWriter::~FiberBundleXWriter() {} void mitk::FiberBundleXWriter::GenerateData() { - MITK_INFO << "Writing fiber bundle"; - m_Success = false; - InputType* input = this->GetInput(); - if (input == NULL) + try { - itkWarningMacro(<<"Sorry, input to FiberBundleXWriter is NULL!"); - return; + const std::string& locale = "C"; + const std::string& currLocale = setlocale( LC_ALL, NULL ); + setlocale(LC_ALL, locale.c_str()); + + MITK_INFO << "Writing fiber bundle"; + m_Success = false; + InputType* input = this->GetInput(); + if (input == NULL) + { + itkWarningMacro(<<"Sorry, input to FiberBundleXWriter is NULL!"); + return; + } + if ( m_FileName == "" ) + { + itkWarningMacro( << "Sorry, filename has not been set!" ); + return ; + } + vtkSmartPointer writer = vtkSmartPointer::New(); + writer->SetInput(input->GetFiberPolyData()); + writer->SetFileName(m_FileName.c_str()); + writer->SetFileTypeToASCII(); + writer->Write(); + + setlocale(LC_ALL, currLocale.c_str()); + m_Success = true; + MITK_INFO << "Fiber bundle written"; } - if ( m_FileName == "" ) + catch(...) { - itkWarningMacro( << "Sorry, filename has not been set!" ); - return ; + throw; } - -// std::string ext = itksys::SystemTools::GetFilenameLastExtension(m_FileName); -// ext = itksys::SystemTools::LowerCase(ext); - -// if (ext == ".fib") -// { -// /* direct linked includes of mitkFiberBundleX DataStructure */ -// -// mitk::Geometry3D* geometry = input->GetGeometry(); -// -// TiXmlDocument documentXML; -// TiXmlDeclaration* declXML = new TiXmlDeclaration( "1.0", "", "" ); // TODO what to write here? encoding? etc.... -// documentXML.LinkEndChild( declXML ); -// -// TiXmlElement* mainXML = new TiXmlElement(mitk::FiberBundleXWriter::XML_FIBER_BUNDLE_FILE); -// mainXML->SetAttribute(mitk::FiberBundleXWriter::XML_FILE_VERSION, mitk::FiberBundleXWriter::VERSION_STRING); -// documentXML.LinkEndChild(mainXML); -// -// TiXmlElement* geometryXML = new TiXmlElement(mitk::FiberBundleXWriter::XML_GEOMETRY); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_MATRIX_XX, geometry->GetMatrixColumn(0)[0]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_MATRIX_XY, geometry->GetMatrixColumn(0)[1]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_MATRIX_XZ, geometry->GetMatrixColumn(0)[2]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_MATRIX_YX, geometry->GetMatrixColumn(1)[0]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_MATRIX_YY, geometry->GetMatrixColumn(1)[1]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_MATRIX_YZ, geometry->GetMatrixColumn(1)[2]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_MATRIX_ZX, geometry->GetMatrixColumn(2)[0]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_MATRIX_ZY, geometry->GetMatrixColumn(2)[1]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_MATRIX_ZZ, geometry->GetMatrixColumn(2)[2]); -// -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_ORIGIN_X, geometry->GetOrigin()[0]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_ORIGIN_Y, geometry->GetOrigin()[1]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_ORIGIN_Z, geometry->GetOrigin()[2]); -// -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_SPACING_X, geometry->GetSpacing()[0]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_SPACING_Y, geometry->GetSpacing()[1]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_SPACING_Z, geometry->GetSpacing()[2]); -// -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_SIZE_X, input->GetBounds()[0]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_SIZE_Y, input->GetBounds()[1]); -// geometryXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_SIZE_Z, input->GetBounds()[2]); -// -// mainXML->LinkEndChild(geometryXML); -// -// TiXmlElement* FiberBundleXXML = new TiXmlElement(mitk::FiberBundleXWriter::XML_FIBER_BUNDLE); -// FiberBundleXXML->SetAttribute(mitk::FiberBundleXWriter::XML_NUM_FIBERS, tractContainer->size()); -// int numParticles = 0; -// for (int i=0; iSize(); i++) -// { -// ContainerTractType::Pointer tract = tractContainer->GetElement(i); -// TiXmlElement* fiberXML = new TiXmlElement(mitk::FiberBundleXWriter::XML_FIBER); -// fiberXML->SetAttribute(mitk::FiberBundleXWriter::XML_ID, i); -// fiberXML->SetAttribute(mitk::FiberBundleXWriter::XML_NUM_PARTICLES, tract->Size()); -// numParticles += tract->Size(); -// for (int j=0; jSize(); j++) -// { -// TiXmlElement* particleXML = new TiXmlElement(mitk::FiberBundleXWriter::XML_PARTICLE); -// ContainerPointType p = tract->GetElement(j); -// particleXML->SetAttribute(mitk::FiberBundleXWriter::XML_ID, j); -// particleXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_POS_X, p[0]); -// particleXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_POS_Y, p[1]); -// particleXML->SetDoubleAttribute(mitk::FiberBundleXWriter::XML_POS_Z, p[2]); -// fiberXML->LinkEndChild(particleXML); -// } -// FiberBundleXXML->LinkEndChild(fiberXML); -// } -// FiberBundleXXML->SetAttribute(mitk::FiberBundleXWriter::XML_NUM_PARTICLES, numParticles); -// mainXML->LinkEndChild(FiberBundleXXML); -// -// documentXML.SaveFile( m_FileName ); -// -// m_Success = true; -// -// MITK_INFO << "Fiber bundle written"; -// -// }else if (ext == ".vfib" || ext == ".vtk") { -// vtkPolyDataWriter* writer = vtkPolyDataWriter::New(); -// writer->SetInput(input->GeneratePolydata()); -// writer->SetFileName(m_FileName.c_str()); -// writer->SetFileTypeToASCII(); -// writer->Write(); -// -// m_Success = true; -// MITK_INFO << "Fiber bundle written as polydata"; -// } - } void mitk::FiberBundleXWriter::SetInputFiberBundleX( InputType* diffVolumes ) { this->ProcessObject::SetNthInput( 0, diffVolumes ); } mitk::FiberBundleX* mitk::FiberBundleXWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return dynamic_cast ( this->ProcessObject::GetInput( 0 ) ); } } std::vector mitk::FiberBundleXWriter::GetPossibleFileExtensions() { std::vector possibleFileExtensions; possibleFileExtensions.push_back(".fib"); - possibleFileExtensions.push_back(".vfib"); possibleFileExtensions.push_back(".vtk"); return possibleFileExtensions; } diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h index 84a248080b..13a4ebb0c9 100644 --- a/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h +++ b/Modules/DiffusionImaging/IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h @@ -1,216 +1,216 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-08-27 17:18:46 +0200 (Mi, 27 Aug 2008) $ Version: $Revision: 15096 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __mitkFiberBundleXWriter_h #define __mitkFiberBundleXWriter_h #include #include #include "mitkFiberBundleX.h" #include namespace mitk { /** * Writes fiber bundles to a file * @ingroup Process */ class FiberBundleXWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro( FiberBundleXWriter, mitk::FileWriterWithInformation ); //mitkWriterMacro; virtual void Write() { if ( this->GetInput() == NULL ) { itkExceptionMacro(<<"Write:Please specify an input!"); return; } /* Fill in image information.*/ this->UpdateOutputInformation(); (*(this->GetInputs().begin()))->SetRequestedRegionToLargestPossibleRegion(); this->PropagateRequestedRegion(NULL); this->UpdateOutputData(NULL); } virtual void Update() { Write(); } itkNewMacro( Self ); typedef mitk::FiberBundleX InputType; /** * Sets the filename of the file to write. * @param FileName the name of the file to write. */ itkSetStringMacro( FileName ); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro( FileName ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePrefix ); /** * @warning multiple write not (yet) supported */ itkSetStringMacro( FilePattern ); /** * @warning multiple write not (yet) supported */ itkGetStringMacro( FilePattern ); /** * Sets the input object for the filter. * @param input the diffusion volumes to write to file. */ void SetInputFiberBundleX( InputType* input ); /** * @returns the 0'th input object of the filter. */ InputType* GetInput(); /** * Returns false if an error happened during writing */ itkGetMacro( Success, bool ); /** * @return possible file extensions for the data type associated with the writer */ virtual std::vector GetPossibleFileExtensions(); // FileWriterWithInformation methods - virtual const char * GetDefaultFilename() { return "FiberBundleX.fib"; } - virtual const char * GetFileDialogPattern() { return "Fiber Bundle (*.fib *.vfib *.vtk)"; } + virtual const char * GetDefaultFilename() { return "FiberBundle.fib"; } + virtual const char * GetFileDialogPattern() { return "Fiber Bundle (*.fib *.vtk)"; } virtual const char * GetDefaultExtension() { return ".fib"; } virtual bool CanWriteBaseDataType(BaseData::Pointer data) { return (dynamic_cast(data.GetPointer()) != NULL); }; virtual void DoWrite(BaseData::Pointer data) { if (CanWriteBaseDataType(data)) { this->SetInputFiberBundleX(dynamic_cast(data.GetPointer())); this->Update(); } }; static const char* XML_GEOMETRY; static const char* XML_MATRIX_XX; static const char* XML_MATRIX_XY; static const char* XML_MATRIX_XZ; static const char* XML_MATRIX_YX; static const char* XML_MATRIX_YY; static const char* XML_MATRIX_YZ; static const char* XML_MATRIX_ZX; static const char* XML_MATRIX_ZY; static const char* XML_MATRIX_ZZ; static const char* XML_ORIGIN_X; static const char* XML_ORIGIN_Y; static const char* XML_ORIGIN_Z; static const char* XML_SPACING_X; static const char* XML_SPACING_Y; static const char* XML_SPACING_Z; static const char* XML_SIZE_X; static const char* XML_SIZE_Y; static const char* XML_SIZE_Z; static const char* XML_FIBER_BUNDLE; static const char* XML_FIBER; static const char* XML_PARTICLE; static const char* XML_ID; static const char* XML_POS_X; static const char* XML_POS_Y; static const char* XML_POS_Z; static const char* VERSION_STRING; static const char* XML_FIBER_BUNDLE_FILE; static const char* XML_FILE_VERSION; static const char* XML_NUM_FIBERS; static const char* XML_NUM_PARTICLES; static const char* ASCII_FILE; static const char* FILE_NAME; protected: FiberBundleXWriter(); virtual ~FiberBundleXWriter(); virtual void GenerateData(); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; bool m_Success; }; } // end of namespace mitk #endif //__mitkFiberBundleXWriter_h diff --git a/Modules/DiffusionImaging/IODataStructures/mitkDiffusionImagingObjectFactory.cpp b/Modules/DiffusionImaging/IODataStructures/mitkDiffusionImagingObjectFactory.cpp index 196d9ffa65..4fd83614f6 100644 --- a/Modules/DiffusionImaging/IODataStructures/mitkDiffusionImagingObjectFactory.cpp +++ b/Modules/DiffusionImaging/IODataStructures/mitkDiffusionImagingObjectFactory.cpp @@ -1,409 +1,374 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-06-18 15:59:04 +0200 (Do, 18 Jun 2009) $ Version: $Revision: 16916 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkDiffusionImagingObjectFactory.h" #include "mitkProperties.h" #include "mitkBaseRenderer.h" #include "mitkDataNode.h" #include "mitkNrrdDiffusionImageIOFactory.h" #include "mitkNrrdDiffusionImageWriterFactory.h" #include "mitkNrrdDiffusionImageWriter.h" #include "mitkDiffusionImage.h" #include "mitkNrrdQBallImageIOFactory.h" #include "mitkNrrdQBallImageWriterFactory.h" #include "mitkNrrdQBallImageWriter.h" #include "mitkNrrdTensorImageIOFactory.h" #include "mitkNrrdTensorImageWriterFactory.h" #include "mitkNrrdTensorImageWriter.h" #include "mitkCompositeMapper.h" #include "mitkDiffusionImageMapper.h" #include "mitkGPUVolumeMapper3D.h" #include "mitkVolumeDataVtkMapper3D.h" #include "mitkTbssImageMapper.h" -//====depricated fiberstructure===== -#include "mitkFiberBundle.h" -#include "mitkFiberBundleMapper2D.h" -#include "mitkFiberBundleMapper3D.h" -#include "mitkFiberBundleIOFactory.h" -#include "mitkFiberBundleWriterFactory.h" -#include "mitkFiberBundleWriter.h" -//================================== - //modernized fiberbundle datastrucutre #include "mitkFiberBundleX.h" #include "mitkFiberBundleXIOFactory.h" #include "mitkFiberBundleXWriterFactory.h" #include "mitkFiberBundleXWriter.h" #include "mitkFiberBundleXMapper3D.h" #include "mitkFiberBundleXMapper2D.h" #include "mitkFiberBundleXThreadMonitorMapper3D.h" #include "mitkFiberBundleXThreadMonitor.h" #include "mitkNrrdTbssImageIOFactory.h" #include "mitkNrrdTbssImageWriterFactory.h" #include "mitkNrrdTbssImageWriter.h" #include "mitkNrrdTbssRoiImageIOFactory.h" #include "mitkNrrdTbssRoiImageWriterFactory.h" #include "mitkNrrdTbssRoiImageWriter.h" #include "mitkPlanarCircleMapper3D.h" #include "mitkPlanarPolygonMapper3D.h" typedef short DiffusionPixelType; typedef char TbssRoiPixelType; typedef float TbssPixelType; typedef int TbssGradientPixelType; typedef mitk::DiffusionImage DiffusionImageShort; typedef std::multimap MultimapType; mitk::DiffusionImagingObjectFactory::DiffusionImagingObjectFactory(bool /*registerSelf*/) :CoreObjectFactoryBase() { static bool alreadyDone = false; if (!alreadyDone) { MITK_DEBUG << "DiffusionImagingObjectFactory c'tor" << std::endl; RegisterIOFactories(); mitk::NrrdDiffusionImageIOFactory::RegisterOneFactory(); mitk::NrrdQBallImageIOFactory::RegisterOneFactory(); mitk::NrrdTensorImageIOFactory::RegisterOneFactory(); - mitk::FiberBundleIOFactory::RegisterOneFactory(); mitk::NrrdTbssImageIOFactory::RegisterOneFactory(); mitk::NrrdTbssRoiImageIOFactory::RegisterOneFactory(); mitk::FiberBundleXIOFactory::RegisterOneFactory(); //modernized mitk::NrrdDiffusionImageWriterFactory::RegisterOneFactory(); mitk::NrrdQBallImageWriterFactory::RegisterOneFactory(); mitk::NrrdTensorImageWriterFactory::RegisterOneFactory(); - mitk::FiberBundleWriterFactory::RegisterOneFactory(); mitk::NrrdTbssImageWriterFactory::RegisterOneFactory(); mitk::NrrdTbssRoiImageWriterFactory::RegisterOneFactory(); mitk::FiberBundleXWriterFactory::RegisterOneFactory();//modernized m_FileWriters.push_back( NrrdDiffusionImageWriter::New().GetPointer() ); m_FileWriters.push_back( NrrdQBallImageWriter::New().GetPointer() ); m_FileWriters.push_back( NrrdTensorImageWriter::New().GetPointer() ); - m_FileWriters.push_back( mitk::FiberBundleWriter::New().GetPointer() ); m_FileWriters.push_back( NrrdTbssImageWriter::New().GetPointer() ); m_FileWriters.push_back( NrrdTbssRoiImageWriter::New().GetPointer() ); m_FileWriters.push_back( mitk::FiberBundleXWriter::New().GetPointer() );//modernized mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(this); CreateFileExtensionsMap(); alreadyDone = true; } } mitk::Mapper::Pointer mitk::DiffusionImagingObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id) { mitk::Mapper::Pointer newMapper=NULL; if ( id == mitk::BaseRenderer::Standard2D ) { std::string classname("QBallImage"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::CompositeMapper::New(); newMapper->SetDataNode(node); node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper()); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::CompositeMapper::New(); newMapper->SetDataNode(node); node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper()); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::DiffusionImageMapper::New(); newMapper->SetDataNode(node); } classname = "TbssRoiImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::ImageVtkMapper2D::New(); newMapper->SetDataNode(node); } - - classname = "FiberBundle"; - if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) - { - newMapper = mitk::FiberBundleMapper2D::New(); - newMapper->SetDataNode(node); - } - + classname = "FiberBundleX"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::FiberBundleXMapper2D::New(); newMapper->SetDataNode(node); } classname = "TbssImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::TbssImageMapper::New(); newMapper->SetDataNode(node); } } else if ( id == mitk::BaseRenderer::Standard3D ) { std::string classname("QBallImage"); if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::GPUVolumeMapper3D::New(); newMapper->SetDataNode(node); } - classname = "FiberBundle"; - if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) - { - newMapper = mitk::FiberBundleMapper3D::New(); - newMapper->SetDataNode(node); - } classname = "FiberBundleX"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::FiberBundleXMapper3D::New(); newMapper->SetDataNode(node); } - + classname = "FiberBundleXThreadMonitor"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::FiberBundleXThreadMonitorMapper3D::New(); - newMapper->SetDataNode(node); + newMapper->SetDataNode(node); } classname = "TbssRoiImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::VolumeDataVtkMapper3D::New(); newMapper->SetDataNode(node); } classname = "TbssImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) - { + { newMapper = mitk::TbssImageMapper::New(); newMapper->SetDataNode(node); } - + classname = "PlanarCircle"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::PlanarCircleMapper3D::New(); newMapper->SetDataNode(node); } - + classname = "PlanarPolygon"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { newMapper = mitk::PlanarPolygonMapper3D::New(); newMapper->SetDataNode(node); } } return newMapper; } void mitk::DiffusionImagingObjectFactory::SetDefaultProperties(mitk::DataNode* node) { std::string classname = "QBallImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::CompositeMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } classname = "TensorImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::CompositeMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } classname = "DiffusionImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::DiffusionImageMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } - classname = "FiberBundle"; - if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) - { - mitk::FiberBundleMapper3D::SetDefaultProperties(node); - mitk::FiberBundleMapper2D::SetDefaultProperties(node); - } - classname = "FiberBundleX"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::FiberBundleXMapper3D::SetDefaultProperties(node); -// mitk::FiberBundleXMapper2D::SetDefaultProperties(node); + mitk::FiberBundleXMapper2D::SetDefaultProperties(node); } classname = "FiberBundleXThreadMonitor"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::FiberBundleXThreadMonitorMapper3D::SetDefaultProperties(node); } - + classname = "TbssRoiImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::ImageVtkMapper2D::SetDefaultProperties(node); mitk::VolumeDataVtkMapper3D::SetDefaultProperties(node); } classname = "TbssImage"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::TbssImageMapper::SetDefaultProperties(node); mitk::GPUVolumeMapper3D::SetDefaultProperties(node); } - classname = "PlanarCircle"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::PlanarCircleMapper3D::SetDefaultProperties(node); } - + classname = "PlanarPolygon"; if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0) { mitk::PlanarPolygonMapper3D::SetDefaultProperties(node); } } const char* mitk::DiffusionImagingObjectFactory::GetFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_FileExtensionsMap, fileExtension); return fileExtension.c_str(); }; mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionImagingObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } const char* mitk::DiffusionImagingObjectFactory::GetSaveFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); return fileExtension.c_str(); }; mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionImagingObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } void mitk::DiffusionImagingObjectFactory::CreateFileExtensionsMap() { m_FileExtensionsMap.insert(std::pair("*.dwi", "Diffusion Weighted Images")); m_FileExtensionsMap.insert(std::pair("*.hdwi", "Diffusion Weighted Images")); m_FileExtensionsMap.insert(std::pair("*.nii", "Diffusion Weighted Images for FSL")); m_FileExtensionsMap.insert(std::pair("*.fsl", "Diffusion Weighted Images for FSL")); m_FileExtensionsMap.insert(std::pair("*.fslgz", "Diffusion Weighted Images for FSL")); m_FileExtensionsMap.insert(std::pair("*.qbi", "Q-Ball Images")); m_FileExtensionsMap.insert(std::pair("*.hqbi", "Q-Ball Images")); m_FileExtensionsMap.insert(std::pair("*.dti", "Tensor Images")); m_FileExtensionsMap.insert(std::pair("*.hdti", "Tensor Images")); m_FileExtensionsMap.insert(std::pair("*.fib", "Fiber Bundle")); - m_FileExtensionsMap.insert(std::pair("*.vfib", "Fiber Bundle Polydata")); - m_FileExtensionsMap.insert(std::pair("*.vtk", "Fiber Bundle Polydata")); + m_FileExtensionsMap.insert(std::pair("*.vtk", "Fiber Bundle")); m_FileExtensionsMap.insert(std::pair("*.tbss", "TBSS data")); m_FileExtensionsMap.insert(std::pair("*.pf", "Planar Figure File")); - m_FileExtensionsMap.insert(std::pair("*.roi", "TBSS ROI data")); + m_FileExtensionsMap.insert(std::pair("*.roi", "TBSS ROI data")); m_SaveFileExtensionsMap.insert(std::pair("*.dwi", "Diffusion Weighted Images")); m_SaveFileExtensionsMap.insert(std::pair("*.hdwi", "Diffusion Weighted Images")); m_SaveFileExtensionsMap.insert(std::pair("*.nii", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair("*.fsl", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair("*.fslgz", "Diffusion Weighted Images for FSL")); m_SaveFileExtensionsMap.insert(std::pair("*.qbi", "Q-Ball Images")); m_SaveFileExtensionsMap.insert(std::pair("*.hqbi", "Q-Ball Images")); m_SaveFileExtensionsMap.insert(std::pair("*.dti", "Tensor Images")); m_SaveFileExtensionsMap.insert(std::pair("*.hdti", "Tensor Images")); m_SaveFileExtensionsMap.insert(std::pair("*.fib", "Fiber Bundle")); - m_SaveFileExtensionsMap.insert(std::pair("*.vfib", "Fiber Bundle Polydata")); - m_SaveFileExtensionsMap.insert(std::pair("*.vtk", "Fiber Bundle Polydata")); + m_SaveFileExtensionsMap.insert(std::pair("*.vtk", "Fiber Bundle")); m_SaveFileExtensionsMap.insert(std::pair("*.tbss", "TBSS data")); m_SaveFileExtensionsMap.insert(std::pair("*.pf", "Planar Figure File")); - m_SaveFileExtensionsMap.insert(std::pair("*.roi", "TBSS ROI data")); + m_SaveFileExtensionsMap.insert(std::pair("*.roi", "TBSS ROI data")); } void mitk::DiffusionImagingObjectFactory::RegisterIOFactories() { } void RegisterDiffusionImagingObjectFactory() { static bool oneDiffusionImagingObjectFactoryRegistered = false; if ( ! oneDiffusionImagingObjectFactoryRegistered ) { MITK_DEBUG << "Registering DiffusionImagingObjectFactory..." << std::endl; mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(mitk::DiffusionImagingObjectFactory::New()); oneDiffusionImagingObjectFactoryRegistered = true; } } diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkParticle.cpp b/Modules/DiffusionImaging/IODataStructures/mitkParticle.cpp similarity index 100% rename from Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkParticle.cpp rename to Modules/DiffusionImaging/IODataStructures/mitkParticle.cpp diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkParticle.h b/Modules/DiffusionImaging/IODataStructures/mitkParticle.h similarity index 100% rename from Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkParticle.h rename to Modules/DiffusionImaging/IODataStructures/mitkParticle.h diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkParticleGrid.cpp b/Modules/DiffusionImaging/IODataStructures/mitkParticleGrid.cpp similarity index 100% rename from Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkParticleGrid.cpp rename to Modules/DiffusionImaging/IODataStructures/mitkParticleGrid.cpp diff --git a/Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkParticleGrid.h b/Modules/DiffusionImaging/IODataStructures/mitkParticleGrid.h similarity index 100% rename from Modules/DiffusionImaging/IODataStructures/FiberBundle/mitkParticleGrid.h rename to Modules/DiffusionImaging/IODataStructures/mitkParticleGrid.h diff --git a/Modules/DiffusionImaging/Interactions/mitkFiberBundleInteractor.cpp b/Modules/DiffusionImaging/Interactions/mitkFiberBundleInteractor.cpp index d138099598..76c26d54c8 100644 --- a/Modules/DiffusionImaging/Interactions/mitkFiberBundleInteractor.cpp +++ b/Modules/DiffusionImaging/Interactions/mitkFiberBundleInteractor.cpp @@ -1,275 +1,275 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2007-12-11 14:46:19 +0100 (Di, 11 Dez 2007) $ Version: $Revision: 13129 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkFiberBundleInteractor.h" #include #include #include #include #include #include #include #include #include #include #include -#include +#include #include "mitkBaseRenderer.h" #include #include #include #include #include #include #include mitk::FiberBundleInteractor::FiberBundleInteractor(const char * type, DataNode* dataNode) : Interactor(type, dataNode), m_LastPosition(0) { m_LastPoint.Fill(0); } mitk::FiberBundleInteractor::~FiberBundleInteractor() {} void mitk::FiberBundleInteractor::SelectFiber(int position) { MITK_INFO << "mitk::FiberBundleInteractor::SelectFiber " << position; mitk::PointSet* pointSet = dynamic_cast(m_DataNode->GetData()); if (pointSet == NULL) return; if (pointSet->GetSize()<=0)//if List is empty, then no select of a point can be done! return; mitk::Point3D noPoint;//dummyPoint... not needed anyway noPoint.Fill(0); mitk::PointOperation* doOp = new mitk::PointOperation(OpSELECTPOINT, noPoint, position); if (m_UndoEnabled) { mitk::PointOperation* undoOp = new mitk::PointOperation(OpDESELECTPOINT, noPoint, position); OperationEvent *operationEvent = new OperationEvent(pointSet, doOp, undoOp); m_UndoController->SetOperationEvent(operationEvent); } pointSet->ExecuteOperation(doOp); } void mitk::FiberBundleInteractor::DeselectAllFibers() { MITK_INFO << "mitk::FiberBundleInteractor::DeselectAllFibers "; mitk::PointSet* pointSet = dynamic_cast(m_DataNode->GetData()); if (pointSet == NULL) return; mitk::PointSet::DataType *itkPointSet = pointSet->GetPointSet(); mitk::PointSet::PointsContainer::Iterator it, end; end = itkPointSet->GetPoints()->End(); for (it = itkPointSet->GetPoints()->Begin(); it != end; it++) { int position = it->Index(); PointSet::PointDataType pointData = {0, false, PTUNDEFINED}; itkPointSet->GetPointData(position, &pointData); if ( pointData.selected )//then declare an operation which unselects this point; UndoOperation as well! { mitk::Point3D noPoint; noPoint.Fill(0); mitk::PointOperation* doOp = new mitk::PointOperation(OpDESELECTPOINT, noPoint, position); if (m_UndoEnabled) { mitk::PointOperation* undoOp = new mitk::PointOperation(OpSELECTPOINT, noPoint, position); OperationEvent *operationEvent = new OperationEvent(pointSet, doOp, undoOp); m_UndoController->SetOperationEvent(operationEvent); } pointSet->ExecuteOperation(doOp); } } } float mitk::FiberBundleInteractor::CanHandleEvent(StateEvent const* stateEvent) const //go through all points and check, if the given Point lies near a line { float returnValue = 0; mitk::PositionEvent const *posEvent = dynamic_cast (stateEvent->GetEvent()); //checking if a keyevent can be handled: if (posEvent == NULL) { //check, if the current state has a transition waiting for that key event. if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL) { return 0.5; } else { return 0; } } //Mouse event handling: //on MouseMove do nothing! reimplement if needed differently if (stateEvent->GetEvent()->GetType() == mitk::Type_MouseMove) { return 0; } //if the event can be understood and if there is a transition waiting for that event if (this->GetCurrentState()->GetTransition(stateEvent->GetId())!=NULL) { returnValue = 0.5;//it can be understood } //check on the right data-type - mitk::FiberBundle* bundle = dynamic_cast(m_DataNode->GetData()); + mitk::FiberBundleX* bundle = dynamic_cast(m_DataNode->GetData()); if (bundle == NULL) return 0; return 0.5; } bool mitk::FiberBundleInteractor::ExecuteAction( Action* action, mitk::StateEvent const* stateEvent ) { bool ok = false;//for return type bool //checking corresponding Data; has to be a PointSet or a subclass - mitk::FiberBundle* bundle = dynamic_cast(m_DataNode->GetData()); + mitk::FiberBundleX* bundle = dynamic_cast(m_DataNode->GetData()); if (bundle == NULL) return false; // Get Event and extract renderer const Event *event = stateEvent->GetEvent(); BaseRenderer *renderer = NULL; vtkRenderWindow *renderWindow = NULL; vtkRenderWindowInteractor *renderWindowInteractor = NULL; vtkRenderer *currentVtkRenderer = NULL; vtkCamera *camera = NULL; if ( event != NULL ) { renderer = event->GetSender(); if ( renderer != NULL ) { renderWindow = renderer->GetRenderWindow(); if ( renderWindow != NULL ) { renderWindowInteractor = renderWindow->GetInteractor(); if ( renderWindowInteractor != NULL ) { currentVtkRenderer = renderWindowInteractor ->GetInteractorStyle()->GetCurrentRenderer(); if ( currentVtkRenderer != NULL ) { camera = currentVtkRenderer->GetActiveCamera(); } } } } } /*Each case must watch the type of the event!*/ switch (action->GetActionId()) { case AcCHECKHOVERING: { QApplication::restoreOverrideCursor(); // Re-enable VTK interactor (may have been disabled previously) if ( renderWindowInteractor != NULL ) { renderWindowInteractor->Enable(); } const DisplayPositionEvent *dpe = dynamic_cast< const DisplayPositionEvent * >( stateEvent->GetEvent() ); // Check if we have a DisplayPositionEvent if ( dpe != NULL ) { // Check if an object is present at the current mouse position DataNode *pickedNode = dpe->GetPickedObjectNode(); if ( pickedNode != m_DataNode ) - { + { // if(pickedNode == 0) // MITK_INFO << "picked node is NULL, no hovering"; // else // MITK_INFO << "wrong node: " << pickedNode; this->HandleEvent( new StateEvent( EIDNOFIGUREHOVER ) ); ok = true; break; } m_CurrentPickedPoint = dpe->GetWorldPosition(); m_CurrentPickedDisplayPoint = dpe->GetDisplayPosition(); QApplication::setOverrideCursor(Qt::UpArrowCursor); this->HandleEvent( new StateEvent( EIDFIGUREHOVER ) ); } ok = true; break; } break; // case AcSELECTPICKEDOBJECT: // MITK_INFO << "FiberBundleInteractor AcSELECTPICKEDOBJECT"; // break; // case AcDESELECTALL: // MITK_INFO << "FiberBundleInteractor AcDESELECTALL"; // break; case AcREMOVE: { MITK_INFO << "picking fiber at " << m_CurrentPickedPoint; // QmitkStdMultiWidgetEditor::Pointer multiWidgetEditor; // multiWidgetEditor->GetStdMultiWidget()->GetRenderWindow1()->GetRenderer()->GetSliceNavigationController()->SelectSliceByPoint( // m_CurrentPickedPoint); BaseRenderer* renderer = mitk::BaseRenderer::GetByName("stdmulti.widget1"); renderer->GetSliceNavigationController()->SelectSliceByPoint( m_CurrentPickedPoint); renderer = mitk::BaseRenderer::GetByName("stdmulti.widget2"); renderer->GetSliceNavigationController()->SelectSliceByPoint( m_CurrentPickedPoint); renderer = mitk::BaseRenderer::GetByName("stdmulti.widget3"); renderer->GetSliceNavigationController()->SelectSliceByPoint( m_CurrentPickedPoint); // mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } break; default: return Superclass::ExecuteAction( action, stateEvent ); } return ok; } diff --git a/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper2D.cpp b/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper2D.cpp deleted file mode 100644 index 3928160bfc..0000000000 --- a/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper2D.cpp +++ /dev/null @@ -1,357 +0,0 @@ -/* - * mitkFiberBundleMapper2D.cpp - * mitk-all - * - * Created by HAL9000 on 1/17/11. - * Copyright 2011 __MyCompanyName__. All rights reserved. - * - */ - -#include "mitkFiberBundleMapper2D.h" -#include -#include "mitkFiberBundleMapper3D.h" - -#include -#include -#include -#include -//#include - -//#include -#include -#include -#include -#include -#include -#include -#include -#include - -//#include -#include -#include - -#include -#include -#include - -#include -#include - -mitk::FiberBundleMapper2D::FiberBundleMapper2D() -{ - - -} - -mitk::FiberBundleMapper2D::~FiberBundleMapper2D() -{ -} - - -const mitk::FiberBundle* mitk::FiberBundleMapper2D::GetInput() -{ - return dynamic_cast ( GetData() ); -} - - - -void mitk::FiberBundleMapper2D::Update(mitk::BaseRenderer * renderer) -{ - - if ( !this->IsVisible( renderer ) ) - { - return; - } - - - // Calculate time step of the input data for the specified renderer (integer value) - // this method is implemented in mitkMapper - this->CalculateTimeStep( renderer ); - - //check if updates occured in the node or on the display - FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); - const DataNode *node = this->GetDataNode(); - if ( (localStorage->m_LastUpdateTime < node->GetMTime()) - || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified? - || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) - { - // MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName(); - this->GenerateDataForRenderer( renderer ); - } - - if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning) - { - - this->UpdateShaderParameter(renderer); - - } - -} - -void mitk::FiberBundleMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer) -{ - FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); - // MITK_INFO << "uSERWAAAAAAAS, da shader brauchat a poor neue zoin"; - //get information about current position of views - mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController(); - mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry(); - - //generate according cutting planes based on the view position - float sliceN[3], planeOrigin[3]; - - - // since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates - - - planeOrigin[0] = (float) planeGeo->GetOrigin()[0]; - planeOrigin[1] = (float) planeGeo->GetOrigin()[1]; - planeOrigin[2] = (float) planeGeo->GetOrigin()[2]; - - sliceN[0] = planeGeo->GetNormal()[0]; - sliceN[1] = planeGeo->GetNormal()[1]; - sliceN[2] = planeGeo->GetNormal()[2]; - - - float tmp1 = planeOrigin[0] * sliceN[0]; - float tmp2 = planeOrigin[1] * sliceN[1]; - float tmp3 = planeOrigin[2] * sliceN[2]; - float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector - - - float plane1[4]; - plane1[0] = sliceN[0]; - plane1[1] = sliceN[1]; - plane1[2] = sliceN[2]; - plane1[3] = d1; - - float thickness = 2.0; - if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness)) - MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR"; - - - bool fiberfading = false; - if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading)) - MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR"; - - - int fiberfading_i = 1; - if (!fiberfading) - fiberfading_i = 0; - - - localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1); - localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness); - localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1, &fiberfading_i); - - -} - -// ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE. -// vtkActors and Mappers are feeded here -void mitk::FiberBundleMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) -{ - - //the handler of local storage gets feeded in this method with requested data for related renderwindow - FBLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); - - //this procedure is depricated, - //not needed after initializaton anymore - mitk::DataNode* node = this->GetDataNode(); - if ( node == NULL ) - { - MITK_INFO << "check DATANODE: ....[Fail] "; - return; - } - /////////////////////////////////// - - - - - - - mitk::FiberBundleMapper3D::Pointer FBMapper3D = dynamic_cast< mitk::FiberBundleMapper3D* > (node->GetMapper( 2 )); - if ( FBMapper3D->GetInput() == NULL ) - { - MITK_INFO << "check FBMapper3D Input: ....[Fail] "; - return; - } - - - - - //feed local storage with data we want to visualize - // localStorage->m_SlicedResult = FBMapper3D->GetCut(planeOrigin, planeN, cutParams); - // localStorage->m_SlicedResult = FBMapper3D->GetVtkFBPolyDataMapper(); - localStorage->m_SlicedResult = (vtkPolyData*) FBMapper3D->getVtkFiberBundleMapper()->GetInputAsDataSet(); - //MITK_INFO << renderer->GetName() << " OutputPoints#: " << localStorage->m_SlicedResult->GetNumberOfPoints(); - - - vtkSmartPointer lut = vtkLookupTable::New(); - lut->Build(); - localStorage->m_PointMapper->SetScalarModeToUsePointFieldData(); - //m_VtkFiberDataMapperGL->SelectColorArray("FaColors"); - localStorage->m_PointMapper->SelectColorArray("ColorValues"); - localStorage->m_PointMapper->SetLookupTable(lut); //apply the properties after the slice was set - //this->ApplyProperties( renderer ); - - //setup the camera according to the actor with zooming/panning etc. - // this->AdjustCamera( renderer, planeGeo ); - - - - // feed the vtk fiber mapper with point data ...TODO do in constructor - localStorage->m_PointMapper->SetInput(localStorage->m_SlicedResult); // in optimized version, mapper is feeded by localStorage->m_cutter->GetOutput(); - localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper); - localStorage->m_PointActor->GetProperty()->ShadingOn(); - - // Applying shading properties - { - //Superclass::ApplyProperties( ls->m_Actor, renderer ) ; - // VTK Properties - //ApplyMitkPropertiesToVtkProperty( this->GetDataNode(), ls->m_Actor->GetProperty(), renderer ); - // Shaders - mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime); - } - - - - this->UpdateShaderParameter(renderer); - - - // We have been modified => save this for next Update() - localStorage->m_LastUpdateTime.Modified(); - - -} - - -vtkProp* mitk::FiberBundleMapper2D::GetVtkProp(mitk::BaseRenderer *renderer) -{ - - //MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)"; - this->Update(renderer); - return m_LSH.GetLocalStorage(renderer)->m_PointActor; - -} - - -void mitk::FiberBundleMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) -{ //add shader to datano - - - //####### load shader from file ######### - QString applicationDir = QCoreApplication::applicationDirPath(); - MITK_INFO << "pathAppdir: " << QCoreApplication::applicationDirPath().toStdString().c_str(); - - - if (applicationDir.endsWith("bin")) - applicationDir.append("/"); - else if (applicationDir.endsWith("MacOS")) - { - //on osx, check if path for installer or MITK development is needed - applicationDir.append("/"); - QFile f( applicationDir+"FiberTrackingLUTBaryCoords.bin" ); - if( !f.exists() ) // if file does not exist, then look in MITK development build directory - applicationDir.append("../../../"); - }else - applicationDir.append("\\..\\"); - -// applicationDir.append("/"); //directory to look when building installer - - mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false ); - mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository(); - -// std::string filepath = mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml"); -// if ( filepath.empty() ) -// { -// applicationDir = QCoreApplication::applicationDirPath(); -// applicationDir.append("/../../"); //directory to look when developing in MITK -// mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false ); -// filepath = mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml"); - -// if ( filepath.empty() ) -// { //for windows systems -// applicationDir = QCoreApplication::applicationDirPath(); -// applicationDir.append("\\..\\"); -// mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false ); - -// } - -// } - - - - shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml")); - - - - //#################################################################### - node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping")); - mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite); - - - //add other parameters to propertylist - node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite ); - node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite ); - - - Superclass::SetDefaultProperties(node, renderer, overwrite); -} - - - - - -// following methods are essential, they actually call the GetVtkProp() method -// which returns the desired actors -void mitk::FiberBundleMapper2D::MitkRenderOverlay(BaseRenderer* renderer) -{ - // MITK_INFO << "FiberBundleMapper2D MitkRenderOVerlay(renderer)"; - if ( this->IsVisible(renderer)==false ) - return; - - if ( this->GetVtkProp(renderer)->GetVisibility() ) - { - this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer()); - } -} - -void mitk::FiberBundleMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer) -{ - // MITK_INFO << "FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)"; - if ( this->IsVisible( renderer )==false ) - return; - - if ( this->GetVtkProp(renderer)->GetVisibility() ) - this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() ); -} -void mitk::FiberBundleMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer) -{ - // MITK_INFO << "FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)"; - if ( this->IsVisible(renderer)==false ) - return; - - //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer??? - if ( this->GetVtkProp(renderer)->GetVisibility() ) - this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer()); - -} -void mitk::FiberBundleMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer) -{ - // MITK_INFO << "FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)"; - if(IsVisible(renderer)==false) - return; - - //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer??? - if ( GetVtkProp(renderer)->GetVisibility() ) - this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer()); - -} - -mitk::FiberBundleMapper2D::FBLocalStorage::FBLocalStorage() -{ - m_PointActor = vtkSmartPointer::New(); - m_PointMapper = vtkSmartPointer::New(); - -} diff --git a/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper2D.h b/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper2D.h deleted file mode 100644 index c882b75e04..0000000000 --- a/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper2D.h +++ /dev/null @@ -1,118 +0,0 @@ -/*========================================================================= - - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2010-09-26 20:40:22 +0200 (So, 26 Sep 2010) $ - Version: $Revision$ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ - -#ifndef FIBERBUNDLEMAPPER2D_H_HEADER_INCLUDED -#define FIBERBUNDLEMAPPER2D_H_HEADER_INCLUDED - -//MITK Rendering -#include -#include -//#include "MitkDiffusionImagingExports.h" - -#include -#include -#include - - -//#include "FBLocalStorage.h" - -class vtkActor; -//class vtkPropAssembly; //lets see if we need it -class mitkBaseRenderer; -class vtkPolyDataMapper; -class vtkCutter; -class vtkPlane; -class vtkPolyData; - - - -namespace mitk { - - - class FiberBundleMapper2D : public VtkMapper2D - { - - public: - mitkClassMacro(FiberBundleMapper2D, VtkMapper2D); - itkNewMacro(Self); - const mitk::FiberBundle* GetInput(); - - - /** \brief Checks whether this mapper needs to update itself and generate - * data. */ - virtual void Update(mitk::BaseRenderer * renderer); - - - static void SetDefaultProperties(DataNode* node, BaseRenderer* renderer = NULL, bool overwrite = false ); - - - //### methods of MITK-VTK rendering pipeline - virtual vtkProp* GetVtkProp(mitk::BaseRenderer* renderer); - virtual void MitkRenderOverlay(BaseRenderer* renderer); - virtual void MitkRenderOpaqueGeometry(BaseRenderer* renderer); - virtual void MitkRenderTranslucentGeometry(BaseRenderer* renderer); - virtual void MitkRenderVolumetricGeometry(BaseRenderer* renderer); - //### end of methods of MITK-VTK rendering pipeline - - - class FBLocalStorage : public mitk::Mapper::BaseLocalStorage - { - public: - /** \brief Point Actor of a 2D render window. */ - vtkSmartPointer m_PointActor; - /** \brief Point Mapper of a 2D render window. */ - vtkSmartPointer m_PointMapper; - /** \brief Point Actor of a 2D render window. */ - // vtkSmartPointer m_TubeActor; //not in use right now - /** \brief Point Mapper of a 2D render window. */ - // vtkSmartPointer m_TubeMapper; //not in use right now - /** \brief Current slice of a 2D render window. */ - // vtkSmartPointer m_cutter; //needed later when optimized 2D mapper - vtkSmartPointer m_SlicingPlane; //needed later when optimized 2D mapper - vtkSmartPointer m_SlicedResult; //might be depricated in optimized 2D mapper - - /** \brief Timestamp of last update of stored data. */ - itk::TimeStamp m_LastUpdateTime; - /** \brief Constructor of the local storage. Do as much actions as possible in here to avoid double executions. */ - FBLocalStorage(); //if u copy&paste from this 2Dmapper, be aware that the implementation of this constructor is in the cpp file - - ~FBLocalStorage() - { - } - }; - - /** \brief This member holds all three LocalStorages for the three 2D render windows. */ - mitk::Mapper::LocalStorageHandler m_LSH; - - - - protected: - FiberBundleMapper2D(); - virtual ~FiberBundleMapper2D(); - - /** Does the actual resampling, without rendering. */ - virtual void GenerateDataForRenderer(mitk::BaseRenderer*); - - void UpdateShaderParameter(mitk::BaseRenderer*); - - - }; - - -}//end namespace - -#endif \ No newline at end of file diff --git a/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper3D.cpp b/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper3D.cpp deleted file mode 100644 index 61891c55b4..0000000000 --- a/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper3D.cpp +++ /dev/null @@ -1,758 +0,0 @@ -/*========================================================================= - - Program: Medical Imaging & Interaction Toolkit - Language: C++ - Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $ - Version: $Revision: 17179 $ - - Copyright (c) German Cancer Research Center, Division of Medical and - Biological Informatics. All rights reserved. - See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. - - =========================================================================*/ - - -#include -#include "mitkFiberBundleMapper3D.h" - - -#include -#include -#include -#include -#include -#include -#include - - -#include -#include -#include -#include - -#include "mitkFiberBundleInteractor.h" -#include - -//template -mitk::FiberBundleMapper3D::FiberBundleMapper3D() -: m_VtkFiberDataMapperGL(vtkOpenGLPolyDataMapper::New()) -, m_FiberActor(vtkOpenGLActor::New()) -, m_FiberAssembly(vtkPropAssembly::New()) -, m_vtkTubeMapper(vtkOpenGLPolyDataMapper::New()) -, m_tubes(vtkTubeFilter::New()) -, m_TubeActor(vtkOpenGLActor::New()) -{ - - -} - -mitk::FiberBundleMapper3D::~FiberBundleMapper3D() -{ - -} - - -const mitk::FiberBundle* mitk::FiberBundleMapper3D::GetInput() -{ - //MITK_INFO << "FiberBundleMapper3D GetInput()" ; - - return static_cast ( GetData() ); -} - -vtkOpenGLPolyDataMapper* mitk::FiberBundleMapper3D::getVtkFiberBundleMapper() -{ - return m_VtkFiberDataMapperGL; -} - -/* - This method is called once the mapper gets new input, - for UI rotation or changes in colorcoding this method is NOT called - */ -void mitk::FiberBundleMapper3D::GenerateData() -{ - /* ######## FIBER PREPARATION START ######### */ - //get fiberbundle - mitk::FiberBundle::Pointer PFiberBundle = dynamic_cast< mitk::FiberBundle* > (this->GetData()); - - //get groupFiberBundle, which is a datastructure containing single fibers - mitk::FiberBundle::FiberGroupType::Pointer groupFiberBundle = PFiberBundle->GetGroupFiberBundle(); - - //extractn single fibers - //in the groupFiberBundle all smartPointers to single fibers are stored in in a ChildrenList - mitk::FiberBundle::ChildrenListType * FiberList; - FiberList = groupFiberBundle->GetChildren(); - - /* ######## FIBER PREPARATION END ######### */ - - /* ######## VTK FIBER REPRESENTATION ######## */ - //create a vtkPoints object and store the all the brainFiber points in it - - vtkSmartPointer vtkSmoothPoints = vtkPoints::New(); //in smoothpoints the interpolated points representing a fiber are stored. - - //in vtkcells all polylines are stored, actually all id's of them are stored - vtkSmartPointer vtkSmoothCells = vtkCellArray::New(); //cellcontainer for smoothed lines - - //in some cases a fiber includes just 1 point, so put it in here - vtkSmartPointer vtkVrtxs = vtkCellArray::New(); - - //colors and alpha value for each single point, RGBA = 4 components - vtkSmartPointer colorsT = vtkUnsignedCharArray::New(); - colorsT->SetNumberOfComponents(4); - colorsT->SetName("ColorValues"); - - vtkSmartPointer faColors = vtkDoubleArray::New(); - faColors->SetName("FaColors"); - - vtkSmartPointer tubeRadius = vtkDoubleArray::New(); - tubeRadius->SetName("TubeRadius"); - - - // iterate through FiberList - for(mitk::FiberBundle::ChildrenListType::iterator itLst = FiberList->begin(); - itLst != FiberList->end(); - ++itLst) - { - //all points are stored in one vtkpoints list, soooooooo that the lines find their point id to start and end we need some kind of helper index who monitors the current ids for a polyline - //unsigned long pntIdxHelper = vtkpointsDTI->GetNumberOfPoints(); - - // lists output is SpatialObject, we know we have DTITubeSpacialObjects - // dynamic cast only likes pointers, no smartpointers, so each dsmartpointer has membermethod .GetPointer() - itk::SpatialObject<3>::Pointer tmp_fbr; - tmp_fbr = *itLst; - mitk::FiberBundle::DTITubeType::Pointer dtiTract = dynamic_cast< mitk::FiberBundle::DTITubeType * > (tmp_fbr.GetPointer()); - if (dtiTract.IsNull()) { - return; } - - //get list of points - int fibrNrPnts = dtiTract->GetNumberOfPoints(); - mitk::FiberBundle::DTITubeType::PointListType dtiPntList = dtiTract->GetPoints(); - - //MITK_INFO << "REAL AMOUNT OF FIBERS: " << fibrNrPnts; - - vtkSmartPointer vtkpointsDTI = vtkPoints::New(); - - if (fibrNrPnts <= 0) { //this should never occour! but who knows - MITK_INFO << "HyperERROR in fiberBundleMapper3D.cpp ...no point in fiberBundle!!! .. check ur trackingAlgorithm"; - continue; - } - - - ///////PROCESS ON FIBERS//////// - for (int i=0; i1 - PFiberBundle->GetGeometry()->IndexToWorld(indexPnt, worldPnt); - double worldFbrPnt[3] = {worldPnt[0], worldPnt[1], worldPnt[2]}; - vtkpointsDTI->InsertNextPoint(worldFbrPnt); - } - - //MITK_INFO << "REDUCED AMOUNT OF FIBERS: " << vtkpointsDTI->GetNumberOfPoints(); - - ////POINTS OF DTI ARE READY FOR FUTHER VTK PROCESSING//// - } - - - /////PROCESS POLYLINE SMOOTHING///// - vtkSmartPointer xSpline = vtkKochanekSpline::New(); - vtkSmartPointer ySpline = vtkKochanekSpline::New(); - vtkSmartPointer zSpline = vtkKochanekSpline::New(); - - vtkSmartPointer spline = vtkParametricSpline::New(); - spline->SetXSpline(xSpline); - spline->SetYSpline(ySpline); - spline->SetZSpline(zSpline); - spline->SetPoints(vtkpointsDTI); - - - vtkSmartPointer functionSource = vtkParametricFunctionSource::New(); - functionSource->SetParametricFunction(spline); - functionSource->SetUResolution(200); - functionSource->SetVResolution(200); - functionSource->SetWResolution(200); - functionSource->Update(); - - - - vtkPolyData* outputFunction = functionSource->GetOutput(); - vtkPoints* tmpSmoothPnts = outputFunction->GetPoints(); //smoothPoints of current fiber - - vtkSmartPointer smoothLine = vtkPolyLine::New(); - smoothLine->GetPointIds()->SetNumberOfIds(tmpSmoothPnts->GetNumberOfPoints()); -// MITK_INFO << "SMOOTHED AMOUNT OF POINTS:" << tmpSmoothPnts->GetNumberOfPoints(); - - - /////CREATE SMOOTH POLYLINE OBJECT//// - /////MANAGE LINE AND CORRELATED POINTS///// - int pointHelperCnt = vtkSmoothPoints->GetNumberOfPoints(); //also put current points into global smooth pointcontainer - int nrSmPnts = tmpSmoothPnts->GetNumberOfPoints(); - tubeRadius->SetNumberOfTuples(nrSmPnts); - double tbradius = 1;//default value for radius - - for(int ism=0; ismGetPointIds()->SetId(ism, ism+pointHelperCnt); - vtkSmoothPoints->InsertNextPoint(tmpSmoothPnts->GetPoint(ism)); - - // MITK_INFO << "LinePntID: " << ism << " linked to: " << ism+pointHelperCnt << " val: " << tmpSmoothPnts->GetPoint(ism)[0] << " " << tmpSmoothPnts->GetPoint(ism)[1] << " " << tmpSmoothPnts->GetPoint(ism)[2]; - tubeRadius->SetTuple1(ism,tbradius); //tuple with 1 argument - - - //colorcoding orientation based - unsigned char rgba[4] = {0,0,0,0}; - if (ism < nrSmPnts-1 && ism>0) - { - - // MITK_INFO << "inbetween fiber, at position:" << ism; -// //nimm nur diff1 - vnl_vector_fixed< double, 3 > tmpPntvtk(tmpSmoothPnts->GetPoint(ism)[0], tmpSmoothPnts->GetPoint(ism)[1],tmpSmoothPnts->GetPoint(ism)[2]); - vnl_vector_fixed< double, 3 > nxttmpPntvtk(tmpSmoothPnts->GetPoint(ism+1)[0], tmpSmoothPnts->GetPoint(ism+1)[1], tmpSmoothPnts->GetPoint(ism+1)[2]); - vnl_vector_fixed< double, 3 > prevtmpPntvtk(tmpSmoothPnts->GetPoint(ism-1)[0], tmpSmoothPnts->GetPoint(ism-1)[1], tmpSmoothPnts->GetPoint(ism-1)[2]); - - vnl_vector_fixed< double, 3 > diff1; - diff1 = tmpPntvtk - nxttmpPntvtk; - diff1.normalize(); - - vnl_vector_fixed< double, 3 > diff2; - diff2 = tmpPntvtk - prevtmpPntvtk; - diff2.normalize(); - - vnl_vector_fixed< double, 3 > diff; - diff = (diff1 - diff2)/2.0; - - - rgba[0] = (unsigned char) (255.0 * std::abs(diff[0])); - rgba[1] = (unsigned char) (255.0 * std::abs(diff[1])); - rgba[2] = (unsigned char) (255.0 * std::abs(diff[2])); - rgba[3] = (unsigned char) (255.0); - - - - } else if(ism==0) { - //explicit handling of startpoint of line - - //nimm nur diff1 - vnl_vector_fixed< double, 3 > tmpPntvtk(tmpSmoothPnts->GetPoint(ism)[0], tmpSmoothPnts->GetPoint(ism)[1],tmpSmoothPnts->GetPoint(ism)[2]); - vnl_vector_fixed< double, 3 > nxttmpPntvtk(tmpSmoothPnts->GetPoint(ism+1)[0], tmpSmoothPnts->GetPoint(ism+1)[1], tmpSmoothPnts->GetPoint(ism+1)[2]); - - - vnl_vector_fixed< double, 3 > diff1; - diff1 = tmpPntvtk - nxttmpPntvtk; - diff1.normalize(); - - rgba[0] = (unsigned char) (255.0 * std::abs(diff1[0])); - rgba[1] = (unsigned char) (255.0 * std::abs(diff1[1])); - rgba[2] = (unsigned char) (255.0 * std::abs(diff1[2])); - rgba[3] = (unsigned char) (255.0); - -// MITK_INFO << "first point color: " << rgba[0] << " " << rgba[1] << " " << rgba[2]; - - - } else if(ism==nrSmPnts-1) { -// last point in fiber - - // nimm nur diff2 - vnl_vector_fixed< double, 3 > tmpPntvtk(tmpSmoothPnts->GetPoint(ism)[0], tmpSmoothPnts->GetPoint(ism)[1],tmpSmoothPnts->GetPoint(ism)[2]); - vnl_vector_fixed< double, 3 > prevtmpPntvtk(tmpSmoothPnts->GetPoint(ism-1)[0], tmpSmoothPnts->GetPoint(ism-1)[1], tmpSmoothPnts->GetPoint(ism-1)[2]); - - vnl_vector_fixed< double, 3 > diff2; - diff2 = tmpPntvtk - prevtmpPntvtk; - diff2.normalize(); - - rgba[0] = (unsigned char) (255.0 * std::abs(diff2[0])); - rgba[1] = (unsigned char) (255.0 * std::abs(diff2[1])); - rgba[2] = (unsigned char) (255.0 * std::abs(diff2[2])); - rgba[3] = (unsigned char) (255.0); -// -// MITK_INFO << "last point color: " << rgba[0] << " " << rgba[1] << " " << rgba[2]; - } //end colorcoding -// - colorsT->InsertNextTupleValue(rgba); - - }//end of smoothline - - ///////smooth Fiber ready//////// - vtkSmoothCells->InsertNextCell(smoothLine); - } - - //vtkpointsDTI->Delete();//points are not needed anymore TODO uncomment! - - - /* - - //get FA value ... for that FA has to be interpolated as well as DTItracktLine - float faVal = tmpFiberPntLst.GetField(mitk::FiberBundle::DTITubePointType::FA); - //use insertNextValue cuz FA Values are reperesented as a single number (1 Tuple containing 1 parameter) - faColors->InsertNextValue((double) faVal); - - */ - //vtkcells->InitTraversal(); - - // Put points and lines together in one polyData structure - vtkSmartPointer polyData = vtkPolyData::New(); - polyData->SetPoints(vtkSmoothPoints); - polyData->SetLines(vtkSmoothCells); - - if (vtkVrtxs->GetSize() > 0) { - polyData->SetVerts(vtkVrtxs); - } - polyData->GetPointData()->AddArray(colorsT); - //polyData->GetPointData()->AddArray(faColors); - //polyData->GetPointData()->AddArray(tubeRadius); - - - vtkSmartPointer lut = vtkLookupTable::New(); - lut->Build(); - - - // m_VtkFiberDataMapperGL = vtkOpenGLPolyDataMapper::New(); - m_VtkFiberDataMapperGL->SetInput(polyData); - m_VtkFiberDataMapperGL->ScalarVisibilityOn(); - - m_VtkFiberDataMapperGL->SetScalarModeToUsePointFieldData(); - //m_VtkFiberDataMapperGL->SelectColorArray("FaColors"); - m_VtkFiberDataMapperGL->SelectColorArray("ColorValues"); - m_VtkFiberDataMapperGL->SetLookupTable(lut); - - - //m_FiberActor = vtkOpenGLActor::New(); - m_FiberActor->SetMapper(m_VtkFiberDataMapperGL); - m_FiberActor->GetProperty()->SetOpacity(1.0); - m_FiberActor->GetProperty()->SetPointSize(4.0f); - // m_FiberActor->GetProperty()->SetColor(255.0, 0.0, 0.0); - - - - m_FiberAssembly->AddPart(m_FiberActor); - - //setting color and opacity in the fiberActor itself is not recommended - //here cuz color and opacity of dataNode will be considered in GetData(baserenderer*) anyway - this->GetDataNode()->SetColor(255.0,0,0); - this->GetDataNode()->SetOpacity(1.0); - - -} - - - - -//template -void mitk::FiberBundleMapper3D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) -{ - - - - // nodeCC = 1 ... ROI colorcoding - // 2 ... orientation colorcoding - // 3 ... FA colorcoding - - - int nodeCC; - bool isCCd = this->GetDataNode()->GetPropertyValue("ColorCoding", nodeCC); - if ( isCCd && nodeCC == 1 ) { - - - //get color and opacity from DataNode - int tmpline; - - bool isLineProp = this->GetDataNode()->GetPropertyValue("LineWidth",tmpline); - - bool isPointRep; - bool successPointProp = this->GetDataNode()->GetPropertyValue("RepPoints", isPointRep); - float pointSize; - bool successPointSize = this->GetDataNode()->GetPropertyValue("pointSize", pointSize); - - if (isLineProp) { - m_FiberActor->GetProperty()->SetLineWidth(tmpline); - } - - if(isPointRep) { - m_FiberActor->GetProperty()->SetRepresentationToPoints(); - m_FiberActor->GetProperty()->SetPointSize(pointSize); - } - - } else if (isCCd && nodeCC == 2) { - float tmpopa; - this->GetDataNode()->GetOpacity(tmpopa, NULL); - m_FiberActor->GetProperty()->SetOpacity((double) tmpopa); - - } else if (isCCd && nodeCC == 3) { - - float temprgb[3]; - this->GetDataNode()->GetColor( temprgb, NULL ); - double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] }; - m_FiberActor->GetProperty()->SetColor(trgb); - - if(m_VtkFiberDataMapperGL->GetScalarVisibility()) //can be 0 or 1, for scalarVis On or Off - { - m_VtkFiberDataMapperGL->ScalarVisibilityOff(); - } - - - - } else if (isCCd && nodeCC == 4) { - - if(!m_VtkFiberDataMapperGL->GetScalarVisibility()) //can be 0 or 1, for scalarVis On or Off - { - m_VtkFiberDataMapperGL->ScalarVisibilityOn(); - } - m_VtkFiberDataMapperGL->SelectColorArray("ColorValues"); - - } else if (isCCd && nodeCC == 5){ - - if(!m_VtkFiberDataMapperGL->GetScalarVisibility()) //if visibility is off, switch it on - { - m_VtkFiberDataMapperGL->ScalarVisibilityOn(); - } - m_VtkFiberDataMapperGL->SelectColorArray("FaColors"); - - } else if (isCCd && nodeCC == 6){ - //orientationbased colorcoding + FA as opacity - //get FA out of polydata, which is saved in faColor vtkDoubleArray - - vtkPolyData *tmpPolyData = m_VtkFiberDataMapperGL->GetInput(); - vtkPointData *tmpPointData = tmpPolyData->GetPointData(); - - - - int hasAr = tmpPointData->HasArray("FaColors"); - if(!hasAr) - return; - - vtkDoubleArray *tmpFAarray = (vtkDoubleArray*)(tmpPointData->GetArray("FaColors")) ; - - /*for(int i=0; iGetNumberOfTuples(); i++) - { - - double *tmpTuple; - tmpFAarray->GetTuple(i, tmpTuple); - - for(int j=0; jGetNumberOfComponents(); j++) - { - MITK_INFO << "FA Value: at index " << i << ": " << tmpTuple[j]; - } - - - } - */ - - //since we have our FA values, lets replace the alpha values in colorT - //we know each 4th entry is a A value of RGBA - int hasArCV = tmpPointData->HasArray("ColorValues"); - if(!hasArCV) - return; - - vtkUnsignedCharArray *colorsTtmp = dynamic_cast (tmpPointData->GetArray("ColorValues")); - - for(int i=0; iGetNumberOfTuples(); i++) - { - - //double *tmpTupleCV = colorsTtmp->GetTuple4(i); - double tmpTupleFA = tmpFAarray->GetTuple1(i); - tmpTupleFA = tmpTupleFA * 255.0; - - colorsTtmp->SetComponent(i,3, tmpTupleFA ); - - // MITK_INFO << "----" << i; - //MITK_INFO << tmpTupleCV[0]; - //MITK_INFO << tmpTupleCV[1]; - //MITK_INFO << tmpTupleCV[2]; - //MITK_INFO << tmpTupleCV[3]; - //double *test = m_VtkFiberDataMapperGL->GetInput()->GetPointData()->GetArray("ColorValues")->GetTuple4(i); - //MITK_INFO << test[0]; - //MITK_INFO << test[1]; - //MITK_INFO << test[2]; - //MITK_INFO << test[3]; - - - } - - m_VtkFiberDataMapperGL->SelectColorArray(""); - m_VtkFiberDataMapperGL->SelectColorArray("ColorValues"); - - - } else if (isCCd && nodeCC == 7){ - - vtkPolyData *tmpPolyData = m_VtkFiberDataMapperGL->GetInput(); - vtkPointData *tmpPointData = tmpPolyData->GetPointData(); - int hasArCV = tmpPointData->HasArray("ColorValues"); - if(!hasArCV) - return; - - vtkUnsignedCharArray *colorsTtmp = dynamic_cast (tmpPointData->GetArray("ColorValues")); - - for(int i=0; iGetNumberOfTuples(); i++) - { - - double tmpTupleFA = 255.0; - colorsTtmp->SetComponent(i,3, tmpTupleFA ); - } - m_VtkFiberDataMapperGL->SelectColorArray(""); - m_VtkFiberDataMapperGL->SelectColorArray("ColorValues"); - - - } else if (isCCd && nodeCC == 8) { - /* something is still missing to activate smoothing or make it work.... */ - if (!renderer->GetRenderWindow()->GetLineSmoothing()) { - renderer->GetRenderWindow()->SetLineSmoothing(1); - renderer->GetRenderWindow()->Modified(); - } - if (!renderer->GetRenderWindow()->GetPointSmoothing()) { - renderer->GetRenderWindow()->SetPointSmoothing(1); - renderer->GetRenderWindow()->Modified(); - } - if (!renderer->GetRenderWindow()->GetPolygonSmoothing()) { - renderer->GetRenderWindow()->SetPolygonSmoothing(1); - renderer->GetRenderWindow()->Modified(); - } - - - } else if (isCCd && nodeCC == 9) { - if (renderer->GetRenderWindow()->GetLineSmoothing()) { - renderer->GetRenderWindow()->SetLineSmoothing(0); - renderer->GetRenderWindow()->Modified(); - } - if (renderer->GetRenderWindow()->GetPointSmoothing()) { - renderer->GetRenderWindow()->SetPointSmoothing(0); - renderer->GetRenderWindow()->Modified(); - } - if (renderer->GetRenderWindow()->GetPolygonSmoothing()) { - renderer->GetRenderWindow()->SetPolygonSmoothing(0); - renderer->GetRenderWindow()->Modified(); - } - - } else if (isCCd && nodeCC == 10) { - // manipulate X Coordinates of selected FiberBundle - int tmpXmove; - - bool isXmove = this->GetDataNode()->GetPropertyValue("Xmove",tmpXmove); - - if (!isXmove) - return; - - vtkPolyData *tmpPolyData = m_VtkFiberDataMapperGL->GetInput(); - vtkPoints* tmpVtkPnts = tmpPolyData->GetPoints(); - double PtmpPntVal[3]; - - for (int i=0; iGetNumberOfPoints(); ++i ) - { - tmpVtkPnts->GetPoint(i,PtmpPntVal); - - PtmpPntVal[0] = PtmpPntVal[0] + (double) tmpXmove; - tmpVtkPnts->SetPoint(i, PtmpPntVal); - - tmpPolyData->Modified(); - - } - - } else if (isCCd && nodeCC == 11) { - // manipulate Y Coordinates of selected FiberBundle - int tmpYmove; - - bool isYmove = this->GetDataNode()->GetPropertyValue("Ymove",tmpYmove); - - if (!isYmove) - return; - - vtkPolyData *tmpPolyData = m_VtkFiberDataMapperGL->GetInput(); - vtkPoints* tmpVtkPnts = tmpPolyData->GetPoints(); - double PtmpPntVal[3]; - - for (int i=0; iGetNumberOfPoints(); ++i ) - { - tmpVtkPnts->GetPoint(i,PtmpPntVal); - - PtmpPntVal[1] = PtmpPntVal[1] + (double) tmpYmove; - tmpVtkPnts->SetPoint(i, PtmpPntVal); - - tmpPolyData->Modified(); - - } - - } else if (isCCd && nodeCC == 12) { - // manipulate Z Coordinates of selected FiberBundle - int tmpZmove; - - bool isZmove = this->GetDataNode()->GetPropertyValue("Zmove",tmpZmove); - if (!isZmove) - return; - - vtkPolyData *tmpPolyData = m_VtkFiberDataMapperGL->GetInput(); - vtkPoints* tmpVtkPnts = tmpPolyData->GetPoints(); - double PtmpPntVal[3]; - - for (int i=0; iGetNumberOfPoints(); ++i ) - { - tmpVtkPnts->GetPoint(i,PtmpPntVal); - - PtmpPntVal[2] = PtmpPntVal[2] + (double) tmpZmove; - //PtmpPntVal[2] = PtmpPntVal[2] + 1; - tmpVtkPnts->SetPoint(i, PtmpPntVal); - - tmpPolyData->Modified(); - - } - - } else if (isCCd && nodeCC == 13) { - int tmpTubeSides; - bool isTubeSides = this->GetDataNode()->GetPropertyValue("TubeSides",tmpTubeSides); - - float tmpRadius; - bool isRadius = this->GetDataNode()->GetPropertyValue("TubeRadius",tmpRadius); - - if (!isTubeSides) - return; - - vtkPolyData *tmpPolyData = m_VtkFiberDataMapperGL->GetInput(); - - - - m_tubes->SetInput(tmpPolyData); - m_tubes->SidesShareVerticesOn(); - m_tubes->SetRadius((double)(tmpRadius)); - m_tubes->SetNumberOfSides(tmpTubeSides); - m_tubes->Modified(); - // m_tubes->Update(); - - - m_vtkTubeMapper->SetInputConnection(m_tubes->GetOutputPort()); - m_vtkTubeMapper->ScalarVisibilityOn(); - m_vtkTubeMapper->SetScalarModeToUsePointFieldData(); - m_vtkTubeMapper->SelectColorArray(""); - m_vtkTubeMapper->SelectColorArray("ColorValues"); - - - - m_TubeActor->SetMapper(m_vtkTubeMapper); - m_TubeActor->GetProperty()->SetOpacity(1); - m_TubeActor->GetProperty()->BackfaceCullingOn(); - - m_FiberAssembly->AddPart(m_TubeActor); - m_FiberAssembly->Modified(); - - } else if (isCCd && nodeCC == 14) { - - float temprgb[3]; - this->GetDataNode()->GetColor( temprgb, NULL ); - double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] }; - m_TubeActor->GetProperty()->SetColor(trgb); - - if(m_vtkTubeMapper->GetScalarVisibility()) //can be 0 or 1, for scalarVis On or Off - { - m_vtkTubeMapper->ScalarVisibilityOff(); - } - - } else if (isCCd && nodeCC == 15) { - m_TubeActor->GetProperty()->SetOpacity(0); - m_FiberAssembly->RemovePart(m_TubeActor); - m_FiberAssembly->Modified(); - - }else if (isCCd && nodeCC == 16) { - float tmpTubeOpacity; - bool isTubeOpacity = this->GetDataNode()->GetPropertyValue("TubeOpacity",tmpTubeOpacity); - - m_TubeActor->GetProperty()->SetOpacity((double) tmpTubeOpacity); - m_TubeActor->Modified(); - - } else if (isCCd && nodeCC == 17) { - m_FiberActor->GetProperty()->SetOpacity(0); - m_FiberAssembly->RemovePart(m_FiberActor); - m_FiberAssembly->Modified(); - - }else if (isCCd && nodeCC == 18) { - m_FiberActor->GetProperty()->SetOpacity(0); - m_FiberAssembly->AddPart(m_FiberActor); - m_FiberAssembly->Modified(); - - } - - - - //MITK_INFO << m_VtkFiberDataMapperGL->GetArrayName(); - - - /* int displayIndex(0); - this->GetDataNode()->GetIntProperty( "DisplayChannel", displayIndex, renderer ); - InputImageType *input = const_cast< InputImageType* >( - this->GetInput() - ); - mitk::DiffusionImage *input2 = dynamic_cast< mitk::DiffusionImage* >( - input - ); - input2->SetDisplayIndexForRendering(displayIndex); - Superclass::GenerateDataForRenderer(renderer); - */ -} - -//template -void mitk::FiberBundleMapper3D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) -{ -// MITK_INFO << "FiberBundleMapper3D SetDefault Properties(...)"; - node->AddProperty( "DisplayChannel", mitk::IntProperty::New( true ), renderer, overwrite ); - node->AddProperty( "LineWidth", mitk::IntProperty::New( true ), renderer, overwrite ); - node->AddProperty( "ColorCoding", mitk::IntProperty::New( 0 ), renderer, overwrite); - node->AddProperty( "VertexOpacity_1", mitk::BoolProperty::New( false ), renderer, overwrite); - node->AddProperty( "Set_FA_VertexAlpha", mitk::BoolProperty::New( false ), renderer, overwrite); - node->AddProperty( "pointSize", mitk::FloatProperty::New(0.5), renderer, overwrite); - node->AddProperty( "setShading", mitk::IntProperty::New(1), renderer, overwrite); - node->AddProperty( "Xmove", mitk::IntProperty::New( 0 ), renderer, overwrite); - node->AddProperty( "Ymove", mitk::IntProperty::New( 0 ), renderer, overwrite); - node->AddProperty( "Zmove", mitk::IntProperty::New( 0 ), renderer, overwrite); - node->AddProperty( "RepPoints", mitk::BoolProperty::New( false ), renderer, overwrite); - node->AddProperty( "TubeSides", mitk::IntProperty::New( 8 ), renderer, overwrite); - node->AddProperty( "TubeRadius", mitk::FloatProperty::New( 0.15 ), renderer, overwrite); - node->AddProperty( "TubeOpacity", mitk::FloatProperty::New( 1.0 ), renderer, overwrite); - - node->AddProperty( "pickable", mitk::BoolProperty::New( true ), renderer, overwrite); - - Superclass::SetDefaultProperties(node, renderer, overwrite); - - - -} - -vtkProp* mitk::FiberBundleMapper3D::GetVtkProp(mitk::BaseRenderer *renderer) -{ - - //MITK_INFO << "FiberBundleMapper3D GetVtkProp(renderer)"; - return m_FiberAssembly; - -} - -void mitk::FiberBundleMapper3D::ApplyProperties(mitk::BaseRenderer* renderer) -{ - // MITK_INFO << "FiberBundleMapper3D ApplyProperties(renderer)"; -} - -void mitk::FiberBundleMapper3D::UpdateVtkObjects() -{ - // MITK_INFO << "FiberBundleMapper3D UpdateVtkObjects()"; - - -} - -void mitk::FiberBundleMapper3D::SetVtkMapperImmediateModeRendering(vtkMapper *) -{ - - - -} - - - diff --git a/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper3D.h b/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper3D.h deleted file mode 100644 index 5234d71650..0000000000 --- a/Modules/DiffusionImaging/Rendering/mitkFiberBundleMapper3D.h +++ /dev/null @@ -1,92 +0,0 @@ -/*========================================================================= - -Program: Medical Imaging & Interaction Toolkit -Language: C++ -Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $ -Version: $Revision: 17179 $ - -Copyright (c) German Cancer Research Center, Division of Medical and -Biological Informatics. All rights reserved. -See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notices for more information. - -=========================================================================*/ - - -#ifndef FiberBundleMapper3D_H_HEADER_INCLUDED -#define FiberBundleMapper3D_H_HEADER_INCLUDED - -//#include "mitkCommon.h" -//#include "mitkBaseRenderer.h" - -#include -#include -#include - - -#include -#include -#include -#include -#include - - -namespace mitk { - - //##Documentation - //## @brief Mapper for FiberBundles - //## @ingroup Mapper -// template - class MitkDiffusionImaging_EXPORT FiberBundleMapper3D : public VtkMapper3D - { - public: - - mitkClassMacro(FiberBundleMapper3D, VtkMapper3D); - itkNewMacro(Self); - - - const mitk::FiberBundle* GetInput(); - - virtual vtkProp *GetVtkProp(mitk::BaseRenderer *renderer); //looks like depricated.. should be replaced bz GetViewProp() - static void SetDefaultProperties(DataNode* node, BaseRenderer* renderer = NULL, bool overwrite = false ); - - virtual void ApplyProperties(mitk::BaseRenderer* renderer); - static void SetVtkMapperImmediateModeRendering(vtkMapper *mapper); - - virtual void GenerateDataForRenderer(mitk::BaseRenderer* renderer); - virtual void GenerateData(); - - vtkOpenGLPolyDataMapper* getVtkFiberBundleMapper(); - protected: - - FiberBundleMapper3D(); - virtual ~FiberBundleMapper3D(); - - void UpdateVtkObjects(); - - - - vtkSmartPointer m_VtkFiberDataMapperGL; - vtkSmartPointer m_FiberActor; - vtkSmartPointer m_FiberAssembly; - - vtkSmartPointer m_vtkTubeMapper; - vtkSmartPointer m_tubes; - vtkSmartPointer m_TubeActor; - - - - - - }; - -} // namespace mitk - - - - -#endif /* FiberBundleMapper3D_H_HEADER_INCLUDED */ - diff --git a/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper2D.cpp b/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper2D.cpp index 55df715ef7..676f219b52 100644 --- a/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper2D.cpp +++ b/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper2D.cpp @@ -1,314 +1,321 @@ /* * mitkFiberBundleMapper2D.cpp * mitk-all * * Created by HAL9000 on 1/17/11. * Copyright 2011 __MyCompanyName__. All rights reserved. * */ #include "mitkFiberBundleXMapper2D.h" #include #include #include #include #include //#include //#include #include #include #include #include #include #include #include #include //#include #include #include #include #include #include #include #include mitk::FiberBundleXMapper2D::FiberBundleXMapper2D() { - + m_lut = vtkLookupTable::New(); + m_lut->Build(); } mitk::FiberBundleXMapper2D::~FiberBundleXMapper2D() { } -const mitk::FiberBundleX* mitk::FiberBundleXMapper2D::GetInput() +mitk::FiberBundleX* mitk::FiberBundleXMapper2D::GetInput() { - return dynamic_cast ( GetData() ); + return dynamic_cast< mitk::FiberBundleX * > ( GetData() ); } void mitk::FiberBundleXMapper2D::Update(mitk::BaseRenderer * renderer) { if ( !this->IsVisible( renderer ) ) { return; } // Calculate time step of the input data for the specified renderer (integer value) // this method is implemented in mitkMapper this->CalculateTimeStep( renderer ); //check if updates occured in the node or on the display FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); const DataNode *node = this->GetDataNode(); if ( (localStorage->m_LastUpdateTime < node->GetMTime()) || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified? || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) { // MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName(); this->GenerateDataForRenderer( renderer ); } if ((localStorage->m_LastUpdateTime < renderer->GetDisplayGeometry()->GetMTime()) ) //was the display geometry modified? e.g. zooming, panning) { this->UpdateShaderParameter(renderer); } } void mitk::FiberBundleXMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer) { FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); - // MITK_INFO << "uSERWAAAAAAAS, da shader brauchat a poor neue zoin"; + //get information about current position of views mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController(); mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry(); //generate according cutting planes based on the view position float sliceN[3], planeOrigin[3]; // since shader uses camera coordinates, transform origin and normal from worldcoordinates to cameracoordinates planeOrigin[0] = (float) planeGeo->GetOrigin()[0]; planeOrigin[1] = (float) planeGeo->GetOrigin()[1]; planeOrigin[2] = (float) planeGeo->GetOrigin()[2]; sliceN[0] = planeGeo->GetNormal()[0]; sliceN[1] = planeGeo->GetNormal()[1]; sliceN[2] = planeGeo->GetNormal()[2]; float tmp1 = planeOrigin[0] * sliceN[0]; float tmp2 = planeOrigin[1] * sliceN[1]; float tmp3 = planeOrigin[2] * sliceN[2]; float d1 = tmp1 + tmp2 + tmp3; //attention, correct normalvector float plane1[4]; plane1[0] = sliceN[0]; plane1[1] = sliceN[1]; plane1[2] = sliceN[2]; plane1[3] = d1; float thickness = 2.0; if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness)) MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR"; bool fiberfading = false; if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading)) MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR"; int fiberfading_i = 1; if (!fiberfading) fiberfading_i = 0; + // set Opacity + float fiberOpacity; + this->GetDataNode()->GetOpacity(fiberOpacity, NULL); localStorage->m_PointActor->GetProperty()->AddShaderVariable("slicingPlane",4, plane1); localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberThickness",1, &thickness); localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberFadingON",1, &fiberfading_i); + localStorage->m_PointActor->GetProperty()->AddShaderVariable("fiberOpacity", 1, &fiberOpacity); } // ALL RAW DATA FOR VISUALIZATION IS GENERATED HERE. // vtkActors and Mappers are feeded here void mitk::FiberBundleXMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { //the handler of local storage gets feeded in this method with requested data for related renderwindow FBXLocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); //this procedure is depricated, //not needed after initializaton anymore mitk::DataNode* node = this->GetDataNode(); if ( node == NULL ) { MITK_INFO << "check DATANODE: ....[Fail] "; return; } /////////////////////////////////// + ///THIS GET INPUT + mitk::FiberBundleX* fbx = this->GetInput(); - - - -///THIS GET INPUT - const mitk::FiberBundleX* fbx = this->GetInput(); -//extract polydata - //todo - - vtkSmartPointer lut = vtkLookupTable::New(); - lut->Build(); + localStorage->m_PointMapper->ScalarVisibilityOn(); localStorage->m_PointMapper->SetScalarModeToUsePointFieldData(); - //m_VtkFiberDataMapperGL->SelectColorArray("FaColors"); - localStorage->m_PointMapper->SelectColorArray("ColorValues"); - localStorage->m_PointMapper->SetLookupTable(lut); //apply the properties after the slice was set + localStorage->m_PointMapper->SetLookupTable(m_lut); //apply the properties after the slice was set + localStorage->m_PointActor->GetProperty()->SetOpacity(0.999); + + // set color + if (fbx->GetCurrentColorCoding() != NULL){ +// localStorage->m_PointMapper->SelectColorArray(""); + localStorage->m_PointMapper->SelectColorArray(fbx->GetCurrentColorCoding()); + MITK_INFO << "MapperFBX 2D: " << fbx->GetCurrentColorCoding(); + + if(fbx->GetCurrentColorCoding() == fbx->COLORCODING_CUSTOM){ + float temprgb[3]; + this->GetDataNode()->GetColor( temprgb, NULL ); + double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] }; + localStorage->m_PointActor->GetProperty()->SetColor(trgb); + } + } + - // feed the vtk fiber mapper with point data ...TODO do in constructor - localStorage->m_PointMapper->SetInput(localStorage->m_SlicedResult); // in optimized version, mapper is feeded by localStorage->m_cutter->GetOutput(); + localStorage->m_PointMapper->SetInput(fbx->GetFiberPolyData()); localStorage->m_PointActor->SetMapper(localStorage->m_PointMapper); localStorage->m_PointActor->GetProperty()->ShadingOn(); // Applying shading properties { - //Superclass::ApplyProperties( ls->m_Actor, renderer ) ; - // VTK Properties - //ApplyMitkPropertiesToVtkProperty( this->GetDataNode(), ls->m_Actor->GetProperty(), renderer ); - // Shaders mitk::ShaderRepository::GetGlobalShaderRepository()->ApplyProperties(this->GetDataNode(),localStorage->m_PointActor,renderer, localStorage->m_LastUpdateTime); } this->UpdateShaderParameter(renderer); // We have been modified => save this for next Update() localStorage->m_LastUpdateTime.Modified(); } vtkProp* mitk::FiberBundleXMapper2D::GetVtkProp(mitk::BaseRenderer *renderer) { //MITK_INFO << "FiberBundleMapper2D GetVtkProp(renderer)"; this->Update(renderer); return m_LSH.GetLocalStorage(renderer)->m_PointActor; } void mitk::FiberBundleXMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { //add shader to datano //####### load shader from file ######### QString applicationDir = QCoreApplication::applicationDirPath(); if (applicationDir.endsWith("bin")) applicationDir.append("/"); else if (applicationDir.endsWith("MacOS")) { //on osx, check if path for installer or MITK development is needed applicationDir.append("/"); QFile f( applicationDir+"FiberTrackingLUTBaryCoords.bin" ); if( !f.exists() ) // if file does not exist, then look in MITK development build directory applicationDir.append("../../../"); }else applicationDir.append("\\..\\"); mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false ); mitk::ShaderRepository::Pointer shaderRepository = mitk::ShaderRepository::GetGlobalShaderRepository(); shaderRepository->LoadShader(mitk::StandardFileLocations::GetInstance()->FindFile("mitkShaderFiberClipping.xml")); //#################################################################### node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping")); mitk::ShaderRepository::GetGlobalShaderRepository()->AddDefaultProperties(node,renderer,overwrite); //add other parameters to propertylist node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(2.0f), renderer, overwrite ); node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite ); Superclass::SetDefaultProperties(node, renderer, overwrite); } // following methods are essential, they actually call the GetVtkProp() method // which returns the desired actors void mitk::FiberBundleXMapper2D::MitkRenderOverlay(BaseRenderer* renderer) { // MITK_INFO << "FiberBundleMapper2D MitkRenderOVerlay(renderer)"; if ( this->IsVisible(renderer)==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) { this->GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer()); } } void mitk::FiberBundleXMapper2D::MitkRenderOpaqueGeometry(BaseRenderer* renderer) { // MITK_INFO << "FiberBundleMapper2D MitkRenderOpaqueGeometry(renderer)"; if ( this->IsVisible( renderer )==false ) return; if ( this->GetVtkProp(renderer)->GetVisibility() ) this->GetVtkProp(renderer)->RenderOpaqueGeometry( renderer->GetVtkRenderer() ); } void mitk::FiberBundleXMapper2D::MitkRenderTranslucentGeometry(BaseRenderer* renderer) { // MITK_INFO << "FiberBundleMapper2D MitkRenderTranslucentGeometry(renderer)"; if ( this->IsVisible(renderer)==false ) return; //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer??? if ( this->GetVtkProp(renderer)->GetVisibility() ) this->GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer()); } void mitk::FiberBundleXMapper2D::MitkRenderVolumetricGeometry(BaseRenderer* renderer) { // MITK_INFO << "FiberBundleMapper2D MitkRenderVolumentricGeometry(renderer)"; if(IsVisible(renderer)==false) return; //TODO is it possible to have a visible BaseRenderer AND an invisible VtkRenderer??? if ( GetVtkProp(renderer)->GetVisibility() ) this->GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer()); } mitk::FiberBundleXMapper2D::FBXLocalStorage::FBXLocalStorage() { m_PointActor = vtkSmartPointer::New(); m_PointMapper = vtkSmartPointer::New(); } diff --git a/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper2D.h b/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper2D.h index 1957719b66..073938ca11 100644 --- a/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper2D.h +++ b/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper2D.h @@ -1,110 +1,112 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2010-09-26 20:40:22 +0200 (So, 26 Sep 2010) $ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef FIBERBUNDLEXMAPPER2D_H_HEADER_INCLUDED #define FIBERBUNDLEXMAPPER2D_H_HEADER_INCLUDED //MITK Rendering #include #include //#include "MitkDiffusionImagingExports.h" #include #include #include class vtkActor; //class vtkPropAssembly; //lets see if we need it class mitkBaseRenderer; class vtkPolyDataMapper; class vtkCutter; class vtkPlane; class vtkPolyData; namespace mitk { class FiberBundleXMapper2D : public VtkMapper2D { public: mitkClassMacro(FiberBundleXMapper2D, VtkMapper2D); itkNewMacro(Self); - const mitk::FiberBundleX* GetInput(); + mitk::FiberBundleX* GetInput(); /** \brief Checks whether this mapper needs to update itself and generate * data. */ virtual void Update(mitk::BaseRenderer * renderer); static void SetDefaultProperties(DataNode* node, BaseRenderer* renderer = NULL, bool overwrite = false ); //### methods of MITK-VTK rendering pipeline virtual vtkProp* GetVtkProp(mitk::BaseRenderer* renderer); virtual void MitkRenderOverlay(BaseRenderer* renderer); virtual void MitkRenderOpaqueGeometry(BaseRenderer* renderer); virtual void MitkRenderTranslucentGeometry(BaseRenderer* renderer); virtual void MitkRenderVolumetricGeometry(BaseRenderer* renderer); //### end of methods of MITK-VTK rendering pipeline class FBXLocalStorage : public mitk::Mapper::BaseLocalStorage { public: /** \brief Point Actor of a 2D render window. */ vtkSmartPointer m_PointActor; /** \brief Point Mapper of a 2D render window. */ vtkSmartPointer m_PointMapper; vtkSmartPointer m_SlicingPlane; //needed later when optimized 2D mapper vtkSmartPointer m_SlicedResult; //might be depricated in optimized 2D mapper /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastUpdateTime; /** \brief Constructor of the local storage. Do as much actions as possible in here to avoid double executions. */ FBXLocalStorage(); //if u copy&paste from this 2Dmapper, be aware that the implementation of this constructor is in the cpp file ~FBXLocalStorage() { } }; /** \brief This member holds all three LocalStorages for the three 2D render windows. */ mitk::Mapper::LocalStorageHandler m_LSH; protected: FiberBundleXMapper2D(); virtual ~FiberBundleXMapper2D(); /** Does the actual resampling, without rendering. */ virtual void GenerateDataForRenderer(mitk::BaseRenderer*); void UpdateShaderParameter(mitk::BaseRenderer*); + private: + vtkSmartPointer m_lut; }; }//end namespace -#endif \ No newline at end of file +#endif diff --git a/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper3D.cpp b/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper3D.cpp index 004a2f4a40..ba6268700b 100644 --- a/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper3D.cpp +++ b/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper3D.cpp @@ -1,206 +1,202 @@ /*========================================================================= - + Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $ Version: $Revision: 17179 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkFiberBundleXMapper3D.h" - #include //#include //#include - #include #include #include //not essential for mapper #include mitk::FiberBundleXMapper3D::FiberBundleXMapper3D() -:m_FiberMapperGLSP(vtkSmartPointer::New()), - m_FiberMapperGLWP(vtkOpenGLPolyDataMapper::New()), - m_FiberActorSP(vtkSmartPointer::New()), - m_FiberActorWP(vtkOpenGLActor::New()), - m_FiberAssembly(vtkPropAssembly::New()) { - + m_lut = vtkLookupTable::New(); + m_lut->Build(); } mitk::FiberBundleXMapper3D::~FiberBundleXMapper3D() { - m_FiberAssembly->Delete(); + } const mitk::FiberBundleX* mitk::FiberBundleXMapper3D::GetInput() { - MITK_INFO << "FiberBundleXxXXMapper3D() GetInput()"; - return static_cast ( GetData() ); + MITK_INFO << "FiberBundleXxXXMapper3D() GetInput()"; + return static_cast ( GetData() ); } /* - This method is called once the mapper gets new input, - for UI rotation or changes in colorcoding this method is NOT called + This method is called once the mapper gets new input, + for UI rotation or changes in colorcoding this method is NOT called */ -void mitk::FiberBundleXMapper3D::GenerateData() +void mitk::FiberBundleXMapper3D::GenerateData(mitk::BaseRenderer *renderer) { - //MITK_INFO << "GENERATE DATA FOR FBX :)"; - //=====timer measurement==== - QTime myTimer; - myTimer.start(); - //========================== - -// mitk::FiberBundleX::Pointer FBX = dynamic_cast< mitk::FiberBundleX* > (this->GetData()); - - mitk::FiberBundleX* FBX = dynamic_cast (this->GetData()); - if (FBX == NULL) { - return; - } - //todo smartpointer - vtkPolyData* FiberData = FBX->GetFiberPolyData(); - - if (FiberData == NULL) { - return; - } - - MITK_INFO << "NumOfFibs: " << FiberData->GetNumberOfLines(); - MITK_INFO << "NumOfPoints: " << FiberData->GetNumberOfPoints(); - - - m_FiberMapperGLSP->SetInput(FiberData); - // m_FiberMapperGLWP->SetInput(FiberData); - - - if ( FiberData->GetPointData()->GetNumberOfArrays() > 0 ) - { - if ( FiberData->GetPointData()->HasArray(FiberBundleX::COLORCODING_ORIENTATION_BASED) ) - { - m_FiberMapperGLSP->SelectColorArray(FiberBundleX::COLORCODING_ORIENTATION_BASED); - // m_FiberMapperGLWP->SelectColorArray(FiberBundleX::COLORCODING_ORIENTATION_BASED); - } else { - // iterate through polydata array and take the first best -but valid- array - - //===ToDo=== - //check of componentsize as well, if it is not RGB or RGBA (ie. size 3 or 4), then check if it is a scalar - // if scalar then create lookuptable for that. + + //MITK_INFO << "GENERATE DATA FOR FBX :)"; + //=====timer measurement==== + QTime myTimer; + myTimer.start(); + //========================== + + + mitk::FiberBundleX* FBX = dynamic_cast (this->GetData()); + if (FBX == NULL) + return; + + vtkSmartPointer FiberData = FBX->GetFiberPolyData(); + if (FiberData == NULL) + return; + + + FBXLocalStorage3D *localStorage = m_LSH.GetLocalStorage(renderer); + localStorage->m_FiberMapper->SetInput(FiberData); + + if ( FiberData->GetPointData()->GetNumberOfArrays() > 0 ) + localStorage->m_FiberMapper->SelectColorArray( FBX->GetCurrentColorCoding() ); + + localStorage->m_FiberMapper->ScalarVisibilityOn(); + localStorage->m_FiberMapper->SetScalarModeToUsePointFieldData(); + localStorage->m_FiberActor->SetMapper(localStorage->m_FiberMapper); +// localStorage->m_FiberActor->GetProperty()->SetOpacity(0.999); + localStorage->m_FiberMapper->SetLookupTable(m_lut); + + + // set Opacity + float tmpopa; + this->GetDataNode()->GetOpacity(tmpopa, NULL); + localStorage->m_FiberActor->GetProperty()->SetOpacity((double) tmpopa); + + // set color + if (FBX->GetCurrentColorCoding() != NULL){ +// localStorage->m_FiberMapper->SelectColorArray(""); + localStorage->m_FiberMapper->SelectColorArray(FBX->GetCurrentColorCoding()); + MITK_INFO << "MapperFBX: " << FBX->GetCurrentColorCoding(); + + if(FBX->GetCurrentColorCoding() == FBX->COLORCODING_CUSTOM) { + float temprgb[3]; + this->GetDataNode()->GetColor( temprgb, NULL ); + double trgb[3] = { (double) temprgb[0], (double) temprgb[1], (double) temprgb[2] }; + localStorage->m_FiberActor->GetProperty()->SetColor(trgb); + } } - - m_FiberMapperGLSP->ScalarVisibilityOn(); - // m_FiberMapperGLWP->ScalarVisibilityOn(); - m_FiberMapperGLSP->SetScalarModeToUsePointFieldData(); - // m_FiberMapperGLWP->SetScalarModeToUsePointFieldData(); - } - - - m_FiberActorSP->SetMapper(m_FiberMapperGLSP); - // m_FiberActorWP->SetMapper(m_FiberMapperGLWP); - - m_FiberActorSP->GetProperty()->SetOpacity(1.0); - // m_FiberActorWP->GetProperty()->SetOpacity(1.0); - - if (FBX->getCurrentColorCoding() != NULL) - m_FiberMapperGLSP->SelectColorArray(FBX->getCurrentColorCoding()); - - m_FiberAssembly->AddPart(m_FiberActorSP); - - //since this method is called after generating all necessary data for fiber visualization, all modifications are represented so far. - FBX->setFBXModificationDone(); - //====timer measurement======== - MITK_INFO << "Execution Time GenerateData() (nmiliseconds): " << myTimer.elapsed(); - //============================= - + + + localStorage->m_FiberAssembly->AddPart(localStorage->m_FiberActor); + localStorage->m_LastUpdateTime.Modified(); + //since this method is called after generating all necessary data for fiber visualization, all modifications are represented so far. + + //====timer measurement======== + MITK_INFO << "Execution Time GenerateData() (nmiliseconds): " << myTimer.elapsed(); + //============================= + } void mitk::FiberBundleXMapper3D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) { - if ( !this->IsVisible( renderer ) ) - { - return; - } - - //MITK_INFO << "FiberBundleXxXXMapper3D()DataForRenderer"; - //ToDo do update checks - mitk::FiberBundleX* FBX = dynamic_cast (this->GetData()); - if(FBX->isFiberBundleXModified()) - this->GenerateData(); + if ( !this->IsVisible( renderer ) ) + return; + + // Calculate time step of the input data for the specified renderer (integer value) + // this method is implemented in mitkMapper + this->CalculateTimeStep( renderer ); + + //check if updates occured in the node or on the display + FBXLocalStorage3D *localStorage = m_LSH.GetLocalStorage(renderer); + const DataNode *node = this->GetDataNode(); + if ( (localStorage->m_LastUpdateTime < node->GetMTime()) + || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified? + || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) + { + MITK_INFO << "UPDATE NEEDED FOR _ " << renderer->GetName(); + this->GenerateData(renderer); + } + } void mitk::FiberBundleXMapper3D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { - -// MITK_INFO << "FiberBundleXxXXMapper3D()SetDefaultProperties"; - - - //MITK_INFO << "FiberBundleMapperX3D SetDefault Properties(...)"; - // node->AddProperty( "DisplayChannel", mitk::IntProperty::New( true ), renderer, overwrite ); - // node->AddProperty( "LineWidth", mitk::IntProperty::New( true ), renderer, overwrite ); - // node->AddProperty( "ColorCoding", mitk::IntProperty::New( 0 ), renderer, overwrite); - // node->AddProperty( "VertexOpacity_1", mitk::BoolProperty::New( false ), renderer, overwrite); - // node->AddProperty( "Set_FA_VertexAlpha", mitk::BoolProperty::New( false ), renderer, overwrite); - // node->AddProperty( "pointSize", mitk::FloatProperty::New(0.5), renderer, overwrite); - // node->AddProperty( "setShading", mitk::IntProperty::New(1), renderer, overwrite); - // node->AddProperty( "Xmove", mitk::IntProperty::New( 0 ), renderer, overwrite); - // node->AddProperty( "Ymove", mitk::IntProperty::New( 0 ), renderer, overwrite); - // node->AddProperty( "Zmove", mitk::IntProperty::New( 0 ), renderer, overwrite); - // node->AddProperty( "RepPoints", mitk::BoolProperty::New( false ), renderer, overwrite); - // node->AddProperty( "TubeSides", mitk::IntProperty::New( 8 ), renderer, overwrite); - // node->AddProperty( "TubeRadius", mitk::FloatProperty::New( 0.15 ), renderer, overwrite); - // node->AddProperty( "TubeOpacity", mitk::FloatProperty::New( 1.0 ), renderer, overwrite); - - node->AddProperty( "pickable", mitk::BoolProperty::New( true ), renderer, overwrite); - - Superclass::SetDefaultProperties(node, renderer, overwrite); - - - + + // MITK_INFO << "FiberBundleXxXXMapper3D()SetDefaultProperties"; + + + //MITK_INFO << "FiberBundleMapperX3D SetDefault Properties(...)"; + // node->AddProperty( "DisplayChannel", mitk::IntProperty::New( true ), renderer, overwrite ); + node->AddProperty( "LineWidth", mitk::IntProperty::New( true ), renderer, overwrite ); + node->AddProperty( "opacity", mitk::FloatProperty::New( 1.0 ), renderer, overwrite); + // node->AddProperty( "VertexOpacity_1", mitk::BoolProperty::New( false ), renderer, overwrite); + // node->AddProperty( "Set_FA_VertexAlpha", mitk::BoolProperty::New( false ), renderer, overwrite); + // node->AddProperty( "pointSize", mitk::FloatProperty::New(0.5), renderer, overwrite); + // node->AddProperty( "setShading", mitk::IntProperty::New(1), renderer, overwrite); + // node->AddProperty( "Xmove", mitk::IntProperty::New( 0 ), renderer, overwrite); + // node->AddProperty( "Ymove", mitk::IntProperty::New( 0 ), renderer, overwrite); + // node->AddProperty( "Zmove", mitk::IntProperty::New( 0 ), renderer, overwrite); + // node->AddProperty( "RepPoints", mitk::BoolProperty::New( false ), renderer, overwrite); + // node->AddProperty( "TubeSides", mitk::IntProperty::New( 8 ), renderer, overwrite); + // node->AddProperty( "TubeRadius", mitk::FloatProperty::New( 0.15 ), renderer, overwrite); + // node->AddProperty( "TubeOpacity", mitk::FloatProperty::New( 1.0 ), renderer, overwrite); + + node->AddProperty( "pickable", mitk::BoolProperty::New( true ), renderer, overwrite); + + Superclass::SetDefaultProperties(node, renderer, overwrite); + + + } vtkProp* mitk::FiberBundleXMapper3D::GetVtkProp(mitk::BaseRenderer *renderer) { - //MITK_INFO << "FiberBundleXxXXMapper3D()GetVTKProp"; - //this->GenerateData(); - return m_FiberAssembly; - + //MITK_INFO << "FiberBundleXxXXMapper3D()GetVTKProp"; + //this->GenerateData(); + return m_LSH.GetLocalStorage(renderer)->m_FiberAssembly; + } void mitk::FiberBundleXMapper3D::ApplyProperties(mitk::BaseRenderer* renderer) { -// MITK_INFO << "FiberBundleXXXXMapper3D ApplyProperties(renderer)"; + } void mitk::FiberBundleXMapper3D::UpdateVtkObjects() { -// MITK_INFO << "FiberBundleXxxXMapper3D UpdateVtkObjects()"; - - + } void mitk::FiberBundleXMapper3D::SetVtkMapperImmediateModeRendering(vtkMapper *) { - - - -} +} +mitk::FiberBundleXMapper3D::FBXLocalStorage3D::FBXLocalStorage3D() +{ + m_FiberActor = vtkSmartPointer::New(); + m_FiberMapper = vtkSmartPointer::New(); + m_FiberAssembly = vtkSmartPointer::New(); +} diff --git a/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper3D.h b/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper3D.h index 370ee0d7a5..b1a33f3611 100644 --- a/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper3D.h +++ b/Modules/DiffusionImaging/Rendering/mitkFiberBundleXMapper3D.h @@ -1,85 +1,105 @@ /*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $ Version: $Revision: 17179 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef FiberBundleXMapper3D_H_HEADER_INCLUDED #define FiberBundleXMapper3D_H_HEADER_INCLUDED //#include //?? necessary #include #include #include #include #include #include +#include class vtkPropAssembly; namespace mitk { - //##Documentation - //## @brief Mapper for FiberBundleX - //## @ingroup Mapper +//##Documentation +//## @brief Mapper for FiberBundleX +//## @ingroup Mapper - class MitkDiffusionImaging_EXPORT FiberBundleXMapper3D : public VtkMapper3D - { - public: +class MitkDiffusionImaging_EXPORT FiberBundleXMapper3D : public VtkMapper3D +{ +public: mitkClassMacro(FiberBundleXMapper3D, VtkMapper3D); itkNewMacro(Self); //========== essential implementation for 3D mapper ======== const FiberBundleX* GetInput(); virtual vtkProp *GetVtkProp(mitk::BaseRenderer *renderer); //looks like depricated.. should be replaced bz GetViewProp() static void SetDefaultProperties(DataNode* node, BaseRenderer* renderer = NULL, bool overwrite = false ); virtual void ApplyProperties(mitk::BaseRenderer* renderer); static void SetVtkMapperImmediateModeRendering(vtkMapper *mapper); virtual void GenerateDataForRenderer(mitk::BaseRenderer* renderer); - virtual void GenerateData(); //========================================================= - - protected: + virtual void GenerateData(mitk::BaseRenderer *renderer); + + class FBXLocalStorage3D : public mitk::Mapper::BaseLocalStorage + { + public: + /** \brief Point Actor of a 3D render window. */ + vtkSmartPointer m_FiberActor; + /** \brief Point Mapper of a 3D render window. */ + vtkSmartPointer m_FiberMapper; + + vtkSmartPointer m_FiberAssembly; + + /** \brief Timestamp of last update of stored data. */ + itk::TimeStamp m_LastUpdateTime; + /** \brief Constructor of the local storage. Do as much actions as possible in here to avoid double executions. */ + FBXLocalStorage3D(); //if u copy&paste from this 2Dmapper, be aware that the implementation of this constructor is in the cpp file + + ~FBXLocalStorage3D() + { + } + }; + + /** \brief This member holds all three LocalStorages for the 3D render window(s). */ + mitk::Mapper::LocalStorageHandler m_LSH; + + +protected: FiberBundleXMapper3D(); virtual ~FiberBundleXMapper3D(); void UpdateVtkObjects(); //?? - vtkSmartPointer m_FiberMapperGLSP; - vtkOpenGLPolyDataMapper* m_FiberMapperGLWP; - - vtkSmartPointer m_FiberActorSP; - vtkOpenGLActor* m_FiberActorWP; - - vtkPropAssembly* m_FiberAssembly; +private: + vtkSmartPointer m_lut; - }; +}; } // end namespace mitk #endif /* FiberBundleXMapper3D_H_HEADER_INCLUDED */ diff --git a/Modules/DiffusionImaging/Rendering/mitkPlanarCircleMapper3D.h b/Modules/DiffusionImaging/Rendering/mitkPlanarCircleMapper3D.h index b1aeff7bbf..82c57b0a43 100644 --- a/Modules/DiffusionImaging/Rendering/mitkPlanarCircleMapper3D.h +++ b/Modules/DiffusionImaging/Rendering/mitkPlanarCircleMapper3D.h @@ -1,98 +1,97 @@ /*========================================================================= - + Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $ Version: $Revision: 17179 $ - + Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. - + This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. - + =========================================================================*/ #ifndef PlanarCircleMapper3D_H_HEADER_INCLUDED #define PlanarCircleMapper3D_H_HEADER_INCLUDED //#include "mitkCommon.h" //#include "mitkBaseRenderer.h" -#include #include #include //#include "MitkDiffusionImagingMBIExports.h" #include #include #include #include #include #include #include #include #include //class mitkPlanarCircle; #include namespace mitk { - + //##Documentation //## @brief Mapper for FiberBundles //## @ingroup Mapper // template class /*MitkDiffusionImagingMBI_EXPORT*/ PlanarCircleMapper3D : public VtkMapper3D { public: - + mitkClassMacro(PlanarCircleMapper3D, VtkMapper3D); itkNewMacro(Self); - - + + const mitk::PlanarCircle* GetInput(); - + virtual vtkProp *GetVtkProp(mitk::BaseRenderer *renderer); //looks like depricated.. should be replaced bz GetViewProp() static void SetDefaultProperties(DataNode* node, BaseRenderer* renderer = NULL, bool overwrite = false ); - + virtual void ApplyProperties(mitk::BaseRenderer* renderer); static void SetVtkMapperImmediateModeRendering(vtkMapper *mapper); - + virtual void GenerateDataForRenderer(mitk::BaseRenderer* renderer); virtual void GenerateData(); - - + + protected: - + PlanarCircleMapper3D(); virtual ~PlanarCircleMapper3D(); - + void UpdateVtkObjects(); - - + + vtkAppendPolyData *m_vtkCircleList; - + vtkOpenGLPolyDataMapper *m_VtkCircleDataMapperGL; - + vtkOpenGLActor *m_CircleActor; - - + + vtkPropAssembly *m_CircleAssembly; - + vtkRegularPolygonSource *m_polygonSource; - + }; - + } // namespace mitk #endif /* FiberBundleMapper3D_H_HEADER_INCLUDED */ diff --git a/Modules/DiffusionImaging/Rendering/mitkShaderFiberClipping.xml b/Modules/DiffusionImaging/Rendering/mitkShaderFiberClipping.xml index 29ab23a67d..ceedf961af 100644 --- a/Modules/DiffusionImaging/Rendering/mitkShaderFiberClipping.xml +++ b/Modules/DiffusionImaging/Rendering/mitkShaderFiberClipping.xml @@ -1,54 +1,56 @@ varying vec3 positionWorld; varying vec3 color; void main(void) { color = gl_Color.rgb; positionWorld = vec3(gl_Vertex); gl_Position = ftransform(); } uniform vec4 slicingPlane; uniform float fiberThickness; uniform int fiberFadingON; + uniform float fiberOpacity; varying vec3 positionWorld; varying vec3 color; void main(void) { float r1 = dot(positionWorld, slicingPlane.xyz) - slicingPlane.w; if ( abs(r1) > fiberThickness ) discard; if (fiberFadingON != 0) { float x = (r1+fiberThickness)/(fiberThickness*2.0); x = 1.0 - x; - gl_FragColor = vec4(color*x, 1.0); + gl_FragColor = vec4(color*x, fiberOpacity); }else{ - gl_FragColor = vec4(color, 1.0); + gl_FragColor = vec4(color, fiberOpacity); } } + diff --git a/Modules/DiffusionImaging/Tractography/GibbsTracking/BuildFibres.cpp b/Modules/DiffusionImaging/Tractography/GibbsTracking/BuildFibres.cpp index 5420f4414d..f7fa4db9eb 100644 --- a/Modules/DiffusionImaging/Tractography/GibbsTracking/BuildFibres.cpp +++ b/Modules/DiffusionImaging/Tractography/GibbsTracking/BuildFibres.cpp @@ -1,366 +1,158 @@ #ifndef _BUILDFIBRES #define _BUILDFIBRES //#include "matrix.h" #define _USE_MATH_DEFINES #include #include #include #include using namespace std; #define PI M_PI - - -#ifdef TIMING - -static struct timeval timeS; - -class PropStats -{ - int N; - int accept; -public: - void clear() { N = 0; accept = 0;} - void propose() {N++;} - void accepted() {accept++;} - - void report(const char *s) - { - mexPrintf("%s #proposals: %8.2fk acceptratio: %.2f \% \n",s,1.0*N/1000.0,100.0*accept/N); - } -}; - - -class Timing -{ -public: - Timing() { time = 0; ncalls = 0;} - void clear() {time = 0; ncalls=0;} - - - long time; - int ncalls; - - void report(const char *s) - { - mexPrintf("%s total: %10.2fms calls: %10.1fk t/call: %10.3fms \n",s,time/1000.0,1.0*ncalls/1000.0,1.0*time/ncalls); - } - - void report_time(const char *s) - { - mexPrintf("%s: %.2fms \n",s,time/1000.0); - } - -}; - -inline void tic(Timing *t) -{ - gettimeofday( &timeS, NULL); - t->time -= (timeS.tv_sec*1000000 + timeS.tv_usec); - t->ncalls++; -} -inline void toc(Timing *t) -{ - gettimeofday( &timeS, NULL); - t->time += (timeS.tv_sec*1000000 + timeS.tv_usec); -} - - -#endif - #include "ParticleGrid.cpp" -class CCAnalysis +#include +#include +#include +#include +#include +#include +#include + +class FiberBuilder { public: Particle *particles; int pcnt; int attrcnt; typedef vector< Particle* > ParticleContainerType; typedef vector< ParticleContainerType* > FiberContainerType; - FiberContainerType* m_FiberContainer; + vtkSmartPointer m_VtkCellArray; + vtkSmartPointer m_VtkPoints; - CCAnalysis(float *points, int numPoints, double spacing[]) + typedef itk::Vector OdfVectorType; + typedef itk::Image ItkQBallImgType; + ItkQBallImgType::Pointer m_ItkQBallImage; + + FiberBuilder(float *points, int numPoints, double spacing[], ItkQBallImgType::Pointer image) { - m_FiberContainer = new FiberContainerType(); + m_ItkQBallImage = image; particles = (Particle*) malloc(sizeof(Particle)*numPoints); pcnt = numPoints; attrcnt = 10; for (int k = 0; k < numPoints; k++) { Particle *p = &(particles[k]); - p->R = pVector(points[attrcnt*k]/spacing[0], points[attrcnt*k+1]/spacing[1],points[attrcnt*k+2]/spacing[2]); + p->R = pVector(points[attrcnt*k]/spacing[0]-0.5, points[attrcnt*k+1]/spacing[1]-0.5,points[attrcnt*k+2]/spacing[2]-0.5); p->N = pVector(points[attrcnt*k+3],points[attrcnt*k+4],points[attrcnt*k+5]); p->cap = points[attrcnt*k+6]; p->len = points[attrcnt*k+7]; p->mID = (int) points[attrcnt*k+8]; p->pID = (int) points[attrcnt*k+9]; p->ID = k; p->label = 0; } + m_VtkCellArray = vtkSmartPointer::New(); + m_VtkPoints = vtkSmartPointer::New(); } - ~CCAnalysis() + ~FiberBuilder() { - for (int i=0; isize(); i++) - delete(m_FiberContainer->at(i)); - delete(m_FiberContainer); free(particles); } - int iterate(int minSize) + vtkSmartPointer iterate(int minSize) { int cur_label = 1; int numFibers = 0; for (int k = 0; k < pcnt;k++) { Particle *dp = &(particles[k]); if (dp->label == 0) { - ParticleContainerType* container = new ParticleContainerType(); + vtkSmartPointer container = vtkSmartPointer::New(); dp->label = cur_label; dp->numerator = 0; labelPredecessors(dp, container); labelSuccessors(dp, container); - //labelrecursivly(dp, 0); cur_label++; - if(container->size()>minSize){ - m_FiberContainer->push_back(container); + if(container->GetPointIds()->GetNumberOfIds()>minSize) + { + m_VtkCellArray->InsertNextCell(container); numFibers++; } } } - return numFibers; + vtkSmartPointer fiberPolyData = vtkSmartPointer::New(); + fiberPolyData->SetPoints(m_VtkPoints); + fiberPolyData->SetLines(m_VtkCellArray); + return fiberPolyData; + } + + void AddPoint(Particle *dp, vtkSmartPointer container) + { + itk::ContinuousIndex index; + index[0] = dp->R[0]; + index[1] = dp->R[1]; + index[2] = dp->R[2]; + itk::Point point; + m_ItkQBallImage->TransformContinuousIndexToPhysicalPoint( index, point ); + vtkIdType id = m_VtkPoints->InsertNextPoint(point.GetDataPointer()); + container->GetPointIds()->InsertNextId(id); } - void labelPredecessors(Particle *dp, ParticleContainerType* container) + void labelPredecessors(Particle *dp, vtkSmartPointer container) { if (dp->mID != -1 && dp->mID!=dp->ID) { if (dp->ID!=particles[dp->mID].pID) { if (dp->ID==particles[dp->mID].mID) { int tmp = particles[dp->mID].pID; particles[dp->mID].pID = particles[dp->mID].mID; particles[dp->mID].mID = tmp; } } if (particles[dp->mID].label == 0) { particles[dp->mID].label = dp->label; particles[dp->mID].numerator = dp->numerator-1; labelPredecessors(&(particles[dp->mID]), container); } } - container->push_back(dp); + AddPoint(dp, container); } - void labelSuccessors(Particle *dp, ParticleContainerType* container) + + void labelSuccessors(Particle *dp, vtkSmartPointer container) { - if(container->back()->ID!=dp->ID) - container->push_back(dp); + AddPoint(dp, container); if (dp->pID != -1 && dp->pID!=dp->ID) { if (dp->ID!=particles[dp->pID].mID) { if (dp->ID==particles[dp->pID].pID) { int tmp = particles[dp->pID].pID; particles[dp->pID].pID = particles[dp->pID].mID; particles[dp->pID].mID = tmp; } } if (particles[dp->pID].label == 0) { particles[dp->pID].label = dp->label; particles[dp->pID].numerator = dp->numerator+1; labelSuccessors(&(particles[dp->pID]), container); } } } - - void labelrecursivly(Particle *dp, int depth) - { - int label = dp->label; - - if (dp->mID != -1) - { - if (particles[dp->mID].label == 0) - { - particles[dp->mID].label = label; - labelrecursivly(&(particles[dp->mID]),depth+1); - } - } - if (dp->pID != -1) - { - if (particles[dp->pID].label == 0) - { - particles[dp->pID].label = label; - labelrecursivly(&(particles[dp->pID]),depth+1); - } - } - } }; - - - - -//klaus static int cmpfloat2(const void *p1,const void *p2) -//klaus { -//klaus if (((REAL*)p1)[1] > ((REAL*)p2)[1]) -//klaus return 1; -//klaus else -//klaus return -1; -//klaus } - - - -typedef std::vector vecint; - - - -//void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) -//{ -// -// if(nrhs != 2) { -// printf("\nUsage: Df = STderivative(f)\n\n",nrhs); -// printf(" Computes xxx\n"); -// printf(" Parameters:\n"); -// printf(" f - 2D input image of type REAL \n"); -// printf(" Return value Df contains xxx.\n\n"); -// return; -// } else if(nlhs>2) { -// printf("Too many output arguments\n"); -// return; -// } -// -// fprintf(stderr,"building fibers "); fflush(stderr); -// -// int pcnt = 0; -// const mxArray *Points; -// Points = prhs[pcnt++]; -// int numPoints = mxGetN(Points); -// REAL *points = (REAL*) mxGetData(Points); -// -// -// const mxArray *Params; -// Params = prhs[pcnt++]; -// double *params = (double*) mxGetPr(Params); -// -// -// int minnumelements = (int) params[0]; -// -// -// CCAnalysis ccana(points,numPoints); -// -// #ifdef TIMING -// -// #endif -// -// int numc = ccana.iterate(); -// -// fprintf(stderr,"."); fflush(stderr); -// -// vector components(numc); -// -// int i; -// -// for (i = 0;i < ccana.pcnt;i++) -// { -// components[ccana.particles[i].label-1].push_back(i); -// } -// -// fprintf(stderr,"."); fflush(stderr); -// -// for (i = 0; i < numc; i++) -// { -// Particle *last = &(ccana.particles[components[i][0]]); -// last->numerator = 0; -// Particle *next = (last->pID == -1)? 0 : &(ccana.particles[last->pID]); -// for (;;) -// { -// if (next == 0) -// break; -// next->numerator = last->numerator+1; -// int nextID = -1; -// if (next->pID != last->ID) -// nextID = next->pID; -// if (next->mID != last->ID) -// nextID = next->mID; -// last = next; -// next = (nextID == -1)? 0: &(ccana.particles[nextID]); -// if (last->numerator > components[i].size()) // circular -// break; -// } -// -// last = &(ccana.particles[components[i][0]]); -// next = (last->mID == -1)? 0 : &(ccana.particles[last->mID]); -// for (;;) -// { -// if (next == 0) -// break; -// next->numerator = last->numerator-1; -// int nextID = -1; -// if (next->pID != last->ID) -// nextID = next->pID; -// if (next->mID != last->ID) -// nextID = next->mID; -// last = next; -// next = (nextID == -1)? 0: &(ccana.particles[nextID]); -// if (last->numerator < -components[i].size()) // circular -// break; -// } -// -// } -// -// fprintf(stderr,"."); fflush(stderr); -// -// -// #ifdef TIMING -// -// #endif -// -// int index = 0; -// for (i = 0; i < numc; i++) -// { -// if (components[i].size() >= minnumelements) -// { -// index++; -// } -// } -// -// int cdims[] = {index}; -// plhs[0] = mxCreateCellArray(1,cdims); -// -// index = 0; -// for (i = 0; i < numc; i++) -// { -// mxArray *ll = 0; -// if (components[i].size() >= minnumelements) -// { -// ll = mxCreateNumericMatrix(2,components[i].size(),mxGetClassID(Points),mxREAL); -// REAL *dat = (REAL*) mxGetData(ll); -// for (int k = 0; k < components[i].size(); k++) -// { -// dat[2*k] = components[i][k]; -// dat[2*k+1] = ccana.particles[components[i][k]].numerator; -// } -// qsort(dat,components[i].size(),sizeof(REAL)*2,cmpfloat2); -// mxSetCell(plhs[0],index++,ll); -// } -// } -// -// fprintf(stderr,".\n"); fflush(stderr); -// -//} -// - #endif diff --git a/Modules/DiffusionImaging/Tractography/GibbsTracking/EnergyComputerBase.cpp b/Modules/DiffusionImaging/Tractography/GibbsTracking/EnergyComputerBase.cpp index 9a2f4c5711..3b2d58cf82 100644 --- a/Modules/DiffusionImaging/Tractography/GibbsTracking/EnergyComputerBase.cpp +++ b/Modules/DiffusionImaging/Tractography/GibbsTracking/EnergyComputerBase.cpp @@ -1,368 +1,369 @@ #ifndef _ENCOMPINTERFACE #define _ENCOMPINTERFACE #include "SphereInterpolator.cpp" #include "ParticleGrid.cpp" #include #include +#include inline float myATAN2(float y,float x) { float phi = acos(x); // float phi = ((x>=1.0) ? ((0.0000*x+-0.0000)) : ((x>=1.0) ? ((-10.0167*x+10.0167)) : ((x>=0.9) ? ((-3.1336*x+3.2713)) : ((x>=0.8) ? ((-1.9247*x+2.1833)) : ((x>=0.5) ? ((-1.3457*x+1.7200)) : ((x>=0.0) ? ((-1.0472*x+1.5708)) : ((x>=-0.5) ? ((-1.0472*x+1.5708)) : ((x>=-0.8) ? ((-1.3457*x+1.4216)) : ((x>=-0.9) ? ((-1.9247*x+0.9583)) : ((x>=-1.0) ? ((-3.1336*x+-0.1297)) : ((x>=-1.0) ? ((-10.0167*x+-6.8751)) : 1 ))))))))))); if (y < 0) phi = 2*PI - phi; if (phi<0) phi = phi + PI; return phi; } class EnergyComputerBase { public: float *m_QBallImageData; const int *m_QBallImageSize; SphereInterpolator *m_SphereInterpolator; ParticleGrid *m_ParticleGrid; int w,h,d; float voxsize_w; float voxsize_h; float voxsize_d; int w_sp,h_sp,d_sp; float voxsize_sp_w; float voxsize_sp_h; float voxsize_sp_d; int nip; // number of data vertices on sphere float *m_MaskImageData; float *cumulspatprob; int *spatidx; int scnt; float eigen_energy; vnl_matrix_fixed m_RotationMatrix; EnergyComputerBase(float *qBallImageData, const int *qBallImageSize, double *voxsize, SphereInterpolator *sp, ParticleGrid *pcon, float *maskImageData, int spmult, vnl_matrix_fixed rotMatrix) { m_RotationMatrix = rotMatrix; m_QBallImageData = qBallImageData; m_QBallImageSize = qBallImageSize; m_SphereInterpolator = sp; m_MaskImageData = maskImageData; nip = m_QBallImageSize[0]; w = m_QBallImageSize[1]; h = m_QBallImageSize[2]; d = m_QBallImageSize[3]; voxsize_w = voxsize[0]; voxsize_h = voxsize[1]; voxsize_d = voxsize[2]; w_sp = m_QBallImageSize[1]*spmult; h_sp = m_QBallImageSize[2]*spmult; d_sp = m_QBallImageSize[3]*spmult; voxsize_sp_w = voxsize[0]/spmult; voxsize_sp_h = voxsize[1]/spmult; voxsize_sp_d = voxsize[2]/spmult; fprintf(stderr,"Data size (voxels) : %i x %i x %i\n",w,h,d); fprintf(stderr,"voxel size: %f x %f x %f\n",voxsize_w,voxsize_h,voxsize_d); fprintf(stderr,"mask_oversamp_mult: %i\n",spmult); if (nip != sp->nverts) { fprintf(stderr,"EnergyComputer: error during init: data does not match with interpolation scheme\n"); } m_ParticleGrid = pcon; int totsz = w_sp*h_sp*d_sp; cumulspatprob = (float*) malloc(sizeof(float) * totsz); spatidx = (int*) malloc(sizeof(int) * totsz); if (cumulspatprob == 0 || spatidx == 0) { fprintf(stderr,"EnergyCOmputerBase: out of memory!\n"); return ; } scnt = 0; cumulspatprob[0] = 0; for (int x = 1; x < w_sp;x++) for (int y = 1; y < h_sp;y++) for (int z = 1; z < d_sp;z++) { int idx = x+(y+z*h_sp)*w_sp; if (m_MaskImageData[idx] > 0.5) { cumulspatprob[scnt+1] = cumulspatprob[scnt] + m_MaskImageData[idx]; spatidx[scnt] = idx; scnt++; } } for (int k = 0; k < scnt; k++) { cumulspatprob[k] /= cumulspatprob[scnt]; } fprintf(stderr,"#active voxels: %i (in mask units) \n",scnt); } ~EnergyComputerBase() { free(cumulspatprob); free(spatidx); } virtual void setParameters() { } void drawSpatPosition(pVector *R) { float r = mtrand.frand(); int j; int rl = 1; int rh = scnt; while(rh != rl) { j = rl + (rh-rl)/2; if (r < cumulspatprob[j]) { rh = j; continue; } if (r > cumulspatprob[j]) { rl = j+1; continue; } break; } R->SetXYZ(voxsize_sp_w*((float)(spatidx[rh-1] % w_sp) + mtrand.frand()), voxsize_sp_h*((float)((spatidx[rh-1]/w_sp) % h_sp) + mtrand.frand()), voxsize_sp_d*((float)(spatidx[rh-1]/(w_sp*h_sp)) + mtrand.frand())); } float SpatProb(pVector R) { int rx = int(R.GetX()/voxsize_sp_w); int ry = int(R.GetY()/voxsize_sp_h); int rz = int(R.GetZ()/voxsize_sp_d); if (rx >= 0 && rx < w_sp && ry >= 0 && ry < h_sp && rz >= 0 && rz < d_sp){ return m_MaskImageData[rx + w_sp* (ry + h_sp*rz)]; } else return 0; } /* inline float evaluateODF(pVector &R, pVector &N, float &len) { const int CU = 10; pVector Rs; float Dn = 0; int xint,yint,zint,spatindex; sinterp->getInterpolation(N); for (int i=-CU; i < CU;i++) { Rs = R + (N * len) * ((float)i/CU); xint = int(Rs.x); yint = int(Rs.y); zint = int(Rs.z); if (xint > 0 && xint < w-1 && yint > 0 && yint < h-1 && zint > 0 && zint < d-1) { spatindex = (xint + w*(yint+h*zint)) *nip; Dn += (dataimg[spatindex + sinterp->idx[0]]*sinterp->interpw[0] + dataimg[spatindex + sinterp->idx[1]]*sinterp->interpw[1] + dataimg[spatindex + sinterp->idx[2]]* sinterp->interpw[2]); } } Dn /= (float)(2*CU+1); return Dn; } */ inline float evaluateODF(pVector &R, pVector &N, float &len) { const int CU = 10; pVector Rs; float Dn = 0; int xint,yint,zint,spatindex; vnl_vector_fixed n; n[0] = N[0]; n[1] = N[1]; n[2] = N[2]; n = m_RotationMatrix*n; m_SphereInterpolator->getInterpolation(n); for (int i=-CU; i <= CU;i++) { Rs = R + (N * len) * ((float)i/CU); float Rx = Rs[0]/voxsize_w-0.5; float Ry = Rs[1]/voxsize_h-0.5; float Rz = Rs[2]/voxsize_d-0.5; xint = int(floor(Rx)); yint = int(floor(Ry)); zint = int(floor(Rz)); if (xint >= 0 && xint < w-1 && yint >= 0 && yint < h-1 && zint >= 0 && zint < d-1) { float xfrac = Rx-xint; float yfrac = Ry-yint; float zfrac = Rz-zint; float weight; weight = (1-xfrac)*(1-yfrac)*(1-zfrac); spatindex = (xint + w*(yint+h*zint)) *nip; Dn += (m_QBallImageData[spatindex + m_SphereInterpolator->idx[0]-1]*m_SphereInterpolator->interpw[0] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[1]-1]*m_SphereInterpolator->interpw[1] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[2]-1]* m_SphereInterpolator->interpw[2])*weight; weight = (xfrac)*(1-yfrac)*(1-zfrac); spatindex = (xint+1 + w*(yint+h*zint)) *nip; Dn += (m_QBallImageData[spatindex + m_SphereInterpolator->idx[0]-1]*m_SphereInterpolator->interpw[0] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[1]-1]*m_SphereInterpolator->interpw[1] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[2]-1]* m_SphereInterpolator->interpw[2])*weight; weight = (1-xfrac)*(yfrac)*(1-zfrac); spatindex = (xint + w*(yint+1+h*zint)) *nip; Dn += (m_QBallImageData[spatindex + m_SphereInterpolator->idx[0]-1]*m_SphereInterpolator->interpw[0] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[1]-1]*m_SphereInterpolator->interpw[1] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[2]-1]* m_SphereInterpolator->interpw[2])*weight; weight = (1-xfrac)*(1-yfrac)*(zfrac); spatindex = (xint + w*(yint+h*(zint+1))) *nip; Dn += (m_QBallImageData[spatindex + m_SphereInterpolator->idx[0]-1]*m_SphereInterpolator->interpw[0] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[1]-1]*m_SphereInterpolator->interpw[1] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[2]-1]* m_SphereInterpolator->interpw[2])*weight; weight = (xfrac)*(yfrac)*(1-zfrac); spatindex = (xint+1 + w*(yint+1+h*zint)) *nip; Dn += (m_QBallImageData[spatindex + m_SphereInterpolator->idx[0]-1]*m_SphereInterpolator->interpw[0] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[1]-1]*m_SphereInterpolator->interpw[1] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[2]-1]* m_SphereInterpolator->interpw[2])*weight; weight = (1-xfrac)*(yfrac)*(zfrac); spatindex = (xint + w*(yint+1+h*(zint+1))) *nip; Dn += (m_QBallImageData[spatindex + m_SphereInterpolator->idx[0]-1]*m_SphereInterpolator->interpw[0] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[1]-1]*m_SphereInterpolator->interpw[1] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[2]-1]* m_SphereInterpolator->interpw[2])*weight; weight = (xfrac)*(1-yfrac)*(zfrac); spatindex = (xint+1 + w*(yint+h*(zint+1))) *nip; Dn += (m_QBallImageData[spatindex + m_SphereInterpolator->idx[0]-1]*m_SphereInterpolator->interpw[0] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[1]-1]*m_SphereInterpolator->interpw[1] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[2]-1]* m_SphereInterpolator->interpw[2])*weight; weight = (xfrac)*(yfrac)*(zfrac); spatindex = (xint+1 + w*(yint+1+h*(zint+1))) *nip; Dn += (m_QBallImageData[spatindex + m_SphereInterpolator->idx[0]-1]*m_SphereInterpolator->interpw[0] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[1]-1]*m_SphereInterpolator->interpw[1] + m_QBallImageData[spatindex + m_SphereInterpolator->idx[2]-1]* m_SphereInterpolator->interpw[2])*weight; } } Dn *= 1.0/(2*CU+1); return Dn; } /* inline float evaluateODF(pVector &R, pVector &N, float &len) { R.storeXYZ(); float Rx = pVector::store[0]/voxsize_w; float Ry = pVector::store[1]/voxsize_h; float Rz = pVector::store[2]/voxsize_d; int xint = int(Rx); int yint = int(Ry); int zint = int(Rz); if (xint >= 0 && xint < w-1 && yint >= 0 && yint < h-1 && zint >= 0 && zint < d-1) { float xfrac = Rx-xint; float yfrac = Ry-yint; float zfrac = Rz-zint; sinterp->getInterpolation(N); float weight; int spatindex; float Dn = 0; weight = (1-xfrac)*(1-yfrac)*(1-zfrac); spatindex = (xint + w*(yint+h*zint)) *nip; Dn += (dataimg[spatindex + sinterp->idx[0]]*sinterp->interpw[0] + dataimg[spatindex + sinterp->idx[1]]*sinterp->interpw[1] + dataimg[spatindex + sinterp->idx[2]]* sinterp->interpw[2])*weight; weight = (xfrac)*(1-yfrac)*(1-zfrac); spatindex = (xint+1 + w*(yint+h*zint)) *nip; Dn += (dataimg[spatindex + sinterp->idx[0]]*sinterp->interpw[0] + dataimg[spatindex + sinterp->idx[1]]*sinterp->interpw[1] + dataimg[spatindex + sinterp->idx[2]]* sinterp->interpw[2])*weight; weight = (1-xfrac)*(yfrac)*(1-zfrac); spatindex = (xint + w*(yint+1+h*zint)) *nip; Dn += (dataimg[spatindex + sinterp->idx[0]]*sinterp->interpw[0] + dataimg[spatindex + sinterp->idx[1]]*sinterp->interpw[1] + dataimg[spatindex + sinterp->idx[2]]* sinterp->interpw[2])*weight; weight = (1-xfrac)*(1-yfrac)*(zfrac); spatindex = (xint + w*(yint+h*(zint+1))) *nip; Dn += (dataimg[spatindex + sinterp->idx[0]]*sinterp->interpw[0] + dataimg[spatindex + sinterp->idx[1]]*sinterp->interpw[1] + dataimg[spatindex + sinterp->idx[2]]* sinterp->interpw[2])*weight; weight = (xfrac)*(yfrac)*(1-zfrac); spatindex = (xint+1 + w*(yint+1+h*zint)) *nip; Dn += (dataimg[spatindex + sinterp->idx[0]]*sinterp->interpw[0] + dataimg[spatindex + sinterp->idx[1]]*sinterp->interpw[1] + dataimg[spatindex + sinterp->idx[2]]* sinterp->interpw[2])*weight; weight = (1-xfrac)*(yfrac)*(zfrac); spatindex = (xint + w*(yint+1+h*(zint+1))) *nip; Dn += (dataimg[spatindex + sinterp->idx[0]]*sinterp->interpw[0] + dataimg[spatindex + sinterp->idx[1]]*sinterp->interpw[1] + dataimg[spatindex + sinterp->idx[2]]* sinterp->interpw[2])*weight; weight = (xfrac)*(1-yfrac)*(zfrac); spatindex = (xint+1 + w*(yint+h*(zint+1))) *nip; Dn += (dataimg[spatindex + sinterp->idx[0]]*sinterp->interpw[0] + dataimg[spatindex + sinterp->idx[1]]*sinterp->interpw[1] + dataimg[spatindex + sinterp->idx[2]]* sinterp->interpw[2])*weight; weight = (xfrac)*(yfrac)*(zfrac); spatindex = (xint+1 + w*(yint+1+h*(zint+1))) *nip; Dn += (dataimg[spatindex + sinterp->idx[0]]*sinterp->interpw[0] + dataimg[spatindex + sinterp->idx[1]]*sinterp->interpw[1] + dataimg[spatindex + sinterp->idx[2]]* sinterp->interpw[2])*weight; return Dn; } return 0; } */ virtual inline float computeExternalEnergy(pVector &R, pVector &N, float &cap, float &len, Particle *dp) { return 0;} virtual inline float computeInternalEnergy(Particle *p1) {return 0;} virtual inline float computeInternalEnergyConnection(Particle *p1,int ep1) {return 0;} virtual inline float computeInternalEnergyConnection(Particle *p1,int ep1, Particle *p2, int ep2) {return 0;} }; #endif diff --git a/Modules/DiffusionImaging/Tractography/GibbsTracking/RJMCMC_randshift.cpp b/Modules/DiffusionImaging/Tractography/GibbsTracking/RJMCMC_randshift.cpp index 0b83f23287..299e787783 100644 --- a/Modules/DiffusionImaging/Tractography/GibbsTracking/RJMCMC_randshift.cpp +++ b/Modules/DiffusionImaging/Tractography/GibbsTracking/RJMCMC_randshift.cpp @@ -1,618 +1,620 @@ #include "ParticleGrid.cpp" #include "RJMCMCBase.cpp" #include class RJMCMC : public RJMCMCBase { public: float T_in ; float T_ex ; float dens; float p_birth; float p_death; float p_shift; float p_shiftopt; float p_cap; float p_con; float sigma_g; float gamma_g; float Z_g; float dthres; float nthres; float T_prop; float stopprobability; float del_prob; float len_def; float len_sig; float cap_def; float cap_sig; float externalEnergy; float internalEnergy; float m_ChempotParticle; Track TrackProposal, TrackBackup; SimpSamp simpsamp; RJMCMC(float *points,int numPoints, float *dimg, const int *dsz, double *voxsz, double cellsz) : RJMCMCBase(points,numPoints,dimg,dsz,voxsz,cellsz) { externalEnergy = 0; internalEnergy = 0; } void SetParameters(float Temp, int numit, float plen, float curv_hardthres, float chempot_particle) { m_Iterations = numit; p_birth = 0.25; p_death = 0.05; p_shift = 0.15; p_shiftopt = 0.1; p_con = 0.45; p_cap = 0.0; m_ChempotParticle = chempot_particle; float sum = p_birth+p_death+p_shift+p_shiftopt+p_con; p_birth /= sum; p_death /= sum; p_shift /= sum; p_shiftopt /= sum; T_in = Temp; T_ex = 0.01; dens = exp(-chempot_particle/T_in); len_def = plen; len_sig = 0.0; cap_def = 1.0; cap_sig = 0.0; // shift proposal sigma_g = len_def/8.0; gamma_g = 1/(sigma_g*sigma_g*2); Z_g = pow(2*PI*sigma_g,3.0/2.0)*(PI*sigma_g/len_def); // conn proposal dthres = len_def; nthres = curv_hardthres; T_prop = 0.5; dthres *= dthres; stopprobability = exp(-1/T_prop); del_prob = 0.1; } void SetTemperature(float temp) { T_in = temp; dens = exp(-m_ChempotParticle/T_in); } void IterateOneStep() { float randnum = mtrand.frand(); //randnum = 0; /////////////////////////////////////////////////////////////// //////// Birth Proposal /////////////////////////////////////////////////////////////// if (randnum < p_birth) { #ifdef TIMING tic(&birthproposal_time); birthstats.propose(); #endif pVector R; enc->drawSpatPosition(&R); + + //fprintf(stderr,"drawn: %f, %f, %f\n",R[0],R[1],R[2]); //R.setXYZ(20.5*3, 35.5*3, 1.5*3); pVector N; N.rand_sphere(); //N.setXYZ(1,0,0); float cap = cap_def - cap_sig*mtrand.frand(); float len = len_def;// + len_sig*(mtrand.frand()-0.5); Particle prop; prop.R = R; prop.N = N; prop.cap = cap; prop.len = len; float prob = dens * p_death /((p_birth)*(m_ParticleGrid.pcnt+1)); float ex_energy = enc->computeExternalEnergy(R,N,cap,len,0); float in_energy = enc->computeInternalEnergy(&prop); prob *= exp((in_energy/T_in+ex_energy/T_ex)) ; if (prob > 1 || mtrand.frand() < prob) { Particle *p = m_ParticleGrid.newParticle(R); if (p!=0) { p->R = R; p->N = N; p->cap = cap; p->len = len; #ifdef TIMING birthstats.accepted(); #endif m_AcceptedProposals++; } } #ifdef TIMING toc(&birthproposal_time); #endif } /////////////////////////////////////////////////////////////// //////// Death Proposal /////////////////////////////////////////////////////////////// else if (randnum < p_birth+p_death) { if (m_ParticleGrid.pcnt > 0) { #ifdef TIMING tic(&deathproposal_time); deathstats.propose(); #endif int pnum = rand()%m_ParticleGrid.pcnt; Particle *dp = &(m_ParticleGrid.particles[pnum]); if (dp->pID == -1 && dp->mID == -1) { float ex_energy = enc->computeExternalEnergy(dp->R,dp->N,dp->cap,dp->len,dp); float in_energy = enc->computeInternalEnergy(dp); float prob = m_ParticleGrid.pcnt * (p_birth) /(dens*p_death); //*SpatProb(dp->R); prob *= exp(-(in_energy/T_in+ex_energy/T_ex)) ; if (prob > 1 || mtrand.frand() < prob) { m_ParticleGrid.remove(pnum); #ifdef TIMING deathstats.accepted(); #endif m_AcceptedProposals++; } } #ifdef TIMING toc(&deathproposal_time); #endif } } /////////////////////////////////////////////////////////////// //////// Cap change Proposal /////////////////////////////////////////////////////////////// else if (randnum < p_birth+p_death+p_cap) { if (m_ParticleGrid.pcnt > 0) { int pnum = rand()%m_ParticleGrid.pcnt; Particle *p = &(m_ParticleGrid.particles[pnum]); Particle prop_p = *p; prop_p.cap = cap_def - cap_sig*mtrand.frand(); float ex_energy = enc->computeExternalEnergy(prop_p.R,prop_p.N,prop_p.cap,p->len,p) - enc->computeExternalEnergy(p->R,p->N,p->cap,p->len,p); //float in_energy = enc->computeExternalEnergy(prop_p.R,prop_p.N,p->cap,p->len,p) // - enc->computeExternalEnergy(p->R,p->N,p->cap,p->len,p); float prob = exp(ex_energy/T_ex); // * SpatProb(p->R) / SpatProb(prop_p.R); if (mtrand.frand() < prob) { p->cap = prop_p.cap; m_AcceptedProposals++; } } } /////////////////////////////////////////////////////////////// //////// Shift Proposal /////////////////////////////////////////////////////////////// else if (randnum < p_birth+p_death+p_shift+p_cap) { float energy = 0; if (m_ParticleGrid.pcnt > 0) { #ifdef TIMING tic(&shiftproposal_time); shiftstats.propose(); #endif int pnum = rand()%m_ParticleGrid.pcnt; Particle *p = &(m_ParticleGrid.particles[pnum]); Particle prop_p = *p; prop_p.R.distortn(sigma_g); prop_p.N.distortn(sigma_g/(2*p->len)); prop_p.N.normalize(); float ex_energy = enc->computeExternalEnergy(prop_p.R,prop_p.N,p->cap,p->len,p) - enc->computeExternalEnergy(p->R,p->N,p->cap,p->len,p); float in_energy = enc->computeInternalEnergy(&prop_p) - enc->computeInternalEnergy(p); float prob = exp(ex_energy/T_ex+in_energy/T_in); // * SpatProb(p->R) / SpatProb(prop_p.R); if (mtrand.frand() < prob) { pVector Rtmp = p->R; pVector Ntmp = p->N; p->R = prop_p.R; p->N = prop_p.N; if (!m_ParticleGrid.tryUpdateGrid(pnum)) { p->R = Rtmp; p->N = Ntmp; } #ifdef TIMING shiftstats.accepted(); #endif m_AcceptedProposals++; } #ifdef TIMING toc(&shiftproposal_time); #endif } } else if (randnum < p_birth+p_death+p_shift+p_shiftopt+p_cap) { float energy = 0; if (m_ParticleGrid.pcnt > 0) { int pnum = rand()%m_ParticleGrid.pcnt; Particle *p = &(m_ParticleGrid.particles[pnum]); bool no_proposal = false; Particle prop_p = *p; if (p->pID != -1 && p->mID != -1) { Particle *plus = m_ParticleGrid.ID_2_address[p->pID]; int ep_plus = (plus->pID == p->ID)? 1 : -1; Particle *minus = m_ParticleGrid.ID_2_address[p->mID]; int ep_minus = (minus->pID == p->ID)? 1 : -1; prop_p.R = (plus->R + plus->N * (plus->len * ep_plus) + minus->R + minus->N * (minus->len * ep_minus))*0.5; prop_p.N = plus->R - minus->R; prop_p.N.normalize(); } else if (p->pID != -1) { Particle *plus = m_ParticleGrid.ID_2_address[p->pID]; int ep_plus = (plus->pID == p->ID)? 1 : -1; prop_p.R = plus->R + plus->N * (plus->len * ep_plus * 2); prop_p.N = plus->N; } else if (p->mID != -1) { Particle *minus = m_ParticleGrid.ID_2_address[p->mID]; int ep_minus = (minus->pID == p->ID)? 1 : -1; prop_p.R = minus->R + minus->N * (minus->len * ep_minus * 2); prop_p.N = minus->N; } else no_proposal = true; if (!no_proposal) { float cos = prop_p.N*p->N; float p_rev = exp(-((prop_p.R-p->R).norm_square() + (1-cos*cos))*gamma_g)/Z_g; float ex_energy = enc->computeExternalEnergy(prop_p.R,prop_p.N,p->cap,p->len,p) - enc->computeExternalEnergy(p->R,p->N,p->cap,p->len,p); float in_energy = enc->computeInternalEnergy(&prop_p) - enc->computeInternalEnergy(p); float prob = exp(ex_energy/T_ex+in_energy/T_in)*p_shift*p_rev/(p_shiftopt+p_shift*p_rev); //* SpatProb(p->R) / SpatProb(prop_p.R); if (mtrand.frand() < prob) { pVector Rtmp = p->R; pVector Ntmp = p->N; p->R = prop_p.R; p->N = prop_p.N; if (!m_ParticleGrid.tryUpdateGrid(pnum)) { p->R = Rtmp; p->N = Ntmp; } m_AcceptedProposals++; } } } } else { if (m_ParticleGrid.pcnt > 0) { #ifdef TIMING tic(&connproposal_time); connstats.propose(); #endif int pnum = rand()%m_ParticleGrid.pcnt; Particle *p = &(m_ParticleGrid.particles[pnum]); EndPoint P; P.p = p; P.ep = (mtrand.frand() > 0.5)? 1 : -1; RemoveAndSaveTrack(P); if (TrackBackup.proposal_probability != 0) { MakeTrackProposal(P); float prob = (TrackProposal.energy-TrackBackup.energy)/T_in ; // prob = exp(prob)*(TrackBackup.proposal_probability) // /(TrackProposal.proposal_probability); prob = exp(prob)*(TrackBackup.proposal_probability * pow(del_prob,TrackProposal.length)) /(TrackProposal.proposal_probability * pow(del_prob,TrackBackup.length)); if (mtrand.frand() < prob) { ImplementTrack(TrackProposal); #ifdef TIMING connstats.accepted(); #endif m_AcceptedProposals++; } else { ImplementTrack(TrackBackup); } } else ImplementTrack(TrackBackup); #ifdef TIMING toc(&connproposal_time); #endif } } } void ImplementTrack(Track &T) { for (int k = 1; k < T.length;k++) { m_ParticleGrid.createConnection(T.track[k-1].p,T.track[k-1].ep,T.track[k].p,-T.track[k].ep); } } void RemoveAndSaveTrack(EndPoint P) { EndPoint Current = P; int cnt = 0; float energy = 0; float AccumProb = 1.0; TrackBackup.track[cnt] = Current; EndPoint Next; for (;;) { Next.p = 0; if (Current.ep == 1) { if (Current.p->pID != -1) { Next.p = m_ParticleGrid.ID_2_address[Current.p->pID]; Current.p->pID = -1; m_ParticleGrid.concnt--; } } else if (Current.ep == -1) { if (Current.p->mID != -1) { Next.p = m_ParticleGrid.ID_2_address[Current.p->mID]; Current.p->mID = -1; m_ParticleGrid.concnt--; } } else { fprintf(stderr,"RJMCMC_randshift: Connection inconsistent 3\n"); break; } if (Next.p == 0) // no successor { Next.ep = 0; // mark as empty successor break; } else { if (Next.p->pID == Current.p->ID) { Next.p->pID = -1; Next.ep = 1; } else if (Next.p->mID == Current.p->ID) { Next.p->mID = -1; Next.ep = -1; } else { fprintf(stderr,"RJMCMC_randshift: Connection inconsistent 4\n"); break; } } ComputeEndPointProposalDistribution(Current); AccumProb *= (simpsamp.probFor(Next)); if (Next.p == 0) // no successor -> break break; energy += enc->computeInternalEnergyConnection(Current.p,Current.ep,Next.p,Next.ep); Current = Next; Current.ep *= -1; cnt++; TrackBackup.track[cnt] = Current; if (mtrand.rand() > del_prob) { break; } } TrackBackup.energy = energy; TrackBackup.proposal_probability = AccumProb; TrackBackup.length = cnt+1; } void MakeTrackProposal(EndPoint P) { EndPoint Current = P; int cnt = 0; float energy = 0; float AccumProb = 1.0; TrackProposal.track[cnt++] = Current; Current.p->label = 1; for (;;) { // next candidate is already connected if ((Current.ep == 1 && Current.p->pID != -1) || (Current.ep == -1 && Current.p->mID != -1)) break; // track too long if (cnt > 250) break; ComputeEndPointProposalDistribution(Current); // // no candidates anymore // if (simpsamp.isempty()) // break; int k = simpsamp.draw(); // stop tracking proposed if (k==0) break; EndPoint Next = simpsamp.objs[k]; float probability = simpsamp.probFor(k); // accumulate energy and proposal distribution energy += enc->computeInternalEnergyConnection(Current.p,Current.ep,Next.p,Next.ep); AccumProb *= probability; // track to next endpoint Current = Next; Current.ep *= -1; Current.p->label = 1; // put label to avoid loops TrackProposal.track[cnt++] = Current; } TrackProposal.energy = energy; TrackProposal.proposal_probability = AccumProb; TrackProposal.length = cnt; // clear labels for (int j = 0; j < TrackProposal.length;j++) { TrackProposal.track[j].p->label = 0; } } void ComputeEndPointProposalDistribution(EndPoint P) { Particle *p = P.p; int ep = P.ep; float dist,dot; pVector R = p->R + (p->N * ep*p->len); m_ParticleGrid.computeNeighbors(R); simpsamp.clear(); simpsamp.add(stopprobability,EndPoint(0,0)); for (;;) { Particle *p2 = m_ParticleGrid.getNextNeighbor(); if (p2 == 0) break; if (p!=p2 && p2->label == 0) { if (p2->mID == -1) { dist = (p2->R - p2->N * p2->len - R).norm_square(); if (dist < dthres) { dot = p2->N*p->N * ep; if (dot > nthres) { float en = enc->computeInternalEnergyConnection(p,ep,p2,-1); simpsamp.add(exp(en/T_prop),EndPoint(p2,-1)); } } } if (p2->pID == -1) { dist = (p2->R + p2->N * p2->len - R).norm_square(); if (dist < dthres) { dot = p2->N*p->N * (-ep); if (dot > nthres) { float en = enc->computeInternalEnergyConnection(p,ep,p2,+1); simpsamp.add(exp(en/T_prop),EndPoint(p2,+1)); } } } } } } }; diff --git a/Modules/DiffusionImaging/Tractography/itkGibbsTrackingFilter.cpp b/Modules/DiffusionImaging/Tractography/itkGibbsTrackingFilter.cpp index 6810c69f0a..5e068d972a 100644 --- a/Modules/DiffusionImaging/Tractography/itkGibbsTrackingFilter.cpp +++ b/Modules/DiffusionImaging/Tractography/itkGibbsTrackingFilter.cpp @@ -1,580 +1,546 @@ #include "itkGibbsTrackingFilter.h" #include #include #include "itkPointShell.h" #include "GibbsTracking/BuildFibres.cpp" #pragma GCC visibility push(default) #include #pragma GCC visibility pop #include -#include -#include #include #include -#include #include "GibbsTracking/reparametrize_arclen2.cpp" #include #include #include #include #include #include struct LessDereference { template bool operator()(const T * lhs, const T * rhs) const { return *lhs < *rhs; } }; namespace itk{ template< class TInputOdfImage, class TInputROIImage > GibbsTrackingFilter< TInputOdfImage, TInputROIImage > ::GibbsTrackingFilter(): m_TempStart(0.1), m_TempEnd(0.001), m_NumIt(500000), m_ParticleWeight(0), m_ParticleWidth(0), m_ParticleLength(0), m_ChempotConnection(10), m_ChempotParticle(0), m_InexBalance(0), m_Chempot2(0.2), m_FiberLength(10), m_AbortTracking(false), m_NumConnections(0), m_NumParticles(0), m_NumAcceptedFibers(0), m_CurrentStep(0), m_SubtractMean(true), m_BuildFibers(false), m_Sampler(NULL), m_Steps(10), m_Memory(0), m_ProposalAcceptance(0), m_GfaImage(NULL) { //this->m_MeasurementFrame.set_identity(); this->SetNumberOfRequiredInputs(2); //Filter needs a DWI image + a Mask Image } template< class TInputOdfImage, class TInputROIImage > GibbsTrackingFilter< TInputOdfImage, TInputROIImage > ::~GibbsTrackingFilter(){ delete BESSEL_APPROXCOEFF; if (m_Sampler!=NULL) delete m_Sampler; } template< class TInputOdfImage, class TInputROIImage > void GibbsTrackingFilter< TInputOdfImage, TInputROIImage > ::ComputeFiberCorrelation(){ float bD = 15; vnl_matrix_fixed bDir = *itk::PointShell >::DistributePointShell(); const int N = QBALL_ODFSIZE; vnl_matrix_fixed temp = bDir.transpose(); vnl_matrix_fixed C = temp*bDir; vnl_matrix_fixed Q = C; vnl_vector_fixed mean; for(int i=0; i repMean; for (int i=0; i P = Q*Q; std::vector pointer; pointer.reserve(N*N); double * start = C.data_block(); double * end = start + N*N; for (double * iter = start; iter != end; ++iter) { pointer.push_back(iter); } std::sort(pointer.begin(), pointer.end(), LessDereference()); vnl_vector_fixed alpha; vnl_vector_fixed beta; for (int i=0; im_Meanval_sq = (sum*sum)/N; vnl_vector_fixed alpha_0; vnl_vector_fixed alpha_2; vnl_vector_fixed alpha_4; vnl_vector_fixed alpha_6; for(int i=0; i T; T.set_column(0,alpha_0); T.set_column(1,alpha_2); T.set_column(2,alpha_4); T.set_column(3,alpha_6); vnl_vector_fixed coeff = vnl_matrix_inverse(T).pinverse()*beta; MITK_INFO << "itkGibbsTrackingFilter: Bessel oefficients: " << coeff; BESSEL_APPROXCOEFF = new float[4]; BESSEL_APPROXCOEFF[0] = coeff(0); BESSEL_APPROXCOEFF[1] = coeff(1); BESSEL_APPROXCOEFF[2] = coeff(2); BESSEL_APPROXCOEFF[3] = coeff(3); // BESSEL_APPROXCOEFF[0] = -0.1714; // BESSEL_APPROXCOEFF[1] = 0.5332; // BESSEL_APPROXCOEFF[2] = -1.4889; // BESSEL_APPROXCOEFF[3] = 2.0389; } // build fibers from tracking result template< class TInputOdfImage, class TInputROIImage > void GibbsTrackingFilter< TInputOdfImage, TInputROIImage > ::BuildFibers(float* points, int numPoints) { - MITK_INFO << "itkGibbsTrackingFilter: Building fibers ..."; + MITK_INFO << "itkGibbsTrackingFilter: Building fibers ..."; - typename InputQBallImageType::Pointer odfImage - = dynamic_cast(this->GetInput(0)); - double spacing[3]; - spacing[0] = odfImage->GetSpacing().GetElement(0); - spacing[1] = odfImage->GetSpacing().GetElement(1); - spacing[2] = odfImage->GetSpacing().GetElement(2); + double spacing[3]; + spacing[0] = m_ItkQBallImage->GetSpacing().GetElement(0); + spacing[1] = m_ItkQBallImage->GetSpacing().GetElement(1); + spacing[2] = m_ItkQBallImage->GetSpacing().GetElement(2); - // initialize array of particles - CCAnalysis ccana(points, numPoints, spacing); + m_FiberPolyData = FiberPolyDataType::New(); - // label the particles according to fiber affiliation and return number of fibers - int numFibers = ccana.iterate(m_FiberLength); + // initialize array of particles + FiberBuilder fiberBuilder(points, numPoints, spacing, m_ItkQBallImage); + // label the particles according to fiber affiliation and return polydata + m_FiberPolyData = fiberBuilder.iterate(m_FiberLength); + m_NumAcceptedFibers = m_FiberPolyData->GetNumberOfLines(); - if (numFibers<=0){ - MITK_INFO << "itkGibbsTrackingFilter: 0 fibers accepted"; - return; - } - - // fill output datastructure - m_FiberBundle.clear(); - for (int i = 0; i < numFibers; i++) - { - vector< Particle* >* particleContainer = ccana.m_FiberContainer->at(i); - - // resample fibers - std::vector< Particle* >* pCon = ResampleFibers(particleContainer, 0.9*spacing[0]); - - FiberTractType tract; - for (int j=0; jsize(); j++) - { - Particle* particle = pCon->at(j); - pVector p = particle->R; - - itk::Point point; - point[0] = p[0]-0.5; - point[1] = p[1]-0.5; - point[2] = p[2]-0.5; - tract.push_back(point); - delete(particle); - } - m_FiberBundle.push_back(tract); - delete(pCon); - } - m_NumAcceptedFibers = numFibers; - MITK_INFO << "itkGibbsTrackingFilter: " << numFibers << " fibers accepted"; + MITK_INFO << "itkGibbsTrackingFilter: " << m_NumAcceptedFibers << " accepted"; } // fill output fiber bundle datastructure template< class TInputOdfImage, class TInputROIImage > -typename GibbsTrackingFilter< TInputOdfImage, TInputROIImage >::FiberBundleType* +typename GibbsTrackingFilter< TInputOdfImage, TInputROIImage >::FiberPolyDataType GibbsTrackingFilter< TInputOdfImage, TInputROIImage > ::GetFiberBundle() { if (!m_AbortTracking) { m_BuildFibers = true; while (m_BuildFibers){} } - return &m_FiberBundle; + return m_FiberPolyData; } // get memory allocated for particle grid template< class TInputOdfImage, class TInputROIImage > float GibbsTrackingFilter< TInputOdfImage, TInputROIImage > ::GetMemoryUsage() { if (m_Sampler!=NULL) return m_Sampler->m_ParticleGrid.GetMemoryUsage(); return 0; } template< class TInputOdfImage, class TInputROIImage > bool GibbsTrackingFilter< TInputOdfImage, TInputROIImage > ::EstimateParticleWeight(){ if (m_GfaImage.IsNull()) { MITK_INFO << "no gfa image found"; return false; } float samplingStart = 1.0; float samplingStop = 0.66; // copy GFA image (original should not be changed) typedef itk::ImageDuplicator< GfaImageType > DuplicateFilterType; DuplicateFilterType::Pointer duplicator = DuplicateFilterType::New(); duplicator->SetInputImage( m_GfaImage ); duplicator->Update(); m_GfaImage = duplicator->GetOutput(); //// GFA iterator //// typedef ImageRegionIterator< GfaImageType > GfaIteratorType; GfaIteratorType gfaIt(m_GfaImage, m_GfaImage->GetLargestPossibleRegion() ); //// Mask iterator //// typedef ImageRegionConstIterator< MaskImageType > MaskIteratorType; MaskIteratorType maskIt(m_MaskImage, m_MaskImage->GetLargestPossibleRegion() ); // set unmasked region of gfa image to 0 gfaIt.GoToBegin(); maskIt.GoToBegin(); while( !gfaIt.IsAtEnd() ) { if(maskIt.Get()<=0) gfaIt.Set(0); ++gfaIt; ++maskIt; } // rescale gfa image to [0,1] typedef itk::RescaleIntensityImageFilter< GfaImageType, GfaImageType > RescaleFilterType; RescaleFilterType::Pointer rescaleFilter = RescaleFilterType::New(); rescaleFilter->SetInput( m_GfaImage ); rescaleFilter->SetOutputMaximum( samplingStart ); rescaleFilter->SetOutputMinimum( 0 ); rescaleFilter->Update(); m_GfaImage = rescaleFilter->GetOutput(); gfaIt = GfaIteratorType(m_GfaImage, m_GfaImage->GetLargestPossibleRegion() ); //// Input iterator //// typedef ImageRegionConstIterator< InputQBallImageType > InputIteratorType; InputIteratorType git(m_ItkQBallImage, m_ItkQBallImage->GetLargestPossibleRegion() ); float upper = 0; int count = 0; for(float thr=samplingStart; thr>samplingStop; thr-=0.01) { git.GoToBegin(); gfaIt.GoToBegin(); while( !gfaIt.IsAtEnd() ) { if(gfaIt.Get()>thr) { itk::OrientationDistributionFunction odf(git.Get().GetDataPointer()); upper += odf.GetMaxValue()-odf.GetMeanValue(); ++count; } ++gfaIt; ++git; } } if (count>0) upper /= count; else return false; m_ParticleWeight = upper/6; return true; } // perform global tracking template< class TInputOdfImage, class TInputROIImage > void GibbsTrackingFilter< TInputOdfImage, TInputROIImage > ::GenerateData(){ // input qball image m_ItkQBallImage = dynamic_cast(this->GetInput(0)); // approximationscoeffizienten der // teilchenkorrelationen im orientierungsraum // 4er vektor ComputeFiberCorrelation(); // image sizes and spacing int qBallImageSize[4] = {QBALL_ODFSIZE, m_ItkQBallImage->GetLargestPossibleRegion().GetSize().GetElement(0), m_ItkQBallImage->GetLargestPossibleRegion().GetSize().GetElement(1), m_ItkQBallImage->GetLargestPossibleRegion().GetSize().GetElement(2)}; double qBallImageSpacing[3] = {m_ItkQBallImage->GetSpacing().GetElement(0),m_ItkQBallImage->GetSpacing().GetElement(1),m_ItkQBallImage->GetSpacing().GetElement(2)}; // make sure image has enough slices if (qBallImageSize[1]<3 || qBallImageSize[2]<3 || qBallImageSize[3]<3) { MITK_INFO << "itkGibbsTrackingFilter: image size < 3 not supported"; m_AbortTracking = true; } // calculate rotation matrix vnl_matrix_fixed directionMatrix = m_ItkQBallImage->GetDirection().GetVnlMatrix(); vnl_vector_fixed d0 = directionMatrix.get_column(0); d0.normalize(); vnl_vector_fixed d1 = directionMatrix.get_column(1); d1.normalize(); vnl_vector_fixed d2 = directionMatrix.get_column(2); d2.normalize(); directionMatrix.set_column(0, d0); directionMatrix.set_column(1, d1); directionMatrix.set_column(2, d2); vnl_matrix_fixed I = directionMatrix*directionMatrix.transpose(); if(!I.is_identity(mitk::eps)){ MITK_INFO << "itkGibbsTrackingFilter: image direction is not a rotation matrix. Tracking not possible!"; m_AbortTracking = true; } // generate local working copy of image buffer int bufferSize = qBallImageSize[0]*qBallImageSize[1]*qBallImageSize[2]*qBallImageSize[3]; float* qBallImageBuffer = (float*) m_ItkQBallImage->GetBufferPointer(); float* workingQballImage = new float[bufferSize]; for (int i=0; i0 && i%qBallImageSize[0] == 0 && i>0) { sum /= qBallImageSize[0]; for (int j=i-qBallImageSize[0]; jGetBufferPointer(); maskImageSize[0] = m_MaskImage->GetLargestPossibleRegion().GetSize().GetElement(0); maskImageSize[1] = m_MaskImage->GetLargestPossibleRegion().GetSize().GetElement(1); maskImageSize[2] = m_MaskImage->GetLargestPossibleRegion().GetSize().GetElement(2); } else { mask = 0; maskImageSize[0] = qBallImageSize[1]; maskImageSize[1] = qBallImageSize[2]; maskImageSize[2] = qBallImageSize[3]; } int mask_oversamp_mult = maskImageSize[0]/qBallImageSize[1]; // load lookuptable QString applicationDir = QCoreApplication::applicationDirPath(); applicationDir.append("/"); mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false ); applicationDir.append("../"); mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false ); applicationDir.append("../../"); mitk::StandardFileLocations::GetInstance()->AddDirectoryForSearch( applicationDir.toStdString().c_str(), false ); std::string lutPath = mitk::StandardFileLocations::GetInstance()->FindFile("FiberTrackingLUTBaryCoords.bin"); ifstream BaryCoords; BaryCoords.open(lutPath.c_str(), ios::in | ios::binary); float* coords; if (BaryCoords.is_open()) { float tmp; coords = new float [1630818]; BaryCoords.seekg (0, ios::beg); for (int i=0; i<1630818; i++) { BaryCoords.read((char *)&tmp, sizeof(tmp)); coords[i] = tmp; } BaryCoords.close(); } else { MITK_INFO << "itkGibbsTrackingFilter: unable to open barycoords file"; m_AbortTracking = true; } ifstream Indices; lutPath = mitk::StandardFileLocations::GetInstance()->FindFile("FiberTrackingLUTIndices.bin"); Indices.open(lutPath.c_str(), ios::in | ios::binary); int* ind; if (Indices.is_open()) { int tmp; ind = new int [1630818]; Indices.seekg (0, ios::beg); for (int i=0; i<1630818; i++) { Indices.read((char *)&tmp, 4); ind[i] = tmp; } Indices.close(); } else { MITK_INFO << "itkGibbsTrackingFilter: unable to open indices file"; m_AbortTracking = true; } // initialize sphere interpolator with lookuptables SphereInterpolator *sinterp = new SphereInterpolator(coords, ind, QBALL_ODFSIZE, 301, 0.5); // get paramters float minSpacing; if(qBallImageSpacing[0]m_NumIt) { MITK_INFO << "itkGibbsTrackingFilter: not enough iterations!"; m_AbortTracking = true; } MITK_INFO << "Steps: " << m_Steps; unsigned long singleIts = (unsigned long)((1.0*m_NumIt) / (1.0*m_Steps)); // setup metropolis hastings sampler MITK_INFO << "itkGibbsTrackingFilter: setting up MH-sampler"; if (m_Sampler!=NULL) delete m_Sampler; m_Sampler = new RJMCMC(NULL, 0, workingQballImage, qBallImageSize, qBallImageSpacing, cellsize); // setup energy computer MITK_INFO << "itkGibbsTrackingFilter: setting up Energy-computer"; EnergyComputer encomp(workingQballImage,qBallImageSize,qBallImageSpacing,sinterp,&(m_Sampler->m_ParticleGrid),mask,mask_oversamp_mult, directionMatrix); encomp.setParameters(m_ParticleWeight,m_ParticleWidth,m_ChempotConnection*m_ParticleLength*m_ParticleLength,m_ParticleLength,curvatureHardThreshold,m_InexBalance,m_Chempot2); m_Sampler->SetEnergyComputer(&encomp); m_Sampler->SetParameters(m_TempStart,singleIts,m_ParticleLength,curvatureHardThreshold,m_ChempotParticle); // main loop for( int step = 0; step < m_Steps; step++ ) { - if (m_AbortTracking) - break; + if (m_AbortTracking) + break; - m_CurrentStep = step+1; - float temperature = m_TempStart * exp(alpha*(((1.0)*step)/((1.0)*m_Steps))); - MITK_INFO << "itkGibbsTrackingFilter: iterating step " << m_CurrentStep; + m_CurrentStep = step+1; + float temperature = m_TempStart * exp(alpha*(((1.0)*step)/((1.0)*m_Steps))); + MITK_INFO << "itkGibbsTrackingFilter: iterating step " << m_CurrentStep; - m_Sampler->SetTemperature(temperature); - m_Sampler->Iterate(&m_ProposalAcceptance, &m_NumConnections, &m_NumParticles, &m_AbortTracking); + m_Sampler->SetTemperature(temperature); + m_Sampler->Iterate(&m_ProposalAcceptance, &m_NumConnections, &m_NumParticles, &m_AbortTracking); - MITK_INFO << "itkGibbsTrackingFilter: proposal acceptance: " << 100*m_ProposalAcceptance << "%"; - MITK_INFO << "itkGibbsTrackingFilter: particles: " << m_NumParticles; - MITK_INFO << "itkGibbsTrackingFilter: connections: " << m_NumConnections; - MITK_INFO << "itkGibbsTrackingFilter: progress: " << 100*(float)step/m_Steps << "%"; + MITK_INFO << "itkGibbsTrackingFilter: proposal acceptance: " << 100*m_ProposalAcceptance << "%"; + MITK_INFO << "itkGibbsTrackingFilter: particles: " << m_NumParticles; + MITK_INFO << "itkGibbsTrackingFilter: connections: " << m_NumConnections; + MITK_INFO << "itkGibbsTrackingFilter: progress: " << 100*(float)step/m_Steps << "%"; - if (m_BuildFibers) - { - int numPoints = m_Sampler->m_ParticleGrid.pcnt; - float* points = new float[numPoints*m_Sampler->m_NumAttributes]; - m_Sampler->WriteOutParticles(points); - BuildFibers(points, numPoints); - delete points; - m_BuildFibers = false; - } + if (m_BuildFibers) + { + int numPoints = m_Sampler->m_ParticleGrid.pcnt; + float* points = new float[numPoints*m_Sampler->m_NumAttributes]; + m_Sampler->WriteOutParticles(points); + BuildFibers(points, numPoints); + delete points; + m_BuildFibers = false; + } } int numPoints = m_Sampler->m_ParticleGrid.pcnt; float* points = new float[numPoints*m_Sampler->m_NumAttributes]; m_Sampler->WriteOutParticles(points); BuildFibers(points, numPoints); delete points; delete sinterp; delete coords; delete ind; delete workingQballImage; m_AbortTracking = true; m_BuildFibers = false; MITK_INFO << "itkGibbsTrackingFilter: done generate data"; } } diff --git a/Modules/DiffusionImaging/Tractography/itkGibbsTrackingFilter.h b/Modules/DiffusionImaging/Tractography/itkGibbsTrackingFilter.h index 47400c4542..7c2ecfc200 100644 --- a/Modules/DiffusionImaging/Tractography/itkGibbsTrackingFilter.h +++ b/Modules/DiffusionImaging/Tractography/itkGibbsTrackingFilter.h @@ -1,172 +1,176 @@ #ifndef itkGibbsTrackingFilter_h #define itkGibbsTrackingFilter_h #include "itkProcessObject.h" #include "itkVectorContainer.h" #include "itkImage.h" #include "GibbsTracking/pcRJMCMC.cpp" #include "GibbsTracking/auxilary_classes.cpp" #include #include +#include +#include +#include +#include +#include namespace itk{ template< class TInputQBallImage, class TInputROIImage > class GibbsTrackingFilter : public ProcessObject{ public: typedef GibbsTrackingFilter Self; typedef ProcessObject Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; itkNewMacro(Self); itkTypeMacro( GibbsTrackingFilter, ProcessObject ); /** Types for the DWI Input Image **/ typedef TInputQBallImage InputQBallImageType; /** Types for the Mask Image **/ typedef TInputROIImage MaskImageType; typedef typename MaskImageType::Pointer MaskImageTypePointer; - typedef std::vector< itk::Point > FiberTractType; - typedef std::vector< FiberTractType > FiberBundleType; + typedef vtkSmartPointer< vtkPolyData > FiberPolyDataType; typedef Image< float, 3 > GfaImageType; typedef typename GfaImageType::Pointer GfaImageTypePointer; itkSetMacro( TempStart, float ); itkGetMacro( TempStart, float ); itkSetMacro( TempEnd, float ); itkGetMacro( TempEnd, float ); itkSetMacro( NumIt, unsigned long ); itkGetMacro( NumIt, unsigned long ); itkSetMacro( ParticleWeight, float ); itkGetMacro( ParticleWeight, float ); /** width of particle sigma (std-dev of gaussian around center) **/ itkSetMacro( ParticleWidth, float ); itkGetMacro( ParticleWidth, float ); /** length of particle from midpoint to ends **/ itkSetMacro( ParticleLength, float ); itkGetMacro( ParticleLength, float ); itkSetMacro( ChempotConnection, float ); itkGetMacro( ChempotConnection, float ); itkSetMacro( ChempotParticle, float ); itkGetMacro( ChempotParticle, float ); itkSetMacro( InexBalance, float ); itkGetMacro( InexBalance, float ); itkSetMacro( Chempot2, float ); itkGetMacro( Chempot2, float ); itkSetMacro( FiberLength, int ); itkGetMacro( FiberLength, int ); itkSetMacro( AbortTracking, bool ); itkGetMacro( AbortTracking, bool ); itkSetMacro( CurrentStep, unsigned long ); itkGetMacro( CurrentStep, unsigned long ); itkSetMacro( SubtractMean, bool); itkGetMacro( SubtractMean, bool); /** Set/Get the Odf Input Image **/ itkSetInputMacro(OdfImage, InputQBallImageType, 0); itkGetInputMacro(OdfImage, InputQBallImageType, 0); /** Set/Get the Input mask image **/ itkSetMacro(MaskImage, MaskImageTypePointer); itkGetMacro(MaskImage, MaskImageTypePointer); itkSetMacro(GfaImage, GfaImageTypePointer); itkGetMacro(GfaImage, GfaImageTypePointer); itkGetMacro(NumParticles, unsigned long); itkGetMacro(NumConnections, unsigned long); itkGetMacro(NumAcceptedFibers, int); itkGetMacro(ProposalAcceptance, float); itkGetMacro(Steps, unsigned int); /** Entry Point For the Algorithm: Is invoked when Update() is called either directly or through itk pipeline propagation **/ void GenerateData(); /** override the Process Object Update because we don't have a dataobject as an outpgnome themeut. We can change this later by wrapping the tractcontainer in a dataobject decorator and letting the Superclass know about it. **/ struct StochasticTractGenerationCallbackStruct{ Pointer Filter; }; virtual void Update(){ this->GenerateData(); } - FiberBundleType* GetFiberBundle(); + FiberPolyDataType GetFiberBundle(); float GetMemoryUsage(); bool EstimateParticleWeight(); protected: GibbsTrackingFilter(); virtual ~GibbsTrackingFilter(); void ComputeFiberCorrelation(); void BuildFibers(float* points, int numPoints); // Input Images typename InputQBallImageType::Pointer m_ItkQBallImage; typename MaskImageType::Pointer m_MaskImage; typename GfaImageType::Pointer m_GfaImage; // Tracking parameters float m_TempStart; // Start temperature float m_TempEnd; // End temperature unsigned long m_NumIt; // Total number of iterations unsigned long m_CurrentStep; // current tracking step float m_ParticleWeight; //w (unitless) float m_ParticleWidth; //sigma (mm) float m_ParticleLength; // ell (mm) float m_ChempotConnection; // gross L (chemisches potential) float m_ChempotParticle;// unbenutzt (immer null, wenn groesser dann insgesamt weniger teilchen) float m_InexBalance; // gewichtung zwischen den lambdas // -5 ... 5 -> nur intern ... nur extern,default 0 float m_Chempot2; // typischerweise 0, // korrektur fuer das geschaetzte integral int m_FiberLength; bool m_AbortTracking; bool m_SubtractMean; int m_NumAcceptedFibers; volatile bool m_BuildFibers; unsigned int m_Steps; float m_Memory; float m_ProposalAcceptance; RJMCMC* m_Sampler; - FiberBundleType m_FiberBundle; + FiberPolyDataType m_FiberPolyData; unsigned long m_NumParticles; unsigned long m_NumConnections; }; } #ifndef ITK_MANUAL_INSTANTIATION #include "itkGibbsTrackingFilter.cpp" #endif #endif diff --git a/Modules/DiffusionImaging/files.cmake b/Modules/DiffusionImaging/files.cmake index 4133a6c61d..eedcc09b14 100644 --- a/Modules/DiffusionImaging/files.cmake +++ b/Modules/DiffusionImaging/files.cmake @@ -1,182 +1,166 @@ SET(CPP_FILES # DicomImport DicomImport/mitkDicomDiffusionImageReader.cpp DicomImport/mitkGroupDiffusionHeadersFilter.cpp DicomImport/mitkDicomDiffusionImageHeaderReader.cpp DicomImport/mitkGEDicomDiffusionImageHeaderReader.cpp DicomImport/mitkPhilipsDicomDiffusionImageHeaderReader.cpp DicomImport/mitkSiemensDicomDiffusionImageHeaderReader.cpp DicomImport/mitkSiemensMosaicDicomDiffusionImageHeaderReader.cpp # DataStructures IODataStructures/mitkDiffusionImagingObjectFactory.cpp # DataStructures -> DWI IODataStructures/DiffusionWeightedImages/mitkDiffusionImageHeaderInformation.cpp IODataStructures/DiffusionWeightedImages/mitkDiffusionImageSource.cpp IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageReader.cpp IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageWriter.cpp IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageIOFactory.cpp IODataStructures/DiffusionWeightedImages/mitkNrrdDiffusionImageWriterFactory.cpp IODataStructures/DiffusionWeightedImages/mitkDiffusionImageSerializer.cpp # DataStructures -> QBall IODataStructures/QBallImages/mitkQBallImageSource.cpp IODataStructures/QBallImages/mitkNrrdQBallImageReader.cpp IODataStructures/QBallImages/mitkNrrdQBallImageWriter.cpp IODataStructures/QBallImages/mitkNrrdQBallImageIOFactory.cpp IODataStructures/QBallImages/mitkNrrdQBallImageWriterFactory.cpp IODataStructures/QBallImages/mitkQBallImage.cpp IODataStructures/QBallImages/mitkQBallImageSerializer.cpp # DataStructures -> Tensor IODataStructures/TensorImages/mitkTensorImageSource.cpp IODataStructures/TensorImages/mitkNrrdTensorImageReader.cpp IODataStructures/TensorImages/mitkNrrdTensorImageWriter.cpp IODataStructures/TensorImages/mitkNrrdTensorImageIOFactory.cpp IODataStructures/TensorImages/mitkNrrdTensorImageWriterFactory.cpp IODataStructures/TensorImages/mitkTensorImage.cpp IODataStructures/TensorImages/mitkTensorImageSerializer.cpp - # DataStructures -> FiberBundle - IODataStructures/FiberBundle/mitkFiberBundle.cpp - IODataStructures/FiberBundle/mitkFiberBundleWriter.cpp - IODataStructures/FiberBundle/mitkFiberBundleReader.cpp - IODataStructures/FiberBundle/mitkFiberBundleIOFactory.cpp - IODataStructures/FiberBundle/mitkFiberBundleWriterFactory.cpp - IODataStructures/FiberBundle/mitkFiberBundleSerializer.cpp - IODataStructures/FiberBundle/mitkParticle.cpp - IODataStructures/FiberBundle/mitkParticleGrid.cpp + IODataStructures/mitkParticle.cpp + IODataStructures/mitkParticleGrid.cpp # DataStructures -> FiberBundleX IODataStructures/FiberBundleX/mitkFiberBundleX.cpp IODataStructures/FiberBundleX/mitkFiberBundleXWriter.cpp IODataStructures/FiberBundleX/mitkFiberBundleXReader.cpp IODataStructures/FiberBundleX/mitkFiberBundleXIOFactory.cpp IODataStructures/FiberBundleX/mitkFiberBundleXWriterFactory.cpp IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.cpp IODataStructures/FiberBundleX/mitkFiberBundleXThreadMonitor.cpp - # DataStructures -> PlanarFigureComposite IODataStructures/PlanarFigureComposite/mitkPlanarFigureComposite.cpp - # DataStructures -> Tbss IODataStructures/TbssImages/mitkTbssImageSource.cpp IODataStructures/TbssImages/mitkTbssRoiImageSource.cpp IODataStructures/TbssImages/mitkNrrdTbssImageReader.cpp IODataStructures/TbssImages/mitkNrrdTbssImageIOFactory.cpp IODataStructures/TbssImages/mitkNrrdTbssRoiImageReader.cpp IODataStructures/TbssImages/mitkNrrdTbssRoiImageIOFactory.cpp IODataStructures/TbssImages/mitkTbssImage.cpp IODataStructures/TbssImages/mitkTbssRoiImage.cpp IODataStructures/TbssImages/mitkNrrdTbssImageWriter.cpp IODataStructures/TbssImages/mitkNrrdTbssImageWriterFactory.cpp IODataStructures/TbssImages/mitkNrrdTbssRoiImageWriter.cpp IODataStructures/TbssImages/mitkNrrdTbssRoiImageWriterFactory.cpp IODataStructures/TbssImages/mitkTbssImporter.cpp - # Rendering Rendering/vtkMaskedProgrammableGlyphFilter.cpp Rendering/mitkCompositeMapper.cpp Rendering/mitkVectorImageVtkGlyphMapper3D.cpp Rendering/vtkOdfSource.cxx Rendering/vtkThickPlane.cxx Rendering/mitkOdfNormalizationMethodProperty.cpp Rendering/mitkOdfScaleByProperty.cpp - Rendering/mitkFiberBundleMapper2D.cpp - Rendering/mitkFiberBundleMapper3D.cpp Rendering/mitkFiberBundleXMapper2D.cpp Rendering/mitkFiberBundleXMapper3D.cpp Rendering/mitkFiberBundleXThreadMonitorMapper3D.cpp Rendering/mitkTbssImageMapper.cpp Rendering/mitkPlanarCircleMapper3D.cpp Rendering/mitkPlanarPolygonMapper3D.cpp - + # Interactions Interactions/mitkFiberBundleInteractor.cpp # Algorithms Algorithms/mitkPartialVolumeAnalysisHistogramCalculator.cpp Algorithms/mitkPartialVolumeAnalysisClusteringCalculator.cpp Algorithms/mitkTractAnalyzer.cpp # Tractography Tractography/itkStochasticTractographyFilter.h ) SET(H_FILES # Rendering Rendering/mitkDiffusionImageMapper.h Rendering/mitkTbssImageMapper.h Rendering/mitkOdfVtkMapper2D.h - Rendering/mitkFiberBundleMapper2D.h - Rendering/mitkFiberBundleMapper3D.h Rendering/mitkFiberBundleXMapper3D.h Rendering/mitkFiberBundleXMapper2D.h Rendering/mitkFiberBundleXThreadMonitorMapper3D.h Rendering/mitkPlanarCircleMapper3D.h Rendering/mitkPlanarPolygonMapper3D.h # Reconstruction Reconstruction/itkDiffusionQballReconstructionImageFilter.h Reconstruction/mitkTeemDiffusionTensor3DReconstructionImageFilter.h Reconstruction/itkAnalyticalDiffusionQballReconstructionImageFilter.h Reconstruction/itkPointShell.h Reconstruction/itkOrientationDistributionFunction.h Reconstruction/itkDiffusionIntravoxelIncoherentMotionReconstructionImageFilter.h Reconstruction/itkRegularizedIVIMLocalVariationImageFilter.h Reconstruction/itkRegularizedIVIMReconstructionFilter.h Reconstruction/itkRegularizedIVIMReconstructionSingleIteration.h # IO Datastructures - IODataStructures/DiffusionWeightedImages/mitkDiffusionImage.h - IODataStructures/FiberBundle/itkSlowPolyLineParametricPath.h + IODataStructures/DiffusionWeightedImages/mitkDiffusionImage.h IODataStructures/TbssImages/mitkTbssImporter.h # DataStructures -> FiberBundleX IODataStructures/FiberBundleX/mitkFiberBundleX.h IODataStructures/FiberBundleX/mitkFiberBundleXWriter.h IODataStructures/FiberBundleX/mitkFiberBundleXReader.h IODataStructures/FiberBundleX/mitkFiberBundleXIOFactory.h IODataStructures/FiberBundleX/mitkFiberBundleXWriterFactory.h IODataStructures/FiberBundleX/mitkFiberBundleXSerializer.h IODataStructures/FiberBundleX/mitkFiberBundleXThreadMonitor.h - - # Tractography Tractography/itkGibbsTrackingFilter.h Tractography/itkStochasticTractographyFilter.h # Algorithms Algorithms/itkDiffusionQballGeneralizedFaImageFilter.h Algorithms/itkDiffusionQballPrepareVisualizationImageFilter.h Algorithms/itkTensorDerivedMeasurementsFilter.h Algorithms/itkBrainMaskExtractionImageFilter.h Algorithms/itkB0ImageExtractionImageFilter.h Algorithms/itkTensorImageToDiffusionImageFilter.h Algorithms/itkTensorToL2NormImageFilter.h - Algorithms/itkTractsToProbabilityImageFilter.h + Algorithms/itkTractDensityImageFilter.h Algorithms/itkTractsToFiberEndingsImageFilter.h + Algorithms/itkTractsToRgbaImageFilter.h Algorithms/itkGaussianInterpolateImageFunction.h Algorithms/mitkPartialVolumeAnalysisHistogramCalculator.h Algorithms/mitkPartialVolumeAnalysisClusteringCalculator.h Algorithms/itkDiffusionTensorPrincipleDirectionImageFilter.h Algorithms/itkCartesianToPolarVectorImageFilter.h Algorithms/itkPolarToCartesianVectorImageFilter.h Algorithms/itkDistanceMapFilter.h Algorithms/itkProjectionFilter.h Algorithms/itkSkeletonizationFilter.h ) SET( TOOL_FILES ) IF(WIN32) ENDIF(WIN32) #MITK_MULTIPLEX_PICTYPE( Algorithms/mitkImageRegistrationMethod-TYPE.cpp )