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];
126 info.myWorkspace->Execute( "eb" );
128 catch( itk::ExceptionObject& err )
130 std::cerr << "Error: " << err << std::endl;
135 AirwaysTree tree = CreateAirwaysTreeFromSegmentation( info.seed, info.Image, *(info.myWorkspace ));
136 tree.SetResultPath(info.folderpath_pigResults);
137 tree.SetImageName(info.image_name);
138 aVector.push_back(tree);
140 for (unsigned int i = 0; i < aVector.size(); ++i)
142 CreateResultDirectory(aVector[i]);
143 std::string fullPath = aVector[i].GetResultPath() + "/" + aVector[i].GetImageName() + ".vtk";
144 DrawVTKLinesFromTree(aVector[i], fullPath, false);
149 // Subtree levels option
150 if (vm.count("subtree_levels"))
153 else if (vm.count("subtree_length"))
156 else if (vm.count("subtree_diameter"))
160 if (vm.count("compare_trees"))
162 std::cout << "Option: Compare trees" << std::endl;
164 * this piece of code only test in the case of two trees, so it can be replaced
165 * to a code which does a cascade
168 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
169 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
170 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
171 //CODIGO DE COMPARACIÓN DE ARBOLES
172 //std::cout << "Comparing trees ..." << std::endl;
173 //aVector[0].CompareTrees(aVector[1]);
174 //std::cout << "Comparing trees ... OK" << std::endl;
176 std::cout << "Tree A ... " << std::endl;
177 //aVector[0].printNodeAndChildrenIds();
178 std::cout << "Tree A ... OK" << std::endl;
180 std::cout << "Tree B ... " << std::endl;
181 //aVector[1].printNodeAndChildrenIds();
182 std::cout << "Tree B ... OK" << std::endl;
184 std::cout << "Comparing trees Orkisz-Morales..." << std::endl;
185 // Vectors to save the common and uncommon nodes
188 vec_nodes nonCommonA;
189 vec_nodes nonCommonB;
190 std::map< unsigned int, std::vector<Node*> > map_A_to_B;
191 std::map< unsigned int, std::vector<Node*> > map_B_to_A;
192 std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > > vector_pair_edges_A_to_B;
194 // Input parameter for comparison
195 unsigned int Q = 1; // Corresponds to the depth to select "fathers" nodes
196 unsigned int F = 1; // Correspond to the depth to select "family" nodes
197 std::cout << "Q = " << Q << std::endl;
198 std::cout << "F = " << F << std::endl;
200 clock_t before_compare = clock();
201 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);
202 clock_t after_compare = clock();
203 double compare_time = double(after_compare - before_compare) / CLOCKS_PER_SEC;
204 std::cout << "Matching time: " << compare_time << std::endl;
206 // Print the common tree with common edges
207 printCommonTreeBetweenTwoTrees(aVector[0], aVector[1], vector_pair_edges_A_to_B, Q, F);
208 printMatchingResultToFile(aVector[0], aVector[1], map_A_to_B, map_B_to_A, Q, F);
209 //printSeparatedCommonTrees(aVector[0], aVector[1], vector_pair_edges_A_to_B, Q, F);
210 //reconstructAndSaveCommonTrees(aVector[0], aVector[1], vector_pair_edges_A_to_B, Q, F);
212 // Print all the maps that have more that two connections
213 std::cout << "Printing multiple relation A to B. Total relations: " << map_A_to_B.size() << std::endl;
214 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)
216 if((*it_map_A_to_B).second.size() > 1)
218 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;
219 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)
221 std::cout << "Id: " << (*it_node)->GetId() << std::endl;
225 std::cout << "Printing multiple relation A to B ... OK" << std::endl;
227 std::cout << "Printing multiple relation B to A. Total relations: " << map_B_to_A.size() << std::endl;
228 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)
230 if((*it_map_B_to_A).second.size() > 1)
232 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;
233 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)
235 std::cout << "Id: " << (*it_node)->GetId() << std::endl;
239 std::cout << "Printing multiple relation B to A ... OK" << std::endl;
241 // Mark only the common nodes
242 aVector[0].UnMarkAll();
243 aVector[1].UnMarkAll();
245 // --------------------------------------
246 // ------ Get common paths marked -------
247 // --------------------------------------
250 std::string path_folder = "/run/media/alfredo/Data/Pulmones/results/airwaysGraphs/comparisonResutls/probes/";
251 std::string suffix_vtk = ".vtk";
252 std::string name_tree = "TreeA_dP2P";
254 for(vec_nodes::iterator it_A = commonA.begin(); it_A != commonA.end(); ++it_A)
256 aVector[0].MarkPathFromNodeToNode(aVector[0].GetRoot(), (*it_A));
258 std::stringstream filepath_actualIteration;
259 filepath_actualIteration << path_folder << name_tree << "__" << iteration << "_idA_" << (*it_A)->GetId() << suffix_vtk;
261 DrawVTKLinesFromTree(aVector[0], filepath_actualIteration.str(), true);
266 name_tree = "TreeB_dP2P";
267 for(vec_nodes::iterator it_B = commonB.begin(); it_B != commonB.end(); ++it_B)
269 aVector[1].MarkPathFromNodeToNode(aVector[1].GetRoot(), (*it_B));
271 std::stringstream filepath_actualIteration;
272 filepath_actualIteration << path_folder << name_tree << "__" << iteration << "_idB_" << (*it_B)->GetId() << suffix_vtk;
274 DrawVTKLinesFromTree(aVector[1], filepath_actualIteration.str(), true);
279 // --------------------------------------
280 // --------------------------------------
283 //XXXXXXXXXXXXXXXXXXXXXXXXXXXX
284 //1. PRINT EACH NODE OF EACH TREE AND SAVE IT USING AS NAME ITS ID
287 for(int i = 2; i < aVector[0].GetWeight(); ++i)
289 //std::cout << "Writing idA: " << i << std::endl;
290 AirwaysTree* tree_id = aVector[0].GetSingleDetachedTreeNodeById(i);
291 //std::cout << "Got id: " << i << ", numberOfNodes: " << tree_id->GetWeight() << std::endl;
294 std::stringstream filepath_actualIteration;
295 filepath_actualIteration << aVector[0].GetResultPath() << "/" << aVector[0].GetImageName() << "_id_" << i << suffix_vtk;
296 DrawVTKLinesFromTree(*tree_id, filepath_actualIteration.str(), false);
300 std::cout << "Tree NULL" << std::endl;
304 for(int i = 2; i < aVector[1].GetWeight(); ++i)
306 //std::cout << "Writing idA: " << i << std::endl;
307 AirwaysTree* tree_id = aVector[1].GetSingleDetachedTreeNodeById(i);
308 //std::cout << "Got id: " << i << ", numberOfNodes: " << tree_id->GetWeight() << std::endl;
311 std::stringstream filepath_actualIteration;
312 filepath_actualIteration << aVector[1].GetResultPath() << "/" << aVector[1].GetImageName() << "_id_" << i << suffix_vtk;
313 DrawVTKLinesFromTree(*tree_id, filepath_actualIteration.str(), false);
317 std::cout << "Tree NULL" << std::endl;
320 std::cout << "Comparing trees Orkisz-Morales... OK" << std::endl;
324 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
325 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
326 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
329 aVector[0].SubIsomorphism(aVector[1]);
331 std::cout << "Flag after SubIsomorphism" << std::endl;
332 std::string fullPathA = aVector[0].GetResultPath() + "/" + aVector[0].GetImageName() + "_CMP.vtk";
333 std::string fullPathB = aVector[1].GetResultPath() + "/" + aVector[1].GetImageName() + "_CMP.vtk";
334 DrawVTKLinesFromTree(aVector[0], fullPathA, true);
335 DrawVTKLinesFromTree(aVector[1], fullPathB, true);
337 std::cout << "Flag after write vtk" << std::endl;
338 TInputImage::Pointer imgA, imgB;
339 aVector[0].ImageReconstruction(imgA);
340 std::cout << "Flag after Reconstruction A" << std::endl;
342 aVector[1].ImageReconstruction(imgB);
343 std::cout << "Flag after Reconstruction B" << std::endl;
345 std::string fullPathA_mhd = aVector[0].GetResultPath() + "/" + aVector[0].GetImageName() + "_CMP.vtk";
346 std::string fullPathB_mhd = aVector[1].GetResultPath() + "/" + aVector[1].GetImageName() + "_CMP.vtk";
347 WriteImage(imgA, fullPathA_mhd);
348 WriteImage(imgB, fullPathB_mhd);
352 po::notify(vm); // throws on error, so do after help in case
354 catch (std::exception& e)
356 std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl;
357 return ERROR_UNHANDLED_EXCEPTION;
360 catch (std::exception& e)
362 std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl;
363 return ERROR_UNHANDLED_EXCEPTION;
368 // -------------------------------------------------------------------------
369 void Load_cpPlugins( const std::string& plugins )
371 myPlugins.LoadConfiguration( plugins );
374 // -------------------------------------------------------------------------
375 void CreateResultDirectory(AirwaysTree tree)
377 boost::filesystem::path dir(tree.GetResultPath());
378 if (boost::filesystem::create_directories(dir))
380 std::cout << "FolderName = " << tree.GetResultPath() << " has been created" << std::endl;
383 std::cout << "FolderName = " << tree.GetResultPath() << " already exists" << std::endl;
386 // -------------------------------------------------------------------------
387 void DrawVTKLinesFromTree(AirwaysTree& tree, const std::string filepath, bool common)
389 // Create the array of points, lines, and colors
390 vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New();
391 vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
392 vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New();
393 colors->SetNumberOfComponents(3);
394 colors->SetName("Colors");
396 //vtk sphere for sources
397 //vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New();
398 //Vec3 root = tree.GetRoot()->GetCoords();
399 //sphereSource->SetCenter(root[0], root[1], root[2]);
400 //sphereSource->SetRadius(1);
406 // Create and fill the points, lines, and color vectors
407 //CalculateVTKLinesFromEdges(tree.GetRoot(), 0, id, pts, lines, colors, common);
408 pts->SetNumberOfPoints(tree.GetWeight()+1);
409 createLinesAndPointsForVTK(tree.GetRoot(), pts, lines, colors, common, true);
411 // Create the polydata
412 vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New();
414 // Set the points, lines, and colors
415 linesPolyData->SetPoints(pts);
416 linesPolyData->SetLines(lines);
417 linesPolyData->GetCellData()->SetScalars(colors);
420 vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
421 writer->SetFileName(filepath.c_str());
423 #if VTK_MAJOR_VERSION <= 5
424 writer->SetInput(linesPolyData);
426 writer->SetInputData(linesPolyData);
430 //The following code is to test the vtk polydata and visualize it
432 vtkSmartPointer<vtkPolyDataMapper> mapper =
433 vtkSmartPointer<vtkPolyDataMapper>::New();
434 #if VTK_MAJOR_VERSION <= 5
435 mapper->SetInput(linesPolyData);
437 mapper->SetInputData(linesPolyData);
439 vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
440 actor->SetMapper(mapper);
443 vtkSmartPointer<vtkPolyDataMapper> mapperSphere = vtkSmartPointer<
444 vtkPolyDataMapper>::New();
445 mapperSphere->SetInputConnection(sphereSource->GetOutputPort());
447 vtkSmartPointer<vtkActor> actorSphere = vtkSmartPointer<vtkActor>::New();
448 actorSphere->SetMapper(mapperSphere);
451 vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
452 vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<
453 vtkRenderWindow>::New();
454 renderWindow->AddRenderer(renderer);
455 vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
456 vtkSmartPointer<vtkRenderWindowInteractor>::New();
457 renderWindowInteractor->SetRenderWindow(renderWindow);
458 renderer->AddActor(actorSphere);
459 renderer->AddActor(actor);
461 renderWindow->Render();
462 renderWindowInteractor->Start();*/
465 // -------------------------------------------------------------------------
466 #include <fpa/Base/ImageSkeleton.h>
467 #include <fpa/Image/MinimumSpanningTree.h>
468 #include <cpExtensions/DataStructures/ImageIndexesContainer.h>
469 #include <itkImage.h>
472 template< class TImage, class TVertex >
473 Node* FAVertexToNode( TVertex vertex, TImage* image )
475 //The FrontAlgorithms Vertex is an TImageType::IndexType
476 typename TImage::PointType point;
477 image->TransformIndexToPhysicalPoint( vertex, point );
478 Vec3 alfPoint(point[0],point[1],point[2]);
479 return new Node(alfPoint);
482 AirwaysTree& ConvertFilterToAirwaysTree( TInputImage* input_image, cpPlugins::Workspace& ws )
485 fpa::Base::ImageSkeleton< fpa::Image::MinimumSpanningTree< 3 > >
487 typedef TFASkeleton::TVertex TVertexFA;
488 typedef TFASkeleton::TVertexCmp TVertexCompareFA;
489 typedef cpExtensions::DataStructures::ImageIndexesContainer< 3 > TVerticesFA;
491 typedef Node TVertexAirways;
492 typedef Edge TEdgeAirways;
493 typedef pair_posVox_rad TSkelePoint;
494 typedef vec_pair_posVox_rad TSkelePoints;
495 typedef std::map< TVertexFA, TVertexAirways*, TVertexCompareFA > VertexMap;
497 std::time_t start,end;
499 std::cout << "Starting conversion " << std::endl;
501 auto w_filter = ws.GetFilter( "eb" );
503 ws.GetFilter( "dmap" )->GetOutputData( "Output" )->
504 GetITK< itk::Image< float, 3 > >( );
506 w_filter->GetOutputData( "Skeleton" )->GetITK< TFASkeleton >( );
507 const auto& branches = sk->Get( );
509 ws.GetFilter( "seed" )->GetOutputData( "Output" )->
510 GetITK< TVerticesFA >( )->Get( )[ 0 ];
512 std::queue< TVertexFA > q;
513 // TODO: std::set< TVertexFA, TVertexCompareFA > marks;
517 auto sVertex = q.front( );
519 auto sIt = branches.find( sVertex );
521 if( marks.find( sVertex ) != marks.end( ) )
523 std::cout << "MARK!!!!! : " << sVertex << std::endl;
525 marks.insert( sVertex );
528 // End node... do nothing
529 if( sIt == branches.end( ) )
532 // Create source node
533 auto srcIt = vertexMap.find( sVertex );
534 if( srcIt == vertexMap.end( ) )
535 srcIt = vertexMap.insert(
536 VertexMap::value_type(
537 sVertex, FAVertexToNode( sVertex, input_image )
541 // TODO: std::cout << sVertex << " " << " " << sLevel << " " << seed0 << std::endl;
542 // Create destination nodes
543 for( auto eIt = sIt->second.begin( ); eIt != sIt->second.end( ); ++eIt )
545 auto dstIt = vertexMap.find( eIt->first );
546 if( dstIt == vertexMap.end( ) )
547 dstIt = vertexMap.insert(
548 VertexMap::value_type(
549 eIt->first, FAVertexToNode( eIt->first, input_image )
553 // Connect in the acyclic graph
554 dstIt->second->SetFather( srcIt->second );
555 srcIt->second->AddChild( dstIt->second );
557 // Create detailed edge
558 TEdgeAirways* edge = new Edge( );
559 edge->SetSource( srcIt->second );
560 edge->SetTarget( dstIt->second );
561 auto path = eIt->second->GetVertexList( );
562 for( unsigned int pIt = 0; pIt < path->Size( ); ++pIt )
564 itk::ImageBase< 3 >::PointType pnt;
565 auto cidx = path->GetElement( pIt );
566 input_image->TransformContinuousIndexToPhysicalPoint( cidx, pnt );
568 input_image->TransformPhysicalPointToIndex( pnt, idx );
569 Vec3 coords = FAVertexToNode( idx, input_image )->GetCoords( );
570 pair_posVox_rad skPair( coords, distance_map->GetPixel( idx ) );
571 edge->AddSkeletonPairInfo( skPair );
575 // Finish association
576 dstIt->second->SetEdge( edge );
578 // Put it as next candidate
579 q.push( eIt->first );
586 new AirwaysTree( input_image, NULL, vertexMap[ seed0 ], false );
588 std::cout << "Finished conversion. New AlfTree has weight: "<<tree->GetWeight()<<". Takes "<<(end-start)<<" s." << std::endl;
592 // -------------------------------------------------------------------------
593 AirwaysTree& CreateAirwaysTreeFromSegmentation(Vec3 seed, TInputImage* input_image, cpPlugins::Workspace& ws )
595 return( ConvertFilterToAirwaysTree( input_image, ws ) );
598 // -------------------------------------------------------------------------
599 vector<TreeInfo> ReadInputFile(const char* filename)
602 std::ifstream infile(filename);
604 std::string folderpath_allResults;
605 vector<TreeInfo> vectorInfo;
607 bool firstLine = false;
609 while (std::getline(infile, line))
611 // First line contains the output folder
612 std::istringstream iss(line);
615 if (!(iss >> folderpath_allResults))
617 std::cout << "no file" << std::endl;
622 // Other lines, not the first one, contain the information for the airways to be created
626 float point_trachea[3];
627 std::string filepath_airwayImage, name_pig, name_image;
628 if (!(iss >> point_trachea[0] >> point_trachea[1] >> point_trachea[2] >> filepath_airwayImage >> name_pig >> name_image))
630 std::cout << "There is no tree information in the file." << std::endl;
636 std::cout << "Point trachea:[" << point_trachea[0] << "," << point_trachea[1] << "," << point_trachea[2] << "]" << std::endl;
642 Vec3 seed(point_trachea[0], point_trachea[1], point_trachea[2]); //real coords seed
643 treeInfo.seed = seed;
644 // Create the outputs
645 treeInfo.folderpath_pigResults = folderpath_allResults + "/" + name_pig + "/";
646 treeInfo.pig_name = name_pig;
647 treeInfo.image_name = name_image;
650 treeInfo.image = ReadImage<TInputImage>(filepath_airwayImage);
652 // Execute first pipeline's part
653 std::stringstream seed_stream;
655 << point_trachea[0] << " "
656 << point_trachea[1] << " "
659 treeInfo.myWorkspace->SetInterface( &myPlugins );
660 std::string err = treeInfo.myWorkspace->LoadWorkspace( "./workspace_airwaysappli.wxml" );
663 std::cerr << "Error: " << err << std::endl;
667 treeInfo.myWorkspace->SetParameter( "FileNames@reader", filepath_airwayImage );
668 treeInfo.myWorkspace->SetParameter( "Text@seed", seed_stream.str( ) );
669 vectorInfo.push_back(treeInfo);
676 // -------------------------------------------------------------------------
677 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)
679 std::cout << "printCommonTreeBetweenTwoTrees, edges:" << vector_pair_edges_A_to_B.size() << std::endl;
681 // Vtk points, cell array, and colors
682 vtkSmartPointer<vtkPoints> points_common = vtkSmartPointer<vtkPoints>::New();
683 vtkSmartPointer<vtkCellArray> lines_common = vtkSmartPointer<vtkCellArray>::New();
684 vtkSmartPointer<vtkUnsignedCharArray> colors_common = vtkSmartPointer<vtkUnsignedCharArray>::New();
685 colors_common->SetNumberOfComponents(3);
686 colors_common->SetName("Colors");
688 // Add all the points
689 // 0 - 1000 points for tree A and from 1001 for tree B
690 points_common->SetNumberOfPoints(1000 + tree_B.GetWeight() + 100);
692 // Add points for tree A
693 vec_nodes vector_nodesA = tree_A.GetNodes();
694 for(vec_nodes::iterator it_nodesA = vector_nodesA.begin(); it_nodesA != vector_nodesA.end(); ++it_nodesA)
696 points_common->SetPoint((*it_nodesA)->GetId(),(*it_nodesA)->GetCoords().GetVec3());
699 // Add points for tree B
700 vec_nodes vector_nodesB = tree_B.GetNodes();
701 for(vec_nodes::iterator it_nodesB = vector_nodesB.begin(); it_nodesB != vector_nodesB.end(); ++it_nodesB)
703 points_common->SetPoint((*it_nodesB)->GetId()+1000,(*it_nodesB)->GetCoords().GetVec3());
706 // Add the edges for both trees
707 std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > >::iterator it_edges = vector_pair_edges_A_to_B.begin();
708 int number_pairs = 0;
709 for(; it_edges != vector_pair_edges_A_to_B.end(); ++it_edges)
711 std::cout << "Pair:" << number_pairs << std::endl;
712 std::pair<Node*, Node*> edge_A = (*it_edges).first;
713 std::pair<Node*, Node*> edge_B = (*it_edges).second;
716 edge_A.first->GetPathToNode(edge_A.second, path_A);
719 edge_B.first->GetPathToNode(edge_B.second, path_B);
721 // Set color to be used
722 int numColor = number_pairs % 6;
723 unsigned char color[3];
733 else if(numColor == 2)
739 else if(numColor == 3)
741 color[0] = yellow[0];
742 color[1] = yellow[1];
743 color[2] = yellow[2];
745 else if(numColor == 4)
747 color[0] = purple[0];
748 color[1] = purple[1];
749 color[2] = purple[2];
751 else if(numColor == 5)
761 //if(path_A.size() > 0 && number_pairs < 50)
764 vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
765 lines_common->InsertNextCell(path_A.size());
767 for(vec_nodes::iterator it_pathA = path_A.begin(); it_pathA != path_A.end(); ++it_pathA)
769 lines_common->InsertCellPoint((*it_pathA)->GetId());
770 //line->GetPointIds()->SetId( id_point, (*it_pathA)->GetId() );
773 //lines_common->InsertNextCell(line);
774 colors_common->InsertNextTupleValue(color);
778 std::cout << "No path A" << std::endl;
783 //if(path_B.size() > 0 && number_pairs < 50)
786 vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
787 lines_common->InsertNextCell(path_B.size());
789 for(vec_nodes::iterator it_pathB = path_B.begin(); it_pathB != path_B.end(); ++it_pathB)
791 lines_common->InsertCellPoint((*it_pathB)->GetId()+1000);
792 //line->GetPointIds()->SetId( id_point, (*it_pathB)->GetId()+1000 );
795 //lines_common->InsertNextCell(line);
796 colors_common->InsertNextTupleValue(color);
800 std::cout << "No path B" << std::endl;
805 // Create the polydata
806 vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New();
808 // Set the points, lines, and colors
809 linesPolyData->SetPoints(points_common);
810 linesPolyData->SetLines(lines_common);
811 linesPolyData->GetCellData()->SetScalars(colors_common);
813 // ------------------------------------------------
814 // Write the vtk file
816 // Create the pathfile to save
817 std::stringstream filepath_actualIteration;
818 filepath_actualIteration << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << ".vtk";
819 std::cout << "File to save:" << filepath_actualIteration.str() << std::endl;
822 vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
823 writer->SetFileName(filepath_actualIteration.str().c_str());
825 // Set input and write
826 #if VTK_MAJOR_VERSION <= 5
827 writer->SetInput(linesPolyData);
829 writer->SetInputData(linesPolyData);
835 // ***************************************
836 // Save the links in a file
839 // Create the outputfile
840 std::stringstream filepath_evaluation;
841 filepath_evaluation << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << ".csv";
843 std::ofstream file(filepath_evaluation.str().c_str());
847 //file << "Node_" << tree_A.GetImageName() << " " << "Node_" << tree_B.GetImageName()<< "\n";
849 "idLocalN1 idLocalN2 "
850 "Node1x Node1y Node1z "
851 "Node2x Node2y Node2z "
853 "idMatch" << std::endl;
856 std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > >::iterator it_edges = vector_pair_edges_A_to_B.begin();
857 for(; it_edges != vector_pair_edges_A_to_B.end(); ++it_edges)
860 std::pair<Node*, Node*> edge_A = (*it_edges).first;
861 std::pair<Node*, Node*> edge_B = (*it_edges).second;
863 //file << edge_A.second->GetId() << " " << edge_B.second->GetId()+1000 << "\n";
864 Vec3 coord_EndNodeA = edge_A.second->GetCoords();
865 Vec3 coord_EndNodeB = edge_B.second->GetCoords();
866 file << tree_A.GetImageName() << " " <<
867 edge_A.second->GetId() << " " << edge_B.second->GetId()+1000 << " " <<
868 coord_EndNodeA[0] << " " << coord_EndNodeA[1] << " " << coord_EndNodeA[2] << " " <<
869 coord_EndNodeB[0] << " " << coord_EndNodeB[1] << " " << coord_EndNodeB[2] << " " <<
870 tree_A.GetImageName() << coord_EndNodeA[0] << coord_EndNodeA[1] << coord_EndNodeA[2] << " " <<
871 tree_B.GetImageName() << coord_EndNodeB[0] << coord_EndNodeB[1] << coord_EndNodeB[2] <<"\n";
873 file << tree_B.GetImageName() << " " <<
874 edge_B.second->GetId()+1000 << " " << edge_A.second->GetId() << " " <<
875 coord_EndNodeB[0] << " " << coord_EndNodeB[1] << " " << coord_EndNodeB[2] << " " <<
876 coord_EndNodeA[0] << " " << coord_EndNodeA[1] << " " << coord_EndNodeA[2] << " " <<
877 tree_B.GetImageName() << coord_EndNodeB[0] << coord_EndNodeB[1] << coord_EndNodeB[2] << " " <<
878 tree_A.GetImageName() << coord_EndNodeA[0] << coord_EndNodeA[1] << coord_EndNodeA[2] << "\n";
884 // ***************************************
889 std::cout << "printCommonTreeBetweenTwoTrees ... OK" << std::endl;
892 // -------------------------------------------------------------------------
893 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)
895 std::cout << "Printing matching result ... " << std::endl;
897 // Variables and types
898 typedef std::map< unsigned int, vec_nodes > map_id_node;
900 // Create the outputfile
901 std::stringstream filepath_evaluation;
902 filepath_evaluation << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << "_matching.csv";
904 std::ofstream file(filepath_evaluation.str().c_str());
908 file << "TreeName idLocalN1 idLocalN2 "
909 "Node1x Node1y Node1z "
910 "Node2x Node2y Node2z "
913 "typeMatch_match_1_nonmatch_0 "
920 // Save the match or non-match for each node from A to B
921 for(int id_a=1; id_a <= tree_A.GetWeight( ); ++id_a)
923 // Get the actual node in tree A
924 Node* node_a = tree_A.GetNodeById( id_a );
925 Vec3 coords_a = node_a->GetCoords();
926 unsigned int depth_a = tree_A.GetDepthById(id_a);
927 bool leaf_a = node_a->IsLeaf();
929 // Check if the node was matched
930 map_id_node::iterator it_a2b = map_A_to_B.find( id_a );
931 if( it_a2b != map_A_to_B.end( ) )
933 // Get the correspoding matching nodes and print them
934 vec_nodes nodes_B = (*it_a2b).second;
936 vec_nodes::iterator it_nodes_b = nodes_B.begin( );
937 for( ; it_nodes_b != nodes_B.end( ); ++it_nodes_b)
939 Vec3 coords_b = (*it_nodes_b)->GetCoords();
941 file << tree_A.GetImageName() << " " << id_a << " " << (*it_nodes_b)->GetId()+1000 << " "
942 << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
943 << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
944 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << " "
945 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << coords_b[0] << coords_b[1] << coords_b[2] << " "
953 file << tree_A.GetImageName() << " " << id_a << " " << "0" << " "
954 << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
955 << "0" << " " << "0" << " " << "0" << " "
956 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << " "
957 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << "0" << "0" << "0" << " "
967 // Save the match or non-match for each node from A to B
968 for(int id_b=1; id_b <= tree_B.GetWeight( ); ++id_b)
970 // Get the actual node in tree B
971 Node* node_b = tree_B.GetNodeById( id_b );
972 Vec3 coords_b = node_b->GetCoords();
973 unsigned int depth_b = tree_B.GetDepthById(id_b);
974 bool leaf_b = node_b->IsLeaf();
976 // Check if the node was matched
977 map_id_node::iterator it_b2a = map_B_to_A.find( id_b );
978 if( it_b2a != map_B_to_A.end( ) )
980 // Get the correspoding matching nodes and print them
981 vec_nodes nodes_A = (*it_b2a).second;
983 vec_nodes::iterator it_nodes_a = nodes_A.begin( );
984 for( ; it_nodes_a != nodes_A.end( ); ++it_nodes_a)
986 Vec3 coords_a = (*it_nodes_a)->GetCoords();
988 file << tree_B.GetImageName() << " " << id_b+1000 << " " << (*it_nodes_a)->GetId() << " "
989 << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
990 << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
991 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << " "
992 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << coords_a[0] << coords_a[1] << coords_a[2] << " "
1000 file << tree_B.GetImageName() << " " << id_b+1000 << " " << "0" << " "
1001 << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
1002 << "0" << " " << "0" << " " << "0" << " "
1003 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << " "
1004 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << "0" << "0" << "0" << " "
1012 file.close(); // Close the file
1014 std::cout << "Printing matching result DONE" << std::endl;
1017 // -------------------------------------------------------------------------
1018 void createLinesAndPointsForVTK(const Node* node, vtkSmartPointer<vtkPoints>& pts,vtkSmartPointer<vtkCellArray>& lines, vtkSmartPointer<vtkUnsignedCharArray>& colors, bool common, bool isRoot)
1020 // Insert the actual point/node
1021 //vtkIdType id_father = idNonRoot;
1023 //id_father = pts->InsertNextPoint(node->GetCoords().GetVec3());
1024 vtkIdType id_father = node->GetId();
1026 pts->SetPoint(id_father,node->GetCoords().GetVec3());
1028 // Iterate over the children
1029 const vec_nodes children = node->GetChildren();
1030 for (vec_nodes::const_iterator it_child = children.begin(); it_child != children.end(); ++it_child)
1032 if (!(*it_child)->IsMarked() && common)
1035 //vtkIdType id_son = pts->InsertNextPoint((*it_child)->GetCoords().GetVec3());
1036 vtkIdType id_son = (*it_child)->GetId();
1037 pts->SetPoint(id_son,(*it_child)->GetCoords().GetVec3());
1039 // Set color to be used
1040 int numColor = (*it_child)->GetLevel() % 4;
1042 colors->InsertNextTupleValue(green);
1043 else if(numColor == 1)
1044 colors->InsertNextTupleValue(red);
1045 else if(numColor == 2)
1046 colors->InsertNextTupleValue(red);
1048 colors->InsertNextTupleValue(red);
1051 vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
1052 line->GetPointIds()->SetId(0, id_father);
1053 line->GetPointIds()->SetId(1, id_son);
1054 lines->InsertNextCell(line);
1056 createLinesAndPointsForVTK(*it_child, pts, lines, colors, common, false);