5 #include <boost/filesystem.hpp>
6 #include <boost/program_options.hpp>
9 #include "airwaysTree.h"
11 #include <cpPlugins/Interface.h>
12 #include <cpPlugins/Workspace.h>
14 using namespace airways;
15 namespace po = boost::program_options;
19 const size_t ERROR_IN_COMMAND_LINE = 1;
20 const size_t SUCCESS = 0;
21 const size_t ERROR_UNHANDLED_EXCEPTION = 2;
24 typedef std::vector< AirwaysTree > AirwaysVector;
26 #include <itkCastImageFilter.h>
28 // Auxiliar struct to save info for execution.
29 typedef void* TImagePointer;
34 this->myWorkspace = new cpPlugins::Workspace( );
39 if( this->IsMyWorkspace )
40 delete this->myWorkspace;
46 auto image = this->myWorkspace->GetFilter( "reader" )->GetOutputData( "Output" )->GetITK< itk::Image< unsigned char, 3 > >( );
47 typedef itk::CastImageFilter< itk::Image< unsigned char, 3 >, TInputImage > _TCast;
48 _TCast::Pointer cast = _TCast::New( );
49 cast->SetInput( image );
51 this->Image = cast->GetOutput( );
52 this->Image->DisconnectPipeline( );
55 TInputImage::Pointer Image;
56 cpPlugins::Workspace* myWorkspace;
59 std::string folderpath_pigResults;
61 std::string image_name;
65 unsigned char red[3] = { 255, 0, 0 };
66 unsigned char green[3] = { 0, 255, 0 };
67 unsigned char blue[3] = { 0, 0, 255 };
68 unsigned char yellow[3]= { 255, 255, 0 };
69 unsigned char purple[3]= { 255, 0, 255 };
70 unsigned char cyan[3]= { 0, 255, 255 };
72 cpPlugins::Interface myPlugins;
74 // -------------------------------------------------------------------------
75 void Load_cpPlugins( const std::string& plugins );
76 void CreateResultDirectory(AirwaysTree tree);
77 void DrawVTKLinesFromTree(AirwaysTree& tree, const std::string filename, bool common);
78 AirwaysTree& CreateAirwaysTreeFromSegmentation(Vec3 seed, TInputImage* input_image, cpPlugins::Workspace& ws );
79 vector<TreeInfo> ReadInputFile(const char* filename);
80 void printCommonTreeBetweenTwoTrees(AirwaysTree tree_A, AirwaysTree tree_B, std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > > vector_pair_edges_A_to_B, unsigned int Q, unsigned int F);
81 void printMatchingResultToFile(AirwaysTree tree_A, AirwaysTree tree_B, std::map< unsigned int, std::vector<Node*> > map_A_to_B, std::map< unsigned int, std::vector<Node*> > map_B_to_A, unsigned int Q, unsigned int F);
82 void createLinesAndPointsForVTK(const Node* node, vtkSmartPointer<vtkPoints>& pts,vtkSmartPointer<vtkCellArray>& lines, vtkSmartPointer<vtkUnsignedCharArray>& colors, bool common, bool isRoot);
84 // -------------------------------------------------------------------------
85 int main( int argc, char* argv[] )
87 Load_cpPlugins( "./plugins.cfg" );
91 // Define and parse the program options
92 po::options_description desc("Options");
93 desc.add_options()("use_file", po::value<std::string>(), "Adds the filepath containing the file to be used in creaAirwaysTree -- Mandatory")
94 ("build_trees","Creates trees from a given filepath (arg) and stores it in a .vtk file")
95 ("subtree_levels", po::value<int>(),"Get a subtree(s) by levels - result: a vtk and reconstructed img .mhd")
96 ("subtree_length", po::value<float>(),"Get a subtree(s) by length - result: a vtk and reconstructed img .mhd")
97 ("subtree_diameter", po::value<float>(),"Get a subtree(s) by diameter - result: a vtk and reconstructed img .mhd")
98 ("compare_trees", "Compare the trees given in the input file or the subtrees using an option - result: a vtk and reconstructed img .mhd");
99 //TODO: Fix image segmentation. ("segment_images", "Creates a binary image corresponding to the segmentation of of a given original image (arg) and seed (arg), saves it to a .mhd file and uses it for subsequent operations")
100 po::variables_map vm;
103 std::string fileName;
104 vector<TreeInfo> treeInfoVector;
105 AirwaysVector aVector;
106 TImagePointer segmentationImage;
108 po::store(po::parse_command_line(argc, argv, desc), vm); // can throw
109 if (vm.count("use_file"))
111 fileName = vm["use_file"].as<std::string>();
112 treeInfoVector = ReadInputFile(fileName.c_str());
115 if(vm.count("segment_images"))
119 // Build trees option
120 if (vm.count("build_trees"))
122 for(unsigned int i = 0; i < treeInfoVector.size(); ++ i){
123 TreeInfo info = treeInfoVector[i];
124 std::string err = info.myWorkspace->Execute( "eb" );
127 std::cerr << "Error: " << err << std::endl;
132 AirwaysTree tree = CreateAirwaysTreeFromSegmentation( info.seed, info.Image, *(info.myWorkspace ));
133 tree.SetResultPath(info.folderpath_pigResults);
134 tree.SetImageName(info.image_name);
135 aVector.push_back(tree);
137 for (unsigned int i = 0; i < aVector.size(); ++i)
139 CreateResultDirectory(aVector[i]);
140 std::string fullPath = aVector[i].GetResultPath() + "/" + aVector[i].GetImageName() + ".vtk";
141 DrawVTKLinesFromTree(aVector[i], fullPath, false);
146 // Subtree levels option
147 if (vm.count("subtree_levels"))
150 else if (vm.count("subtree_length"))
153 else if (vm.count("subtree_diameter"))
157 if (vm.count("compare_trees"))
159 std::cout << "Option: Compare trees" << std::endl;
161 * this piece of code only test in the case of two trees, so it can be replaced
162 * to a code which does a cascade
165 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
166 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
167 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
168 //CODIGO DE COMPARACIÓN DE ARBOLES
169 //std::cout << "Comparing trees ..." << std::endl;
170 //aVector[0].CompareTrees(aVector[1]);
171 //std::cout << "Comparing trees ... OK" << std::endl;
173 std::cout << "Tree A ... " << std::endl;
174 //aVector[0].printNodeAndChildrenIds();
175 std::cout << "Tree A ... OK" << std::endl;
177 std::cout << "Tree B ... " << std::endl;
178 //aVector[1].printNodeAndChildrenIds();
179 std::cout << "Tree B ... OK" << std::endl;
181 std::cout << "Comparing trees Orkisz-Morales..." << std::endl;
182 // Vectors to save the common and uncommon nodes
185 vec_nodes nonCommonA;
186 vec_nodes nonCommonB;
187 std::map< unsigned int, std::vector<Node*> > map_A_to_B;
188 std::map< unsigned int, std::vector<Node*> > map_B_to_A;
189 std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > > vector_pair_edges_A_to_B;
191 // Input parameter for comparison
192 unsigned int Q = 1; // Corresponds to the depth to select "fathers" nodes
193 unsigned int F = 1; // Correspond to the depth to select "family" nodes
194 std::cout << "Q = " << Q << std::endl;
195 std::cout << "F = " << F << std::endl;
197 clock_t before_compare = clock();
198 aVector[0].CompareTreesOrkiszMorales(aVector[1], Q, F, commonA, commonB, nonCommonA, nonCommonB, map_A_to_B, map_B_to_A, vector_pair_edges_A_to_B);
199 clock_t after_compare = clock();
200 double compare_time = double(after_compare - before_compare) / CLOCKS_PER_SEC;
201 std::cout << "Matching time: " << compare_time << std::endl;
203 // Print the common tree with common edges
204 printCommonTreeBetweenTwoTrees(aVector[0], aVector[1], vector_pair_edges_A_to_B, Q, F);
205 printMatchingResultToFile(aVector[0], aVector[1], map_A_to_B, map_B_to_A, Q, F);
206 //printSeparatedCommonTrees(aVector[0], aVector[1], vector_pair_edges_A_to_B, Q, F);
207 //reconstructAndSaveCommonTrees(aVector[0], aVector[1], vector_pair_edges_A_to_B, Q, F);
209 // Print all the maps that have more that two connections
210 std::cout << "Printing multiple relation A to B. Total relations: " << map_A_to_B.size() << std::endl;
211 for(std::map< unsigned int, std::vector<Node*> >::iterator it_map_A_to_B = map_A_to_B.begin(); it_map_A_to_B != map_A_to_B.end(); ++it_map_A_to_B)
213 if((*it_map_A_to_B).second.size() > 1)
215 std::cout << "Multiple relation A to B with size:" << (*it_map_A_to_B).second.size() << ", from Id:" << (*it_map_A_to_B).first << std::endl;
216 for(std::vector<Node*>::iterator it_node = (*it_map_A_to_B).second.begin(); it_node != (*it_map_A_to_B).second.end(); ++it_node)
218 std::cout << "Id: " << (*it_node)->GetId() << std::endl;
222 std::cout << "Printing multiple relation A to B ... OK" << std::endl;
224 std::cout << "Printing multiple relation B to A. Total relations: " << map_B_to_A.size() << std::endl;
225 for(std::map< unsigned int, std::vector<Node*> >::iterator it_map_B_to_A = map_B_to_A.begin(); it_map_B_to_A != map_B_to_A.end(); ++it_map_B_to_A)
227 if((*it_map_B_to_A).second.size() > 1)
229 std::cout << "Multiple relation B to A with size:" << (*it_map_B_to_A).second.size() << ", from Id:" << (*it_map_B_to_A).first << std::endl;
230 for(std::vector<Node*>::iterator it_node = (*it_map_B_to_A).second.begin(); it_node != (*it_map_B_to_A).second.end(); ++it_node)
232 std::cout << "Id: " << (*it_node)->GetId() << std::endl;
236 std::cout << "Printing multiple relation B to A ... OK" << std::endl;
238 // Mark only the common nodes
239 aVector[0].UnMarkAll();
240 aVector[1].UnMarkAll();
242 // --------------------------------------
243 // ------ Get common paths marked -------
244 // --------------------------------------
247 std::string path_folder = "/run/media/alfredo/Data/Pulmones/results/airwaysGraphs/comparisonResutls/probes/";
248 std::string suffix_vtk = ".vtk";
249 std::string name_tree = "TreeA_dP2P";
251 for(vec_nodes::iterator it_A = commonA.begin(); it_A != commonA.end(); ++it_A)
253 aVector[0].MarkPathFromNodeToNode(aVector[0].GetRoot(), (*it_A));
255 std::stringstream filepath_actualIteration;
256 filepath_actualIteration << path_folder << name_tree << "__" << iteration << "_idA_" << (*it_A)->GetId() << suffix_vtk;
258 DrawVTKLinesFromTree(aVector[0], filepath_actualIteration.str(), true);
263 name_tree = "TreeB_dP2P";
264 for(vec_nodes::iterator it_B = commonB.begin(); it_B != commonB.end(); ++it_B)
266 aVector[1].MarkPathFromNodeToNode(aVector[1].GetRoot(), (*it_B));
268 std::stringstream filepath_actualIteration;
269 filepath_actualIteration << path_folder << name_tree << "__" << iteration << "_idB_" << (*it_B)->GetId() << suffix_vtk;
271 DrawVTKLinesFromTree(aVector[1], filepath_actualIteration.str(), true);
276 // --------------------------------------
277 // --------------------------------------
280 //XXXXXXXXXXXXXXXXXXXXXXXXXXXX
281 //1. PRINT EACH NODE OF EACH TREE AND SAVE IT USING AS NAME ITS ID
284 for(int i = 2; i < aVector[0].GetWeight(); ++i)
286 //std::cout << "Writing idA: " << i << std::endl;
287 AirwaysTree* tree_id = aVector[0].GetSingleDetachedTreeNodeById(i);
288 //std::cout << "Got id: " << i << ", numberOfNodes: " << tree_id->GetWeight() << std::endl;
291 std::stringstream filepath_actualIteration;
292 filepath_actualIteration << aVector[0].GetResultPath() << "/" << aVector[0].GetImageName() << "_id_" << i << suffix_vtk;
293 DrawVTKLinesFromTree(*tree_id, filepath_actualIteration.str(), false);
297 std::cout << "Tree NULL" << std::endl;
301 for(int i = 2; i < aVector[1].GetWeight(); ++i)
303 //std::cout << "Writing idA: " << i << std::endl;
304 AirwaysTree* tree_id = aVector[1].GetSingleDetachedTreeNodeById(i);
305 //std::cout << "Got id: " << i << ", numberOfNodes: " << tree_id->GetWeight() << std::endl;
308 std::stringstream filepath_actualIteration;
309 filepath_actualIteration << aVector[1].GetResultPath() << "/" << aVector[1].GetImageName() << "_id_" << i << suffix_vtk;
310 DrawVTKLinesFromTree(*tree_id, filepath_actualIteration.str(), false);
314 std::cout << "Tree NULL" << std::endl;
317 std::cout << "Comparing trees Orkisz-Morales... OK" << std::endl;
321 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
322 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
323 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
326 aVector[0].SubIsomorphism(aVector[1]);
328 std::cout << "Flag after SubIsomorphism" << std::endl;
329 std::string fullPathA = aVector[0].GetResultPath() + "/" + aVector[0].GetImageName() + "_CMP.vtk";
330 std::string fullPathB = aVector[1].GetResultPath() + "/" + aVector[1].GetImageName() + "_CMP.vtk";
331 DrawVTKLinesFromTree(aVector[0], fullPathA, true);
332 DrawVTKLinesFromTree(aVector[1], fullPathB, true);
334 std::cout << "Flag after write vtk" << std::endl;
335 TInputImage::Pointer imgA, imgB;
336 aVector[0].ImageReconstruction(imgA);
337 std::cout << "Flag after Reconstruction A" << std::endl;
339 aVector[1].ImageReconstruction(imgB);
340 std::cout << "Flag after Reconstruction B" << std::endl;
342 std::string fullPathA_mhd = aVector[0].GetResultPath() + "/" + aVector[0].GetImageName() + "_CMP.vtk";
343 std::string fullPathB_mhd = aVector[1].GetResultPath() + "/" + aVector[1].GetImageName() + "_CMP.vtk";
344 WriteImage(imgA, fullPathA_mhd);
345 WriteImage(imgB, fullPathB_mhd);
349 po::notify(vm); // throws on error, so do after help in case
351 catch (std::exception& e)
353 std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl;
354 return ERROR_UNHANDLED_EXCEPTION;
357 catch (std::exception& e)
359 std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl;
360 return ERROR_UNHANDLED_EXCEPTION;
365 // -------------------------------------------------------------------------
366 void Load_cpPlugins( const std::string& plugins )
368 myPlugins.LoadConfiguration( plugins );
371 // -------------------------------------------------------------------------
372 void CreateResultDirectory(AirwaysTree tree)
374 boost::filesystem::path dir(tree.GetResultPath());
375 if (boost::filesystem::create_directories(dir))
377 std::cout << "FolderName = " << tree.GetResultPath() << " has been created" << std::endl;
380 std::cout << "FolderName = " << tree.GetResultPath() << " already exists" << std::endl;
383 // -------------------------------------------------------------------------
384 void DrawVTKLinesFromTree(AirwaysTree& tree, const std::string filepath, bool common)
386 // Create the array of points, lines, and colors
387 vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New();
388 vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
389 vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New();
390 colors->SetNumberOfComponents(3);
391 colors->SetName("Colors");
393 //vtk sphere for sources
394 //vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New();
395 //Vec3 root = tree.GetRoot()->GetCoords();
396 //sphereSource->SetCenter(root[0], root[1], root[2]);
397 //sphereSource->SetRadius(1);
403 // Create and fill the points, lines, and color vectors
404 //CalculateVTKLinesFromEdges(tree.GetRoot(), 0, id, pts, lines, colors, common);
405 pts->SetNumberOfPoints(tree.GetWeight()+1);
406 createLinesAndPointsForVTK(tree.GetRoot(), pts, lines, colors, common, true);
408 // Create the polydata
409 vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New();
411 // Set the points, lines, and colors
412 linesPolyData->SetPoints(pts);
413 linesPolyData->SetLines(lines);
414 linesPolyData->GetCellData()->SetScalars(colors);
417 vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
418 writer->SetFileName(filepath.c_str());
420 #if VTK_MAJOR_VERSION <= 5
421 writer->SetInput(linesPolyData);
423 writer->SetInputData(linesPolyData);
427 //The following code is to test the vtk polydata and visualize it
429 vtkSmartPointer<vtkPolyDataMapper> mapper =
430 vtkSmartPointer<vtkPolyDataMapper>::New();
431 #if VTK_MAJOR_VERSION <= 5
432 mapper->SetInput(linesPolyData);
434 mapper->SetInputData(linesPolyData);
436 vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
437 actor->SetMapper(mapper);
440 vtkSmartPointer<vtkPolyDataMapper> mapperSphere = vtkSmartPointer<
441 vtkPolyDataMapper>::New();
442 mapperSphere->SetInputConnection(sphereSource->GetOutputPort());
444 vtkSmartPointer<vtkActor> actorSphere = vtkSmartPointer<vtkActor>::New();
445 actorSphere->SetMapper(mapperSphere);
448 vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
449 vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<
450 vtkRenderWindow>::New();
451 renderWindow->AddRenderer(renderer);
452 vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
453 vtkSmartPointer<vtkRenderWindowInteractor>::New();
454 renderWindowInteractor->SetRenderWindow(renderWindow);
455 renderer->AddActor(actorSphere);
456 renderer->AddActor(actor);
458 renderWindow->Render();
459 renderWindowInteractor->Start();*/
462 // -------------------------------------------------------------------------
463 #include <fpa/Base/ImageSkeleton.h>
464 #include <fpa/Image/MinimumSpanningTree.h>
465 #include <cpExtensions/DataStructures/ImageIndexesContainer.h>
466 #include <itkImage.h>
468 template< class TImage, class TVertex >
469 Node* FAVertexToNode( TVertex vertex, TImage* image )
471 //The FrontAlgorithms Vertex is an TImageType::IndexType
472 typename TImage::PointType point;
473 image->TransformIndexToPhysicalPoint( vertex, point );
474 Vec3 alfPoint(point[0],point[1],point[2]);
475 return new Node(alfPoint);
478 AirwaysTree& ConvertFilterToAirwaysTree( TInputImage* input_image, cpPlugins::Workspace& ws )
481 fpa::Base::ImageSkeleton< fpa::Image::MinimumSpanningTree< 3 > >
483 typedef TFASkeleton::TVertex TVertexFA;
484 typedef TFASkeleton::TVertexCmp TVertexCompareFA;
485 typedef cpExtensions::DataStructures::ImageIndexesContainer< 3 > TVerticesFA;
487 typedef Node TVertexAirways;
488 typedef Edge TEdgeAirways;
489 typedef pair_posVox_rad TSkelePoint;
490 typedef vec_pair_posVox_rad TSkelePoints;
491 typedef std::map< TVertexFA, TVertexAirways*, TVertexCompareFA > VertexMap;
493 std::time_t start,end;
495 std::cout << "Starting conversion " << std::endl;
497 auto w_filter = ws.GetFilter( "eb" );
499 ws.GetFilter( "dmap" )->GetOutputData( "Output" )->
500 GetITK< itk::Image< float, 3 > >( );
502 w_filter->GetOutputData( "Skeleton" )->GetITK< TFASkeleton >( );
503 auto sIt = branches->Get( ).begin( );
504 for( ; sIt!=branches->Get( ).end( ); ++sIt )
506 auto srcIt = vertexMap.find( sIt->first );
507 if( srcIt == vertexMap.end( ) )
508 srcIt = vertexMap.insert(
509 VertexMap::value_type(
510 sIt->first, FAVertexToNode( sIt->first, input_image )
513 auto eIt = sIt->second.begin( );
514 for( ; eIt != sIt->second.end( ); ++eIt )
516 auto dstIt = vertexMap.find( eIt->first );
517 if( dstIt != vertexMap.end( ) )
519 dstIt = vertexMap.insert(
520 VertexMap::value_type(
521 eIt->first, FAVertexToNode( eIt->first, input_image )
525 dstIt->second->SetFather( srcIt->second );
526 srcIt->second->AddChild( dstIt->second );
527 TEdgeAirways* edge = new Edge( );
528 auto path = eIt->second->GetVertexList( );
529 for( unsigned int pIt = 0; pIt < path->Size( ); ++pIt )
531 itk::ImageBase< 3 >::PointType pnt;
532 auto cidx = path->GetElement( pIt );
533 input_image->TransformContinuousIndexToPhysicalPoint( cidx, pnt );
535 input_image->TransformPhysicalPointToIndex( pnt, idx );
536 Vec3 coords = FAVertexToNode( idx, input_image )->GetCoords( );
537 pair_posVox_rad skPair( coords, distance_map->GetPixel( idx ) );
538 edge->AddSkeletonPairInfo( skPair );
546 ws.GetFilter( "seed" )->GetOutputData( "Output" )->
547 GetITK< TVerticesFA >( )->Get( )[ 0 ];
549 new AirwaysTree( input_image, NULL, vertexMap[ seed0 ], false );
551 std::cout << "Finished conversion. New AlfTree has weight: "<<tree->GetWeight()<<". Takes "<<(end-start)<<" s." << std::endl;
555 // -------------------------------------------------------------------------
556 AirwaysTree& CreateAirwaysTreeFromSegmentation(Vec3 seed, TInputImage* input_image, cpPlugins::Workspace& ws )
558 return( ConvertFilterToAirwaysTree( input_image, ws ) );
561 // -------------------------------------------------------------------------
562 vector<TreeInfo> ReadInputFile(const char* filename)
565 std::ifstream infile(filename);
567 std::string folderpath_allResults;
568 vector<TreeInfo> vectorInfo;
570 bool firstLine = false;
572 while (std::getline(infile, line))
574 // First line contains the output folder
575 std::istringstream iss(line);
578 if (!(iss >> folderpath_allResults))
580 std::cout << "no file" << std::endl;
585 // Other lines, not the first one, contain the information for the airways to be created
589 float point_trachea[3];
590 std::string filepath_airwayImage, name_pig, name_image;
591 if (!(iss >> point_trachea[0] >> point_trachea[1] >> point_trachea[2] >> filepath_airwayImage >> name_pig >> name_image))
593 std::cout << "There is no tree information in the file." << std::endl;
599 std::cout << "Point trachea:[" << point_trachea[0] << "," << point_trachea[1] << "," << point_trachea[2] << "]" << std::endl;
605 Vec3 seed(point_trachea[0], point_trachea[1], point_trachea[2]); //real coords seed
606 treeInfo.seed = seed;
607 // Create the outputs
608 treeInfo.folderpath_pigResults = folderpath_allResults + "/" + name_pig + "/";
609 treeInfo.pig_name = name_pig;
610 treeInfo.image_name = name_image;
613 treeInfo.image = ReadImage<TInputImage>(filepath_airwayImage);
615 // Execute first pipeline's part
616 std::stringstream seed_stream;
618 << point_trachea[0] << " "
619 << point_trachea[1] << " "
622 treeInfo.myWorkspace->SetInterface( &myPlugins );
623 std::string err = treeInfo.myWorkspace->LoadWorkspace( "./workspace_airwaysappli.wxml" );
626 std::cerr << "Error: " << err << std::endl;
630 treeInfo.myWorkspace->SetParameter( "FileNames@reader", filepath_airwayImage );
631 treeInfo.myWorkspace->SetParameter( "Text@seed", seed_stream.str( ) );
632 vectorInfo.push_back(treeInfo);
639 // -------------------------------------------------------------------------
640 void printCommonTreeBetweenTwoTrees(AirwaysTree tree_A, AirwaysTree tree_B, std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > > vector_pair_edges_A_to_B, unsigned int Q, unsigned int F)
642 std::cout << "printCommonTreeBetweenTwoTrees, edges:" << vector_pair_edges_A_to_B.size() << std::endl;
644 // Vtk points, cell array, and colors
645 vtkSmartPointer<vtkPoints> points_common = vtkSmartPointer<vtkPoints>::New();
646 vtkSmartPointer<vtkCellArray> lines_common = vtkSmartPointer<vtkCellArray>::New();
647 vtkSmartPointer<vtkUnsignedCharArray> colors_common = vtkSmartPointer<vtkUnsignedCharArray>::New();
648 colors_common->SetNumberOfComponents(3);
649 colors_common->SetName("Colors");
651 // Add all the points
652 // 0 - 1000 points for tree A and from 1001 for tree B
653 points_common->SetNumberOfPoints(1000 + tree_B.GetWeight() + 100);
655 // Add points for tree A
656 vec_nodes vector_nodesA = tree_A.GetNodes();
657 for(vec_nodes::iterator it_nodesA = vector_nodesA.begin(); it_nodesA != vector_nodesA.end(); ++it_nodesA)
659 points_common->SetPoint((*it_nodesA)->GetId(),(*it_nodesA)->GetCoords().GetVec3());
662 // Add points for tree B
663 vec_nodes vector_nodesB = tree_B.GetNodes();
664 for(vec_nodes::iterator it_nodesB = vector_nodesB.begin(); it_nodesB != vector_nodesB.end(); ++it_nodesB)
666 points_common->SetPoint((*it_nodesB)->GetId()+1000,(*it_nodesB)->GetCoords().GetVec3());
669 // Add the edges for both trees
670 std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > >::iterator it_edges = vector_pair_edges_A_to_B.begin();
671 int number_pairs = 0;
672 for(; it_edges != vector_pair_edges_A_to_B.end(); ++it_edges)
674 std::cout << "Pair:" << number_pairs << std::endl;
675 std::pair<Node*, Node*> edge_A = (*it_edges).first;
676 std::pair<Node*, Node*> edge_B = (*it_edges).second;
679 edge_A.first->GetPathToNode(edge_A.second, path_A);
682 edge_B.first->GetPathToNode(edge_B.second, path_B);
684 // Set color to be used
685 int numColor = number_pairs % 6;
686 unsigned char color[3];
696 else if(numColor == 2)
702 else if(numColor == 3)
704 color[0] = yellow[0];
705 color[1] = yellow[1];
706 color[2] = yellow[2];
708 else if(numColor == 4)
710 color[0] = purple[0];
711 color[1] = purple[1];
712 color[2] = purple[2];
714 else if(numColor == 5)
724 //if(path_A.size() > 0 && number_pairs < 50)
727 vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
728 lines_common->InsertNextCell(path_A.size());
730 for(vec_nodes::iterator it_pathA = path_A.begin(); it_pathA != path_A.end(); ++it_pathA)
732 lines_common->InsertCellPoint((*it_pathA)->GetId());
733 //line->GetPointIds()->SetId( id_point, (*it_pathA)->GetId() );
736 //lines_common->InsertNextCell(line);
737 colors_common->InsertNextTupleValue(color);
741 std::cout << "No path A" << std::endl;
746 //if(path_B.size() > 0 && number_pairs < 50)
749 vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
750 lines_common->InsertNextCell(path_B.size());
752 for(vec_nodes::iterator it_pathB = path_B.begin(); it_pathB != path_B.end(); ++it_pathB)
754 lines_common->InsertCellPoint((*it_pathB)->GetId()+1000);
755 //line->GetPointIds()->SetId( id_point, (*it_pathB)->GetId()+1000 );
758 //lines_common->InsertNextCell(line);
759 colors_common->InsertNextTupleValue(color);
763 std::cout << "No path B" << std::endl;
768 // Create the polydata
769 vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New();
771 // Set the points, lines, and colors
772 linesPolyData->SetPoints(points_common);
773 linesPolyData->SetLines(lines_common);
774 linesPolyData->GetCellData()->SetScalars(colors_common);
776 // ------------------------------------------------
777 // Write the vtk file
779 // Create the pathfile to save
780 std::stringstream filepath_actualIteration;
781 filepath_actualIteration << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << ".vtk";
782 std::cout << "File to save:" << filepath_actualIteration.str() << std::endl;
785 vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
786 writer->SetFileName(filepath_actualIteration.str().c_str());
788 // Set input and write
789 #if VTK_MAJOR_VERSION <= 5
790 writer->SetInput(linesPolyData);
792 writer->SetInputData(linesPolyData);
798 // ***************************************
799 // Save the links in a file
802 // Create the outputfile
803 std::stringstream filepath_evaluation;
804 filepath_evaluation << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << ".csv";
806 std::ofstream file(filepath_evaluation.str().c_str());
810 //file << "Node_" << tree_A.GetImageName() << " " << "Node_" << tree_B.GetImageName()<< "\n";
812 "idLocalN1 idLocalN2 "
813 "Node1x Node1y Node1z "
814 "Node2x Node2y Node2z "
816 "idMatch" << std::endl;
819 std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > >::iterator it_edges = vector_pair_edges_A_to_B.begin();
820 for(; it_edges != vector_pair_edges_A_to_B.end(); ++it_edges)
823 std::pair<Node*, Node*> edge_A = (*it_edges).first;
824 std::pair<Node*, Node*> edge_B = (*it_edges).second;
826 //file << edge_A.second->GetId() << " " << edge_B.second->GetId()+1000 << "\n";
827 Vec3 coord_EndNodeA = edge_A.second->GetCoords();
828 Vec3 coord_EndNodeB = edge_B.second->GetCoords();
829 file << tree_A.GetImageName() << " " <<
830 edge_A.second->GetId() << " " << edge_B.second->GetId()+1000 << " " <<
831 coord_EndNodeA[0] << " " << coord_EndNodeA[1] << " " << coord_EndNodeA[2] << " " <<
832 coord_EndNodeB[0] << " " << coord_EndNodeB[1] << " " << coord_EndNodeB[2] << " " <<
833 tree_A.GetImageName() << coord_EndNodeA[0] << coord_EndNodeA[1] << coord_EndNodeA[2] << " " <<
834 tree_B.GetImageName() << coord_EndNodeB[0] << coord_EndNodeB[1] << coord_EndNodeB[2] <<"\n";
836 file << tree_B.GetImageName() << " " <<
837 edge_B.second->GetId()+1000 << " " << edge_A.second->GetId() << " " <<
838 coord_EndNodeB[0] << " " << coord_EndNodeB[1] << " " << coord_EndNodeB[2] << " " <<
839 coord_EndNodeA[0] << " " << coord_EndNodeA[1] << " " << coord_EndNodeA[2] << " " <<
840 tree_B.GetImageName() << coord_EndNodeB[0] << coord_EndNodeB[1] << coord_EndNodeB[2] << " " <<
841 tree_A.GetImageName() << coord_EndNodeA[0] << coord_EndNodeA[1] << coord_EndNodeA[2] << "\n";
847 // ***************************************
852 std::cout << "printCommonTreeBetweenTwoTrees ... OK" << std::endl;
855 // -------------------------------------------------------------------------
856 void printMatchingResultToFile(AirwaysTree tree_A, AirwaysTree tree_B, std::map< unsigned int, std::vector<Node*> > map_A_to_B, std::map< unsigned int, std::vector<Node*> > map_B_to_A, unsigned int Q, unsigned int F)
858 std::cout << "Printing matching result ... " << std::endl;
860 // Variables and types
861 typedef std::map< unsigned int, vec_nodes > map_id_node;
863 // Create the outputfile
864 std::stringstream filepath_evaluation;
865 filepath_evaluation << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << "_matching.csv";
867 std::ofstream file(filepath_evaluation.str().c_str());
871 file << "TreeName idLocalN1 idLocalN2 "
872 "Node1x Node1y Node1z "
873 "Node2x Node2y Node2z "
876 "typeMatch_match_1_nonmatch_0 "
883 // Save the match or non-match for each node from A to B
884 for(int id_a=1; id_a <= tree_A.GetWeight( ); ++id_a)
886 // Get the actual node in tree A
887 Node* node_a = tree_A.GetNodeById( id_a );
888 Vec3 coords_a = node_a->GetCoords();
889 unsigned int depth_a = tree_A.GetDepthById(id_a);
890 bool leaf_a = node_a->IsLeaf();
892 // Check if the node was matched
893 map_id_node::iterator it_a2b = map_A_to_B.find( id_a );
894 if( it_a2b != map_A_to_B.end( ) )
896 // Get the correspoding matching nodes and print them
897 vec_nodes nodes_B = (*it_a2b).second;
899 vec_nodes::iterator it_nodes_b = nodes_B.begin( );
900 for( ; it_nodes_b != nodes_B.end( ); ++it_nodes_b)
902 Vec3 coords_b = (*it_nodes_b)->GetCoords();
904 file << tree_A.GetImageName() << " " << id_a << " " << (*it_nodes_b)->GetId()+1000 << " "
905 << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
906 << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
907 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << " "
908 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << coords_b[0] << coords_b[1] << coords_b[2] << " "
916 file << tree_A.GetImageName() << " " << id_a << " " << "0" << " "
917 << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
918 << "0" << " " << "0" << " " << "0" << " "
919 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << " "
920 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << "0" << "0" << "0" << " "
930 // Save the match or non-match for each node from A to B
931 for(int id_b=1; id_b <= tree_B.GetWeight( ); ++id_b)
933 // Get the actual node in tree B
934 Node* node_b = tree_B.GetNodeById( id_b );
935 Vec3 coords_b = node_b->GetCoords();
936 unsigned int depth_b = tree_B.GetDepthById(id_b);
937 bool leaf_b = node_b->IsLeaf();
939 // Check if the node was matched
940 map_id_node::iterator it_b2a = map_B_to_A.find( id_b );
941 if( it_b2a != map_B_to_A.end( ) )
943 // Get the correspoding matching nodes and print them
944 vec_nodes nodes_A = (*it_b2a).second;
946 vec_nodes::iterator it_nodes_a = nodes_A.begin( );
947 for( ; it_nodes_a != nodes_A.end( ); ++it_nodes_a)
949 Vec3 coords_a = (*it_nodes_a)->GetCoords();
951 file << tree_B.GetImageName() << " " << id_b+1000 << " " << (*it_nodes_a)->GetId() << " "
952 << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
953 << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
954 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << " "
955 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << coords_a[0] << coords_a[1] << coords_a[2] << " "
963 file << tree_B.GetImageName() << " " << id_b+1000 << " " << "0" << " "
964 << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
965 << "0" << " " << "0" << " " << "0" << " "
966 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << " "
967 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << "0" << "0" << "0" << " "
975 file.close(); // Close the file
977 std::cout << "Printing matching result DONE" << std::endl;
980 // -------------------------------------------------------------------------
981 void createLinesAndPointsForVTK(const Node* node, vtkSmartPointer<vtkPoints>& pts,vtkSmartPointer<vtkCellArray>& lines, vtkSmartPointer<vtkUnsignedCharArray>& colors, bool common, bool isRoot)
983 // Insert the actual point/node
984 //vtkIdType id_father = idNonRoot;
986 //id_father = pts->InsertNextPoint(node->GetCoords().GetVec3());
987 vtkIdType id_father = node->GetId();
989 pts->SetPoint(id_father,node->GetCoords().GetVec3());
991 // Iterate over the children
992 const vec_nodes children = node->GetChildren();
993 for (vec_nodes::const_iterator it_child = children.begin(); it_child != children.end(); ++it_child)
995 if (!(*it_child)->IsMarked() && common)
998 //vtkIdType id_son = pts->InsertNextPoint((*it_child)->GetCoords().GetVec3());
999 vtkIdType id_son = (*it_child)->GetId();
1000 pts->SetPoint(id_son,(*it_child)->GetCoords().GetVec3());
1002 // Set color to be used
1003 int numColor = (*it_child)->GetLevel() % 4;
1005 colors->InsertNextTupleValue(green);
1006 else if(numColor == 1)
1007 colors->InsertNextTupleValue(red);
1008 else if(numColor == 2)
1009 colors->InsertNextTupleValue(red);
1011 colors->InsertNextTupleValue(red);
1014 vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
1015 line->GetPointIds()->SetId(0, id_father);
1016 line->GetPointIds()->SetId(1, id_son);
1017 lines->InsertNextCell(line);
1019 createLinesAndPointsForVTK(*it_child, pts, lines, colors, common, false);