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>
469 template< class TImage, class TVertex >
470 Node* FAVertexToNode( TVertex vertex, TImage* image )
472 //The FrontAlgorithms Vertex is an TImageType::IndexType
473 typename TImage::PointType point;
474 image->TransformIndexToPhysicalPoint( vertex, point );
475 Vec3 alfPoint(point[0],point[1],point[2]);
476 return new Node(alfPoint);
479 AirwaysTree& ConvertFilterToAirwaysTree( TInputImage* input_image, cpPlugins::Workspace& ws )
482 fpa::Base::ImageSkeleton< fpa::Image::MinimumSpanningTree< 3 > >
484 typedef TFASkeleton::TVertex TVertexFA;
485 typedef TFASkeleton::TVertexCmp TVertexCompareFA;
486 typedef cpExtensions::DataStructures::ImageIndexesContainer< 3 > TVerticesFA;
488 typedef Node TVertexAirways;
489 typedef Edge TEdgeAirways;
490 typedef pair_posVox_rad TSkelePoint;
491 typedef vec_pair_posVox_rad TSkelePoints;
492 typedef std::map< TVertexFA, TVertexAirways*, TVertexCompareFA > VertexMap;
494 std::time_t start,end;
496 std::cout << "Starting conversion " << std::endl;
498 auto w_filter = ws.GetFilter( "eb" );
500 ws.GetFilter( "dmap" )->GetOutputData( "Output" )->
501 GetITK< itk::Image< float, 3 > >( );
503 w_filter->GetOutputData( "Skeleton" )->GetITK< TFASkeleton >( );
504 const auto& branches = sk->Get( );
506 ws.GetFilter( "seed" )->GetOutputData( "Output" )->
507 GetITK< TVerticesFA >( )->Get( )[ 0 ];
509 std::queue< TVertexFA > q;
510 // TODO: std::set< TVertexFA, TVertexCompareFA > marks;
514 auto sVertex = q.front( );
516 auto sIt = branches.find( sVertex );
518 if( marks.find( sVertex ) != marks.end( ) )
520 std::cout << "MARK!!!!! : " << sVertex << std::endl;
522 marks.insert( sVertex );
525 // End node... do nothing
526 if( sIt == branches.end( ) )
529 // Create source node
530 auto srcIt = vertexMap.find( sVertex );
531 if( srcIt == vertexMap.end( ) )
532 srcIt = vertexMap.insert(
533 VertexMap::value_type(
534 sVertex, FAVertexToNode( sVertex, input_image )
538 // TODO: std::cout << sVertex << " " << " " << sLevel << " " << seed0 << std::endl;
539 // Create destination nodes
540 for( auto eIt = sIt->second.begin( ); eIt != sIt->second.end( ); ++eIt )
542 auto dstIt = vertexMap.find( eIt->first );
543 if( dstIt == vertexMap.end( ) )
544 dstIt = vertexMap.insert(
545 VertexMap::value_type(
546 eIt->first, FAVertexToNode( eIt->first, input_image )
550 // Connect in the acyclic graph
551 dstIt->second->SetFather( srcIt->second );
552 srcIt->second->AddChild( dstIt->second );
554 // Create detailed edge
555 TEdgeAirways* edge = new Edge( );
556 edge->SetSource( srcIt->second );
557 edge->SetTarget( dstIt->second );
558 auto path = eIt->second->GetVertexList( );
559 for( unsigned int pIt = 0; pIt < path->Size( ); ++pIt )
561 itk::ImageBase< 3 >::PointType pnt;
562 auto cidx = path->GetElement( pIt );
563 input_image->TransformContinuousIndexToPhysicalPoint( cidx, pnt );
565 input_image->TransformPhysicalPointToIndex( pnt, idx );
566 Vec3 coords = FAVertexToNode( idx, input_image )->GetCoords( );
567 pair_posVox_rad skPair( coords, distance_map->GetPixel( idx ) );
568 edge->AddSkeletonPairInfo( skPair );
572 // Finish association
573 dstIt->second->SetEdge( edge );
575 // Put it as next candidate
576 q.push( eIt->first );
583 new AirwaysTree( input_image, NULL, vertexMap[ seed0 ], false );
585 std::cout << "Finished conversion. New AlfTree has weight: "<<tree->GetWeight()<<". Takes "<<(end-start)<<" s." << std::endl;
589 // -------------------------------------------------------------------------
590 AirwaysTree& CreateAirwaysTreeFromSegmentation(Vec3 seed, TInputImage* input_image, cpPlugins::Workspace& ws )
592 return( ConvertFilterToAirwaysTree( input_image, ws ) );
595 // -------------------------------------------------------------------------
596 vector<TreeInfo> ReadInputFile(const char* filename)
599 std::ifstream infile(filename);
601 std::string folderpath_allResults;
602 vector<TreeInfo> vectorInfo;
604 bool firstLine = false;
606 while (std::getline(infile, line))
608 // First line contains the output folder
609 std::istringstream iss(line);
612 if (!(iss >> folderpath_allResults))
614 std::cout << "no file" << std::endl;
619 // Other lines, not the first one, contain the information for the airways to be created
623 float point_trachea[3];
624 std::string filepath_airwayImage, name_pig, name_image;
625 if (!(iss >> point_trachea[0] >> point_trachea[1] >> point_trachea[2] >> filepath_airwayImage >> name_pig >> name_image))
627 std::cout << "There is no tree information in the file." << std::endl;
633 std::cout << "Point trachea:[" << point_trachea[0] << "," << point_trachea[1] << "," << point_trachea[2] << "]" << std::endl;
639 Vec3 seed(point_trachea[0], point_trachea[1], point_trachea[2]); //real coords seed
640 treeInfo.seed = seed;
641 // Create the outputs
642 treeInfo.folderpath_pigResults = folderpath_allResults + "/" + name_pig + "/";
643 treeInfo.pig_name = name_pig;
644 treeInfo.image_name = name_image;
647 treeInfo.image = ReadImage<TInputImage>(filepath_airwayImage);
649 // Execute first pipeline's part
650 std::stringstream seed_stream;
652 << point_trachea[0] << " "
653 << point_trachea[1] << " "
656 treeInfo.myWorkspace->SetInterface( &myPlugins );
657 std::string err = treeInfo.myWorkspace->LoadWorkspace( "./workspace_airwaysappli.wxml" );
660 std::cerr << "Error: " << err << std::endl;
664 treeInfo.myWorkspace->SetParameter( "FileNames@reader", filepath_airwayImage );
665 treeInfo.myWorkspace->SetParameter( "Text@seed", seed_stream.str( ) );
666 vectorInfo.push_back(treeInfo);
673 // -------------------------------------------------------------------------
674 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)
676 std::cout << "printCommonTreeBetweenTwoTrees, edges:" << vector_pair_edges_A_to_B.size() << std::endl;
678 // Vtk points, cell array, and colors
679 vtkSmartPointer<vtkPoints> points_common = vtkSmartPointer<vtkPoints>::New();
680 vtkSmartPointer<vtkCellArray> lines_common = vtkSmartPointer<vtkCellArray>::New();
681 vtkSmartPointer<vtkUnsignedCharArray> colors_common = vtkSmartPointer<vtkUnsignedCharArray>::New();
682 colors_common->SetNumberOfComponents(3);
683 colors_common->SetName("Colors");
685 // Add all the points
686 // 0 - 1000 points for tree A and from 1001 for tree B
687 points_common->SetNumberOfPoints(1000 + tree_B.GetWeight() + 100);
689 // Add points for tree A
690 vec_nodes vector_nodesA = tree_A.GetNodes();
691 for(vec_nodes::iterator it_nodesA = vector_nodesA.begin(); it_nodesA != vector_nodesA.end(); ++it_nodesA)
693 points_common->SetPoint((*it_nodesA)->GetId(),(*it_nodesA)->GetCoords().GetVec3());
696 // Add points for tree B
697 vec_nodes vector_nodesB = tree_B.GetNodes();
698 for(vec_nodes::iterator it_nodesB = vector_nodesB.begin(); it_nodesB != vector_nodesB.end(); ++it_nodesB)
700 points_common->SetPoint((*it_nodesB)->GetId()+1000,(*it_nodesB)->GetCoords().GetVec3());
703 // Add the edges for both trees
704 std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > >::iterator it_edges = vector_pair_edges_A_to_B.begin();
705 int number_pairs = 0;
706 for(; it_edges != vector_pair_edges_A_to_B.end(); ++it_edges)
708 std::cout << "Pair:" << number_pairs << std::endl;
709 std::pair<Node*, Node*> edge_A = (*it_edges).first;
710 std::pair<Node*, Node*> edge_B = (*it_edges).second;
713 edge_A.first->GetPathToNode(edge_A.second, path_A);
716 edge_B.first->GetPathToNode(edge_B.second, path_B);
718 // Set color to be used
719 int numColor = number_pairs % 6;
720 unsigned char color[3];
730 else if(numColor == 2)
736 else if(numColor == 3)
738 color[0] = yellow[0];
739 color[1] = yellow[1];
740 color[2] = yellow[2];
742 else if(numColor == 4)
744 color[0] = purple[0];
745 color[1] = purple[1];
746 color[2] = purple[2];
748 else if(numColor == 5)
758 //if(path_A.size() > 0 && number_pairs < 50)
761 vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
762 lines_common->InsertNextCell(path_A.size());
764 for(vec_nodes::iterator it_pathA = path_A.begin(); it_pathA != path_A.end(); ++it_pathA)
766 lines_common->InsertCellPoint((*it_pathA)->GetId());
767 //line->GetPointIds()->SetId( id_point, (*it_pathA)->GetId() );
770 //lines_common->InsertNextCell(line);
771 colors_common->InsertNextTupleValue(color);
775 std::cout << "No path A" << std::endl;
780 //if(path_B.size() > 0 && number_pairs < 50)
783 vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
784 lines_common->InsertNextCell(path_B.size());
786 for(vec_nodes::iterator it_pathB = path_B.begin(); it_pathB != path_B.end(); ++it_pathB)
788 lines_common->InsertCellPoint((*it_pathB)->GetId()+1000);
789 //line->GetPointIds()->SetId( id_point, (*it_pathB)->GetId()+1000 );
792 //lines_common->InsertNextCell(line);
793 colors_common->InsertNextTupleValue(color);
797 std::cout << "No path B" << std::endl;
802 // Create the polydata
803 vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New();
805 // Set the points, lines, and colors
806 linesPolyData->SetPoints(points_common);
807 linesPolyData->SetLines(lines_common);
808 linesPolyData->GetCellData()->SetScalars(colors_common);
810 // ------------------------------------------------
811 // Write the vtk file
813 // Create the pathfile to save
814 std::stringstream filepath_actualIteration;
815 filepath_actualIteration << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << ".vtk";
816 std::cout << "File to save:" << filepath_actualIteration.str() << std::endl;
819 vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
820 writer->SetFileName(filepath_actualIteration.str().c_str());
822 // Set input and write
823 #if VTK_MAJOR_VERSION <= 5
824 writer->SetInput(linesPolyData);
826 writer->SetInputData(linesPolyData);
832 // ***************************************
833 // Save the links in a file
836 // Create the outputfile
837 std::stringstream filepath_evaluation;
838 filepath_evaluation << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << ".csv";
840 std::ofstream file(filepath_evaluation.str().c_str());
844 //file << "Node_" << tree_A.GetImageName() << " " << "Node_" << tree_B.GetImageName()<< "\n";
846 "idLocalN1 idLocalN2 "
847 "Node1x Node1y Node1z "
848 "Node2x Node2y Node2z "
850 "idMatch" << std::endl;
853 std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > >::iterator it_edges = vector_pair_edges_A_to_B.begin();
854 for(; it_edges != vector_pair_edges_A_to_B.end(); ++it_edges)
857 std::pair<Node*, Node*> edge_A = (*it_edges).first;
858 std::pair<Node*, Node*> edge_B = (*it_edges).second;
860 //file << edge_A.second->GetId() << " " << edge_B.second->GetId()+1000 << "\n";
861 Vec3 coord_EndNodeA = edge_A.second->GetCoords();
862 Vec3 coord_EndNodeB = edge_B.second->GetCoords();
863 file << tree_A.GetImageName() << " " <<
864 edge_A.second->GetId() << " " << edge_B.second->GetId()+1000 << " " <<
865 coord_EndNodeA[0] << " " << coord_EndNodeA[1] << " " << coord_EndNodeA[2] << " " <<
866 coord_EndNodeB[0] << " " << coord_EndNodeB[1] << " " << coord_EndNodeB[2] << " " <<
867 tree_A.GetImageName() << coord_EndNodeA[0] << coord_EndNodeA[1] << coord_EndNodeA[2] << " " <<
868 tree_B.GetImageName() << coord_EndNodeB[0] << coord_EndNodeB[1] << coord_EndNodeB[2] <<"\n";
870 file << tree_B.GetImageName() << " " <<
871 edge_B.second->GetId()+1000 << " " << edge_A.second->GetId() << " " <<
872 coord_EndNodeB[0] << " " << coord_EndNodeB[1] << " " << coord_EndNodeB[2] << " " <<
873 coord_EndNodeA[0] << " " << coord_EndNodeA[1] << " " << coord_EndNodeA[2] << " " <<
874 tree_B.GetImageName() << coord_EndNodeB[0] << coord_EndNodeB[1] << coord_EndNodeB[2] << " " <<
875 tree_A.GetImageName() << coord_EndNodeA[0] << coord_EndNodeA[1] << coord_EndNodeA[2] << "\n";
881 // ***************************************
886 std::cout << "printCommonTreeBetweenTwoTrees ... OK" << std::endl;
889 // -------------------------------------------------------------------------
890 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)
892 std::cout << "Printing matching result ... " << std::endl;
894 // Variables and types
895 typedef std::map< unsigned int, vec_nodes > map_id_node;
897 // Create the outputfile
898 std::stringstream filepath_evaluation;
899 filepath_evaluation << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << "_matching.csv";
901 std::ofstream file(filepath_evaluation.str().c_str());
905 file << "TreeName idLocalN1 idLocalN2 "
906 "Node1x Node1y Node1z "
907 "Node2x Node2y Node2z "
910 "typeMatch_match_1_nonmatch_0 "
917 // Save the match or non-match for each node from A to B
918 for(int id_a=1; id_a <= tree_A.GetWeight( ); ++id_a)
920 // Get the actual node in tree A
921 Node* node_a = tree_A.GetNodeById( id_a );
922 Vec3 coords_a = node_a->GetCoords();
923 unsigned int depth_a = tree_A.GetDepthById(id_a);
924 bool leaf_a = node_a->IsLeaf();
926 // Check if the node was matched
927 map_id_node::iterator it_a2b = map_A_to_B.find( id_a );
928 if( it_a2b != map_A_to_B.end( ) )
930 // Get the correspoding matching nodes and print them
931 vec_nodes nodes_B = (*it_a2b).second;
933 vec_nodes::iterator it_nodes_b = nodes_B.begin( );
934 for( ; it_nodes_b != nodes_B.end( ); ++it_nodes_b)
936 Vec3 coords_b = (*it_nodes_b)->GetCoords();
938 file << tree_A.GetImageName() << " " << id_a << " " << (*it_nodes_b)->GetId()+1000 << " "
939 << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
940 << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
941 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << " "
942 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << coords_b[0] << coords_b[1] << coords_b[2] << " "
950 file << tree_A.GetImageName() << " " << id_a << " " << "0" << " "
951 << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
952 << "0" << " " << "0" << " " << "0" << " "
953 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << " "
954 << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << "0" << "0" << "0" << " "
964 // Save the match or non-match for each node from A to B
965 for(int id_b=1; id_b <= tree_B.GetWeight( ); ++id_b)
967 // Get the actual node in tree B
968 Node* node_b = tree_B.GetNodeById( id_b );
969 Vec3 coords_b = node_b->GetCoords();
970 unsigned int depth_b = tree_B.GetDepthById(id_b);
971 bool leaf_b = node_b->IsLeaf();
973 // Check if the node was matched
974 map_id_node::iterator it_b2a = map_B_to_A.find( id_b );
975 if( it_b2a != map_B_to_A.end( ) )
977 // Get the correspoding matching nodes and print them
978 vec_nodes nodes_A = (*it_b2a).second;
980 vec_nodes::iterator it_nodes_a = nodes_A.begin( );
981 for( ; it_nodes_a != nodes_A.end( ); ++it_nodes_a)
983 Vec3 coords_a = (*it_nodes_a)->GetCoords();
985 file << tree_B.GetImageName() << " " << id_b+1000 << " " << (*it_nodes_a)->GetId() << " "
986 << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
987 << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
988 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << " "
989 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << coords_a[0] << coords_a[1] << coords_a[2] << " "
997 file << tree_B.GetImageName() << " " << id_b+1000 << " " << "0" << " "
998 << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
999 << "0" << " " << "0" << " " << "0" << " "
1000 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << " "
1001 << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << "0" << "0" << "0" << " "
1009 file.close(); // Close the file
1011 std::cout << "Printing matching result DONE" << std::endl;
1014 // -------------------------------------------------------------------------
1015 void createLinesAndPointsForVTK(const Node* node, vtkSmartPointer<vtkPoints>& pts,vtkSmartPointer<vtkCellArray>& lines, vtkSmartPointer<vtkUnsignedCharArray>& colors, bool common, bool isRoot)
1017 // Insert the actual point/node
1018 //vtkIdType id_father = idNonRoot;
1020 //id_father = pts->InsertNextPoint(node->GetCoords().GetVec3());
1021 vtkIdType id_father = node->GetId();
1023 pts->SetPoint(id_father,node->GetCoords().GetVec3());
1025 // Iterate over the children
1026 const vec_nodes children = node->GetChildren();
1027 for (vec_nodes::const_iterator it_child = children.begin(); it_child != children.end(); ++it_child)
1029 if (!(*it_child)->IsMarked() && common)
1032 //vtkIdType id_son = pts->InsertNextPoint((*it_child)->GetCoords().GetVec3());
1033 vtkIdType id_son = (*it_child)->GetId();
1034 pts->SetPoint(id_son,(*it_child)->GetCoords().GetVec3());
1036 // Set color to be used
1037 int numColor = (*it_child)->GetLevel() % 4;
1039 colors->InsertNextTupleValue(green);
1040 else if(numColor == 1)
1041 colors->InsertNextTupleValue(red);
1042 else if(numColor == 2)
1043 colors->InsertNextTupleValue(red);
1045 colors->InsertNextTupleValue(red);
1048 vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
1049 line->GetPointIds()->SetId(0, id_father);
1050 line->GetPointIds()->SetId(1, id_son);
1051 lines->InsertNextCell(line);
1053 createLinesAndPointsForVTK(*it_child, pts, lines, colors, common, false);