// Calculate the union of two reference lists. void MdamRefList::unionx(const MdamRefList & refList0Ref, const MdamRefList & refList1Ref, FixedSizeHeapManager & mdamRefListEntryHeap) { // Delete all the entries from the target list. deleteEntries(mdamRefListEntryHeap); // Obtain the first disjunct number from each source list. Int32 disjunctNum0 = disjunctNumInitialValue; Int32 disjunctNum1 = disjunctNumInitialValue; MdamRefListIterator iterator0(&refList0Ref); MdamRefListIterator iterator1(&refList1Ref); NABoolean more0 = iterator0(disjunctNum0); NABoolean more1 = iterator1(disjunctNum1); // Loop through both lists until either one is empty. while (more0 && more1) { if (disjunctNum0 == disjunctNum1) { // Disjunct numbers are equal. Keep one copy. insert(disjunctNum0, mdamRefListEntryHeap); // Advance both lists. more0 = iterator0(disjunctNum0); more1 = iterator1(disjunctNum1); } else if (disjunctNum0 < disjunctNum1) { // Disjunct number from list 0 is less. // Insert it into the result and advance list 0. insert(disjunctNum0, mdamRefListEntryHeap); more0 = iterator0(disjunctNum0); } else { // Disjunct number from list 1 is less. // Insert it into the result and advance list 1. insert(disjunctNum1, mdamRefListEntryHeap); more1 = iterator1(disjunctNum1); } } // Copy any remaining disjunct numbers from refList0Ref. while (more0) { insert(disjunctNum0, mdamRefListEntryHeap); more0 = iterator0(disjunctNum0); } // Copy any remaining disjunct numbers from refList1Ref. while (more1) { insert(disjunctNum1, mdamRefListEntryHeap); more1 = iterator1(disjunctNum1); } }
bool KMLReader::characters(const QString &ch) { if (is_point&&is_LineString) { QStringList list1, list2; list1 = ch.split(QRegExp("[ ]"), QString::SkipEmptyParts); QStringListIterator iterator1(list1); while (iterator1.hasNext()) { CPoint f; list2 = iterator1.next().split(QRegExp("[,]"), QString::SkipEmptyParts); QStringListIterator iterator2(list2); bool ok; double y = iterator2.next().toDouble(&ok); if (!ok||y<-180||y>180) return true; double x = iterator2.next().toDouble(&ok); if (!ok||x<-90||x>90) return true; if (iterator2.hasNext()) { double z = iterator2.next().toDouble(&ok); if (!ok) return true; f.setData(x,y,z); has_ele=true; } else { f.setData(x,y); if (has_ele==true) has_ele=false; } points.insert(points.size(),f); } } return true; }
void setUp() { typedef itk::Image<double, 3> ImageType; typedef itk::VectorImage<double, 3> VectorImageType; typedef itk::ImageRegionIterator<ImageType> ImageIteratorType; typedef itk::ImageDuplicator<ImageType> DuplicatorType; typedef itk::ComposeImageFilter<ImageType> CompositeFilterType; // generate two images with one component ImageType::Pointer imageComponent1 = itk::Image<double, 3>::New(); ImageType::IndexType start; start.Fill(0); ImageType::SizeType size; size.Fill(5); ImageType::RegionType region; region.SetSize(size); region.SetIndex(start); imageComponent1->SetRegions(region); imageComponent1->Allocate(); DuplicatorType::Pointer duplicator = DuplicatorType::New(); duplicator->SetInputImage(imageComponent1); duplicator->Update(); ImageType::Pointer imageComponent2 = duplicator->GetOutput(); // give them differing data ImageIteratorType iterator1(imageComponent1, imageComponent1->GetLargestPossibleRegion()); iterator1.GoToBegin(); int i = 0; while (!iterator1.IsAtEnd()) { iterator1.Set((double)i); ++iterator1; ++i; } ImageIteratorType iterator2(imageComponent2, imageComponent2->GetLargestPossibleRegion()); iterator2.GoToBegin(); i = 2000; while (!iterator2.IsAtEnd()) { iterator2.Set((double)i); ++iterator2; ++i; } // copy into single VectorImage CompositeFilterType::Pointer compositeFilter = CompositeFilterType::New(); compositeFilter->SetInput(0, imageComponent1); compositeFilter->SetInput(1, imageComponent2); compositeFilter->Update(); itk::VectorImage<double, 3>::Pointer multiComponentImage = compositeFilter->GetOutput(); // cast images to mitk mitk::CastToMitkImage(multiComponentImage, m_mitkMultiComponentImage); mitk::CastToMitkImage(imageComponent1, m_mitkImageComponent1); mitk::CastToMitkImage(imageComponent2, m_mitkImageComponent2); }
void WholeCellSeg::RemoveSmallObjs(){ typedef itk::LabelGeometryImageFilter< UShortImageType, UShortImageType > GeometryFilterType; typedef itk::LabelStatisticsImageFilter< UShortImageType,UShortImageType > StatisticsFilterType; typedef itk::CastImageFilter< UShortImageType, UShortImageType > CastUSUSType; typedef itk::ImageRegionIteratorWithIndex< UShortImageType > IteratorType; typedef GeometryFilterType::LabelIndicesType labelindicestype; std::vector< unsigned short > labelsList; GeometryFilterType::Pointer geomfilt1 = GeometryFilterType::New(); geomfilt1->SetInput( seg_im_out ); geomfilt1->SetCalculatePixelIndices( true ); geomfilt1->Update(); labelsList = geomfilt1->GetLabels(); StatisticsFilterType::Pointer statsfilt = StatisticsFilterType::New(); statsfilt->UseHistogramsOn(); statsfilt->SetInput( intermediate_bin_im_out ); statsfilt->SetLabelInput( seg_im_out ); statsfilt->Update(); CastUSUSType::Pointer castUSUSfilter = CastUSUSType::New(); if( draw_real_bounds && draw_synth_bounds ){ castUSUSfilter->SetInput( nuclab_inp ); castUSUSfilter->Update(); nuclab_inp_cpy = castUSUSfilter->GetOutput(); } for( unsigned short i=0; i<labelsList.size(); ++i ){ if( !labelsList[i] ) continue; labelindicestype indices1; indices1 = geomfilt1->GetPixelIndices( labelsList[i] ); if( !(statsfilt->GetSum( labelsList[i] )) ){ IteratorType iterator ( seg_im_out, seg_im_out->GetRequestedRegion() ); for( labelindicestype::const_iterator itPixind = indices1.begin(); itPixind != indices1.end(); ++itPixind ){ iterator.SetIndex( *itPixind ); iterator.Set( 0 ); } } else if( draw_real_bounds && draw_synth_bounds ){ IteratorType iterator1 ( nuclab_inp_cpy, nuclab_inp_cpy->GetRequestedRegion() ); for( labelindicestype::const_iterator itPixind = indices1.begin(); itPixind != indices1.end(); ++itPixind ){ iterator1.SetIndex( *itPixind ); if( iterator1.Get()==labelsList[i] ) iterator1.Set( 0 ); } } } if( !draw_synth_bounds && draw_real_bounds ) seg_done = 1; }
// Calculate the intersection of two reference lists. void MdamRefList::intersect(const MdamRefList & refList0Ref, const MdamRefList & refList1Ref, FixedSizeHeapManager & mdamRefListEntryHeap) { // Delete all the entries from this list. deleteEntries(mdamRefListEntryHeap); // Obtain the first disjunct number from each list. Int32 disjunctNum0 = disjunctNumInitialValue; Int32 disjunctNum1 = disjunctNumInitialValue; MdamRefListIterator iterator0(&refList0Ref); MdamRefListIterator iterator1(&refList1Ref); NABoolean more0 = iterator0(disjunctNum0); NABoolean more1 = iterator1(disjunctNum1); // Iterate finding disjunct numbers common to both lists. // Stop when either list is exhausted. while (more0 && more1) { if (disjunctNum0 == disjunctNum1) { // Disjunct numbers are equal. Insert into result list. insert(disjunctNum0, mdamRefListEntryHeap); // Advance both lists. more0 = iterator0(disjunctNum0); more1 = iterator1(disjunctNum1); } else if (disjunctNum0 < disjunctNum1) { // Disjunct number from list 0 is less. // Advance list 0. more0 = iterator0(disjunctNum0); } else { // Disjunct number from list 1 is less. // Advance list 1. more1 = iterator1(disjunctNum1); } } }
bool P_Thing_Move (int tid, AActor *source, int mapspot, bool fog) { AActor *target; if (tid != 0) { FActorIterator iterator1(tid); source = iterator1.Next(); } FActorIterator iterator2 (mapspot); target = iterator2.Next (); if (source != NULL && target != NULL) { return P_MoveThing(source, target->Pos(), fog); } return false; }
// //########################################################################### // TestOrder //########################################################################### // bool TreeTestNode::TestOrder() { TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); TreeTestPlug *testPlug1, *testPlug2; int i, size; size = iterator1.GetSize(); for (i = 1; i < size; i++) { testPlug1 = iterator1.GetNth(i-1); testPlug2 = iterator2.GetNth(i); Test_Assumption(testPlug1->value < testPlug2->value); } return true; }
/* use this function to compute one associative measurement */ float NuclearAssociationRules::ComputeOneAssocMeasurement(itk::SmartPointer<TargImageType> trgIm, int ruleID, int objID) { //fisrt, get the bounding box around the object //The bounding box is defined by the area around the object such that the object+outerdistance are included int imBounds[6] = {0,x_Size,0,y_Size,0,z_Size}; LabelGeometryType::BoundingBoxType bbox = labGeometryFilter->GetBoundingBox(objID); //make sure the object exists int valid = 0; for(int dim=0; dim < imDim*2; ++dim) { if(bbox[dim] > 0) valid = 1; } if(valid == 0) return -1; std::vector< int > retBbox(0); int dist, val; dist = assocRulesList[ruleID].GetOutDistance(); for(int dim=0; dim < imDim*2; ++dim) { if(dim%2 == 0) //even { val = int(bbox[dim])-dist-1; if(val<imBounds[dim]) val=imBounds[dim]; } else //odd { val = int(bbox[dim])+dist+1; if(val>=imBounds[dim]) val=imBounds[dim]-1; } retBbox.push_back( val ); } //the bounding box defines the region of interest we need (from both segmentation and target images) //so, use it to get sub images DistImageType::Pointer subSegImg = DistImageType::New(); LabImageType::IndexType start; start[0] = 0; // first index on X start[1] = 0; // first index on Y start[2] = 0; // first index on Z LabImageType::SizeType size; size[0] = retBbox[1]-retBbox[0]+1; // size along X size[1] = retBbox[3]-retBbox[2]+1; // size along Y if(imDim == 3) size[2] = retBbox[5]-retBbox[4]+1; // size along Z else size[2] = 1; LabImageType::RegionType region; region.SetSize( size ); region.SetIndex( start ); subSegImg->SetRegions( region ); subSegImg->Allocate(); subSegImg->FillBuffer(0); subSegImg->Update(); LabImageType::IndexType start2; start2[0] = retBbox[0]; // first index on X start2[1] = retBbox[2]; // first index on Y if(imDim == 3) start2[2] = retBbox[4]; // first index on Z else start2[2] = 0; LabImageType::RegionType region2; region2.SetSize( size ); region2.SetIndex( start2 ); labImage->SetRequestedRegion(region2); trgIm->SetRequestedRegion(region2); typedef itk::ImageRegionIteratorWithIndex< LabImageType > IteratorType; IteratorType iterator1(labImage, labImage->GetRequestedRegion()); typedef itk::ImageRegionIteratorWithIndex< DistImageType > IteratorType2; IteratorType2 iterator2(subSegImg, subSegImg->GetRequestedRegion()); //in the sub-segmentation image, we need to mask out any pixel from another object int counter = 0; while ( ! iterator1.IsAtEnd()) { int V = iterator1.Get(); if(V == objID) { iterator2.Set(255.0); counter++; //just for debuging purposes,, will be removed } else iterator2.Set(0.0); ++iterator1; ++iterator2; } //Let's try this (for debugging): save the binary mask /* typedef itk::Image< unsigned short, 3 > OutputImageType; typedef itk::CastImageFilter< DistImageType, OutputImageType > CastType; CastType::Pointer cast = CastType::New(); cast->SetInput( subSegImg ); cast->Update(); typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New( ); writer->SetInput( cast->GetOutput() ); writer->SetFileName( "c:/bin_mask.tif" ); writer->Update(); */ //Compute the distance transform in the sub-segmentation image region DTFilter::Pointer dt_obj= DTFilter::New() ; dt_obj->SetInput(subSegImg) ; //dt_obj->SetInsideValue(255.0); //dt_obj->SetOutsideValue(0.0); try{ dt_obj->Update() ; } catch( itk::ExceptionObject & err ){ std::cout << "Error in Distance Transform: " << err << std::endl; return 0; } //Let's try this (for debugging): save the distance map ////typedef itk::Image< unsigned short, 3 > OutputImageType; ////typedef itk::CastImageFilter< DistImageType, OutputImageType > CastType; ////CastType::Pointer cast = CastType::New(); //cast->SetInput( dt_obj->GetOutput() ); //cast->Update(); ////typedef itk::ImageFileWriter< OutputImageType > WriterType; ////WriterType::Pointer writer = WriterType::New( ); //writer->SetInput( cast->GetOutput() ); //writer->SetFileName( "c:/dist_map.tif" ); //writer->Update(); //now, mask out all the pixels (in the sub-seg image) that are not in the region of interest as defined by the association rule and get the intensities of the needed pixels from the target image. The intensities are saved into an std vector IteratorType2 iterator3(dt_obj->GetOutput(), dt_obj->GetOutput()->GetRequestedRegion()); IteratorType iterator4(trgIm, trgIm->GetRequestedRegion()); std::vector<int> trgInt; int counter_in = 0; int counter_at = 0; int counter_ot = 0; while ( ! iterator3.IsAtEnd()) { int V = (int)iterator3.Get(); if(V<0) counter_in++; if(V==0) counter_at++; if(V>0) counter_ot++; //if it is outside with distance less than outDistance away if(V>0 && V<=assocRulesList[ruleID].GetOutDistance()) trgInt.push_back(iterator4.Get()); //if it is inside and the whole cell is used else if(V<=0 && assocRulesList[ruleID].IsUseWholeObject()) trgInt.push_back(iterator4.Get()); //if it is inside with distance less than in Distance else if(V<=0 && abs(V)<=assocRulesList[ruleID].GetInDistance()) trgInt.push_back(iterator4.Get()); ++iterator3; ++iterator4; } if(!trgInt.size()) return 0; //Finally, given the list of intensities compute the associative measrement based on the type defined by the association rule switch(assocRulesList[ruleID].GetAssocType()) { case ASSOC_MIN: return FindMin(trgInt); break; case ASSOC_MAX: return FindMax(trgInt); break; case ASSOC_TOTAL: return ComputeTotal(trgInt); break; case ASSOC_AVERAGE: return ComputeAverage(trgInt); break; default: return ComputeAverage(trgInt); } //we will never go here, just silencing a compiler warning return 0.0; }
bool NestLoopExecutor::p_execute(const NValueArray ¶ms, ReadWriteTracker *tracker) { VOLT_DEBUG("executing NestLoop..."); NestLoopPlanNode* node = dynamic_cast<NestLoopPlanNode*>(abstract_node); assert(node); assert(node->getInputTables().size() == 2); Table* output_table_ptr = node->getOutputTable(); assert(output_table_ptr); // output table must be a temp table TempTable* output_table = dynamic_cast<TempTable*>(output_table_ptr); assert(output_table); Table* outer_table = node->getInputTables()[0]; assert(outer_table); Table* inner_table = node->getInputTables()[1]; assert(inner_table); VOLT_TRACE ("input table left:\n %s", outer_table->debug().c_str()); VOLT_TRACE ("input table right:\n %s", inner_table->debug().c_str()); // // Join Expression // AbstractExpression *predicate = node->getPredicate(); if (predicate) { predicate->substitute(params); VOLT_TRACE ("predicate: %s", predicate == NULL ? "NULL" : predicate->debug(true).c_str()); } int outer_cols = outer_table->columnCount(); int inner_cols = inner_table->columnCount(); TableTuple outer_tuple(node->getInputTables()[0]->schema()); TableTuple inner_tuple(node->getInputTables()[1]->schema()); TableTuple &joined = output_table->tempTuple(); TableIterator iterator0(outer_table); while (iterator0.next(outer_tuple)) { // populate output table's temp tuple with outer table's values // probably have to do this at least once - avoid doing it many // times per outer tuple for (int col_ctr = 0; col_ctr < outer_cols; col_ctr++) { joined.setNValue(col_ctr, outer_tuple.getNValue(col_ctr)); } TableIterator iterator1(inner_table); while (iterator1.next(inner_tuple)) { if (predicate == NULL || predicate->eval(&outer_tuple, &inner_tuple).isTrue()) { // Matched! Complete the joined tuple with the inner column values. for (int col_ctr = 0; col_ctr < inner_cols; col_ctr++) { joined.setNValue(col_ctr + outer_cols, inner_tuple.getNValue(col_ctr)); } output_table->insertTupleNonVirtual(joined); } } } return (true); }
// Determine if the intersection of three reference lists is empty. // - this (which we will refer as refList0), refList1 and reflist2. NABoolean MdamRefList::intersectEmpty(const MdamRefList & refList1, const MdamRefList & refList2) { // For readability purpose, let's refer to this pointer as reflist0. MdamRefList *refList0 = this; // Obtain the first disjunct number from each list. Int32 disjunctNum0 = disjunctNumInitialValue; Int32 disjunctNum1 = disjunctNumInitialValue; Int32 disjunctNum2 = disjunctNumInitialValue; MdamRefListIterator iterator0(refList0); MdamRefListIterator iterator1(&refList1); MdamRefListIterator iterator2(&refList2); NABoolean more0 = iterator0(disjunctNum0); NABoolean more1 = iterator1(disjunctNum1); NABoolean more2 = iterator2(disjunctNum2); // Iterate finding disjunct numbers common to all three lists. // Stop when one is found or when one of the refLists is exhausted. while (more0 && more1 && more2) { if (disjunctNum0 == disjunctNum1) { if (disjunctNum0 == disjunctNum2) return FALSE; // Found a match in refList0 refList1 and refList2! // intersection is non-empty. else if (disjunctNum0 < disjunctNum2) { // We already know disjunctNum0=disjunctNum1. // Advance both refList0 and refList1. more0 = iterator0(disjunctNum0); more1 = iterator1(disjunctNum1); } else { // Must be disjunctNum2<disjunctNum0 and // disjunctNum2<disjunctNum1 more2 = iterator2(disjunctNum2); } } else if (disjunctNum0 < disjunctNum1) { if (disjunctNum0 < disjunctNum2) { // Disjunct number from list 0 is less than 1 and 2. // Advance list 0. more0 = iterator0(disjunctNum0); } else { // We know disjunctNum2 <= disjunctNum0 < disjunctNum1 more0 = iterator0(disjunctNum0); more2 = iterator2(disjunctNum2); } } else // (disjunctNum1 < disjunctNum0) { if (disjunctNum1 < disjunctNum2) { // Disjunct number from list 1 is less than from 0 and 2. // Advance list 1. more1 = iterator1(disjunctNum1); } else { // We know that disjunctNum2 <= disjunctNum1 < disjunctNum0 more1 = iterator1(disjunctNum1); more2 = iterator2(disjunctNum2); } } }//While return TRUE; // Return true because the intersection is empty. }
// //########################################################################### // RunTest //########################################################################### // bool TreeTestNode::RunTest() { TreeTestPlug *testPlug1, *testPlug2; int values[TEST_COUNT]; int i, j; // Time startTicks; /* * Generate unique values, shuffle them */ for (i = 0; i < TEST_COUNT; i++) { values[i] = i; } for (i = 0; i < TEST_COUNT; i++) { int tmp; j = i + Random::GetLessThan(TEST_COUNT - i); tmp = values[j]; values[j] = values[i]; values[i] = tmp; } // //-------------------------------------------------------------------- // Stress tests //-------------------------------------------------------------------- // /* * Create plugs and add to both sockets */ for (i = 0; i < TEST_COUNT; i++) { testPlug1 = new TreeTestPlug(values[i]); Register_Object(testPlug1); tree1.AddValue(testPlug1, values[i]); tree2.AddValue(testPlug1, values[i]); } TestOrder(); /* * Find */ { for (i = 0; i < TEST_COUNT; i++) { testPlug1 = tree1.Find(i); testPlug2 = tree2.Find(i); Test_Assumption( testPlug1->value == i ); Test_Assumption( testPlug2->value == i ); Test_Assumption( testPlug1 == testPlug2 ); } } /* * Test_Assumption first and last */ { TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); iterator1.First(); iterator2.First(); testPlug1 = iterator1.GetCurrent(); testPlug2 = iterator2.GetCurrent(); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1 == iterator1.GetNth(0) ); Test_Assumption( testPlug1 == iterator2.GetNth(0) ); } /* * Test_Assumption next and prev */ { TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while ((testPlug1 = iterator1.GetCurrent()) != NULL) { testPlug2 = iterator2.GetCurrent(); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1->value == i ); Test_Assumption( testPlug2->value == i ); iterator1.Next(); iterator2.Next(); i++; } Test_Assumption( i == TEST_COUNT ); } /* * Test_Assumption read next and read prev */ { TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while ((testPlug1 = iterator1.ReadAndNext()) != NULL) { testPlug2 = iterator2.ReadAndNext(); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1->value == i ); Test_Assumption( testPlug2->value == i ); i++; } Test_Assumption( i == TEST_COUNT ); } /* * Test_Assumption nth */ { TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); for (i = 0; i < TEST_COUNT; i++) { testPlug1 = iterator1.GetNth(i); testPlug2 = iterator2.GetNth(i); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1->value == i ); Test_Assumption( testPlug2->value == i ); } } /* * Test_Assumption Remove */ { TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while ((testPlug1 = iterator1.GetCurrent()) != NULL) { Test_Assumption( testPlug1->value == i ); iterator1.Remove(); testPlug2 = iterator2.GetNth(0); Test_Assumption( testPlug2->value == i ); Test_Assumption( testPlug1 == testPlug2 ); Unregister_Object(testPlug2); delete testPlug2; i++; TestOrder(); } Test_Assumption( i == TEST_COUNT ); Test_Assumption( iterator1.GetSize() == 0 ); Test_Assumption( iterator2.GetSize() == 0 ); } /* * Test_Assumption random deletion */ /* * Add plugs to both sockets */ { TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); Test_Assumption( iterator1.GetSize() == 0 ); Test_Assumption( iterator2.GetSize() == 0 ); for (i = 0; i < TEST_COUNT; i++) { testPlug1 = new TreeTestPlug(values[i]); Register_Object( testPlug1 ); tree1.AddValue(testPlug1, values[i]); tree2.AddValue(testPlug1, values[i]); TestOrder(); } TestOrder(); } /* * Perform random deletion */ { int size, index; TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while((size = iterator1.GetSize()) != 0) { index = Random::GetLessThan(size); testPlug1 = iterator1.GetNth(index); iterator1.Remove(); testPlug2 = iterator2.GetNth(index); Test_Assumption( testPlug1 == testPlug2 ); Unregister_Object( testPlug2 ); delete(testPlug2); i++; TestOrder(); } Test_Assumption( i == TEST_COUNT ); Test_Assumption( iterator1.GetSize() == 0 ); Test_Assumption( iterator2.GetSize() == 0 ); } return true; }
// //########################################################################### // RunProfile //########################################################################### // bool TreeTestNode::RunProfile() { TreeTestPlug *testPlug1, *testPlug2; int values[TEST_COUNT]; int i, j; Time startTicks; /* * Generate unique values, shuffle them */ for (i = 0; i < TEST_COUNT; i++) { values[i] = i; } for (i = 0; i < TEST_COUNT; i++) { int tmp; j = i + Random::GetLessThan(TEST_COUNT - i); tmp = values[j]; values[j] = values[i]; values[i] = tmp; } // //-------------------------------------------------------------------- // Run timing tests //-------------------------------------------------------------------- // /* * Create plugs and add to both sockets */ startTicks = gos_GetHiResTime(); for (i = 0; i < TEST_COUNT; i++) { testPlug1 = new TreeTestPlug(values[i]); Register_Object( testPlug1 ); tree1.AddValue(testPlug1, values[i]); tree2.AddValue(testPlug1, values[i]); } SPEW(( GROUP_STUFF_TEST, "TreeTestNode::RunTest Create = %f", gos_GetHiResTime() - startTicks )); /* * Iterate over both sockets */ startTicks = gos_GetHiResTime(); { TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while ((testPlug1 = iterator1.ReadAndNext()) != NULL) { Test_Assumption( testPlug1->value == i ); i++; } Test_Assumption( i == TEST_COUNT ); i = 0; while ((testPlug1 = iterator2.ReadAndNext()) != NULL) { Test_Assumption( testPlug1->value == i ); i++; } Test_Assumption( i == TEST_COUNT ); } SPEW(( GROUP_STUFF_TEST, "TreeTestNode::RunTest Iterate = %f", gos_GetHiResTime() - startTicks )); /* * Find */ startTicks = gos_GetHiResTime(); { TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); for (i = 0; i < TEST_COUNT; i++) { testPlug1 = iterator1.Find(i); testPlug2 = iterator2.Find(i); Test_Assumption( testPlug1->value == i ); Test_Assumption( testPlug2->value == i ); Test_Assumption( testPlug1 == testPlug2 ); } } SPEW(( GROUP_STUFF_TEST, "TreeTestNode::RunTest Find = %f", gos_GetHiResTime() - startTicks )); /* * Destroy from tree1, verify with tree2 */ startTicks = gos_GetHiResTime(); { TreeIteratorOf<TreeTestPlug*, int> iterator1(&tree1); TreeIteratorOf<TreeTestPlug*, int> iterator2(&tree2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while ((testPlug1 = iterator1.ReadAndNext()) != NULL) { Test_Assumption( testPlug1->value == i ); i++; Unregister_Object(testPlug1); delete(testPlug1); } Test_Assumption( i == TEST_COUNT ); Test_Assumption( iterator1.GetSize() == 0 ); Test_Assumption( iterator2.GetSize() == 0 ); } SPEW(( GROUP_STUFF_TEST, "TreeTestNode::RunTest Destroy = %f", gos_GetHiResTime() - startTicks )); return true; }
bool SafeChainTestNode::RunProfile() { SafeChainTestPlug *testPlug1; int i; Time startTicks; // //-------------------------------------------------------------------- // Run timing tests //-------------------------------------------------------------------- // /* * Create plugs and add to both sockets */ startTicks = gos_GetHiResTime(); for (i = 0; i < TEST_COUNT; i++) { testPlug1 = new SafeChainTestPlug(i); Register_Object( testPlug1 ); chain1.Add(testPlug1); chain2.Add(testPlug1); } SPEW(( GROUP_STUFF_TEST, "SafeChainTestNode::RunTest Create = %f", gos_GetHiResTime() - startTicks )); /* * Iterate over both sockets */ startTicks = gos_GetHiResTime(); { SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); SafeChainIteratorOf<SafeChainTestPlug*> iterator2(&chain2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while ((testPlug1 = iterator1.ReadAndNext()) != NULL) { Test_Assumption( testPlug1->value == i ); i++; } Test_Assumption( i == TEST_COUNT ); i = 0; while ((testPlug1 = iterator2.ReadAndNext()) != NULL) { Test_Assumption( testPlug1->value == i ); i++; } Test_Assumption( i == TEST_COUNT ); } SPEW(( GROUP_STUFF_TEST, "SafeChainTestNode::RunTest Iterate = %f", gos_GetHiResTime() - startTicks )); /* * Destroy from chain1, verify with chain2 */ startTicks = gos_GetHiResTime(); { SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); SafeChainIteratorOf<SafeChainTestPlug*> iterator2(&chain2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while ((testPlug1 = iterator1.ReadAndNext()) != NULL) { Test_Assumption( testPlug1->value == i ); i++; Unregister_Object( testPlug1 ); delete(testPlug1); } Test_Assumption( i == TEST_COUNT ); Test_Assumption( iterator1.GetSize() == 0 ); Test_Assumption( iterator2.GetSize() == 0 ); } SPEW(( GROUP_STUFF_TEST, "SafeChainTestNode::RunTest Destroy = %f", gos_GetHiResTime() - startTicks )); return true; }
bool SafeChainTestNode::RunTest() { SafeChainTestPlug *testPlug1, *testPlug2; int i, j; // Time startTicks; // //-------------------------------------------------------------------- // Stress tests //-------------------------------------------------------------------- // /* * Create plugs and add to both sockets */ for (i = 0; i < TEST_COUNT; i++) { testPlug1 = new SafeChainTestPlug(i); Register_Object( testPlug1 ); chain1.Add(testPlug1); chain2.Add(testPlug1); } /* * Test_Assumption first and last */ { SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); SafeChainIteratorOf<SafeChainTestPlug*> iterator2(&chain2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); iterator1.First(); iterator2.First(); testPlug1 = iterator1.GetCurrent(); testPlug2 = iterator2.GetCurrent(); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1 == iterator1.GetNth(0) ); Test_Assumption( testPlug1 == iterator2.GetNth(0) ); iterator1.Last(); iterator2.Last(); testPlug1 = iterator1.GetCurrent(); testPlug2 = iterator2.GetCurrent(); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1 == iterator1.GetNth(TEST_COUNT - 1) ); Test_Assumption( testPlug1 == iterator2.GetNth(TEST_COUNT - 1) ); } /* * Test_Assumption next and prev */ { SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); SafeChainIteratorOf<SafeChainTestPlug*> iterator2(&chain2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while ((testPlug1 = iterator1.GetCurrent()) != NULL) { testPlug2 = iterator2.GetCurrent(); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1->value == i ); Test_Assumption( testPlug2->value == i ); iterator1.Next(); iterator2.Next(); i++; } Test_Assumption( i == TEST_COUNT ); iterator1.Last(); iterator2.Last(); i = TEST_COUNT - 1; while ((testPlug1 = iterator1.GetCurrent()) != NULL) { testPlug2 = iterator2.GetCurrent(); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1->value == i ); Test_Assumption( testPlug2->value == i ); iterator1.Previous(); iterator2.Previous(); i--; } Test_Assumption( i == -1 ); } /* * Test_Assumption read next and read prev */ { SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); SafeChainIteratorOf<SafeChainTestPlug*> iterator2(&chain2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while ((testPlug1 = iterator1.ReadAndNext()) != NULL) { testPlug2 = iterator2.ReadAndNext(); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1->value == i ); Test_Assumption( testPlug2->value == i ); i++; } Test_Assumption( i == TEST_COUNT ); iterator1.Last(); iterator2.Last(); i = TEST_COUNT - 1; while ((testPlug1 = iterator1.ReadAndPrevious()) != NULL) { testPlug2 = iterator2.ReadAndPrevious(); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1->value == i ); Test_Assumption( testPlug2->value == i ); i--; } Test_Assumption( i == -1 ); } /* * Test_Assumption nth */ { SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); SafeChainIteratorOf<SafeChainTestPlug*> iterator2(&chain2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); for (i = 0; i < TEST_COUNT; i++) { testPlug1 = iterator1.GetNth(i); testPlug2 = iterator2.GetNth(i); Test_Assumption( testPlug1 == testPlug2 ); Test_Assumption( testPlug1->value == i ); Test_Assumption( testPlug2->value == i ); } } /* * Test_Assumption Remove */ { SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); SafeChainIteratorOf<SafeChainTestPlug*> iterator2(&chain2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while ((testPlug1 = iterator1.GetCurrent()) != NULL) { Test_Assumption( testPlug1->value == i ); iterator1.Remove(); testPlug2 = iterator2.GetNth(0); Test_Assumption( testPlug2->value == i ); Test_Assumption( testPlug1 == testPlug2 ); Unregister_Object( testPlug2 ); delete(testPlug2); i++; } Test_Assumption( i == TEST_COUNT ); Test_Assumption( iterator1.GetSize() == 0 ); Test_Assumption( iterator2.GetSize() == 0 ); } /* * Test_Assumption random deletion */ { /* * Add plugs to both sockets */ SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); SafeChainIteratorOf<SafeChainTestPlug*> iterator2(&chain2); Test_Assumption( iterator1.GetSize() == 0 ); Test_Assumption( iterator2.GetSize() == 0 ); for (i = 0; i < TEST_COUNT; i++) { testPlug1 = new SafeChainTestPlug(i); Register_Object( testPlug1 ); chain1.Add(testPlug1); chain2.Add(testPlug1); } } { /* * Perform random deletion */ int size, index; SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); SafeChainIteratorOf<SafeChainTestPlug*> iterator2(&chain2); Test_Assumption( iterator1.GetSize() == TEST_COUNT ); Test_Assumption( iterator2.GetSize() == TEST_COUNT ); i = 0; while((size = iterator1.GetSize()) != 0) { index = Random::GetLessThan(size); testPlug1 = iterator1.GetNth(index); iterator1.Remove(); testPlug2 = iterator2.GetNth(index); Test_Assumption( testPlug1 == testPlug2 ); Unregister_Object( testPlug2 ); delete(testPlug2); i++; } Test_Assumption( i == TEST_COUNT ); Test_Assumption( iterator1.GetSize() == 0 ); Test_Assumption( iterator2.GetSize() == 0 ); } /* * Test_Assumption insertion */ { SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); Test_Assumption(iterator1.GetSize() == 0); for (i = 0; i < TEST_COUNT; i++) { testPlug1 = new SafeChainTestPlug(i); Register_Object(testPlug1); if (i == 0) { chain1.Add(testPlug1); } else { iterator1.First(); iterator1.Insert(testPlug1); } } for (i = 0, j = TEST_COUNT-1; i < TEST_COUNT; i++, j--) { testPlug1 = iterator1.GetNth(i); Test_Assumption(testPlug1->value == j); } iterator1.DeletePlugs(); } { SafeChainIteratorOf<SafeChainTestPlug*> iterator1(&chain1); Test_Assumption(iterator1.GetSize() == 0); for (i = 0; i < TEST_COUNT; i++) { testPlug1 = new SafeChainTestPlug(i); Register_Object(testPlug1); if (i == 0) { chain1.Add(testPlug1); } else { iterator1.Last(); iterator1.Insert(testPlug1); } } for (i = 0; i < TEST_COUNT; i++) { testPlug1 = iterator1.GetNth(i); if (i == TEST_COUNT-1) { Test_Assumption(testPlug1->value == 0); } else { Test_Assumption(testPlug1->value == i+1); } } iterator1.DeletePlugs(); } return true; }
void Graph::drawCurves(QPainter *painter) { QRect rect(Margin, Margin, width() - 2 * Margin, height() - 2 * Margin); if(!rect.isValid()) return; painter->setClipRect(rect.adjusted(+1, +1, -1, -1)); QPolygon polyline0, polyline1; QVectorIterator<QPoint> iterator0(pointStorage_0); while(iterator0.hasNext()){ QPoint point = iterator0.next(); int x = rect.left() + point.x(); int y = rect.bottom() - point.y(); polyline0 << QPoint(x, y); } QVectorIterator<QPoint> iterator1(pointStorage_1); while(iterator1.hasNext()){ QPoint point = iterator1.next(); int x = rect.left() + point.x(); int y = rect.bottom() - point.y(); polyline1 << QPoint(x, y); } QPen light = palette().light().color(); QPen bright(Qt::green, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); int static xyz = 0; int value0, value1; if(!polyline0.isEmpty()){ value0 = polyline0.last().y(); } if(!polyline1.isEmpty()){ value1 = polyline1.last().y(); } painter->setPen(light); painter->drawPolyline(polyline0); painter->drawText(rect, Qt::AlignCenter, QString::number(value0)); painter->setPen(bright); painter->drawPolyline(polyline1); painter->drawText(rect, Qt::AlignVCenter, QString::number(value1)); painter->setPen(light); painter->drawLine(rect.left() + xyz, rect.left() + 50, rect.left() + xyz, rect.left() + 15); painter->drawRect(rect.adjusted(0, 0, -1, -1)); xyz++; }
int main(int argc, char* argv[]) { //if(argc < 5){ // std::cout<<"Usage1: darpa_tracer <Global_Centroids_List> <DAPI_Montage_File> <GFP_Montage_File> <Seg_Params_File> \n"; // return 0; //} //Input: Somas_file, nucleus_montage, trace_channel_montage, nuc_seg_parameters //std::fstream soma_centroid_file; //soma_centroid_file.open(argv[1], std::fstream::in); //std::vector<centroids> centroid_list; //while (soma_centroid_file.good()){ // centroids new_centroid; // soma_centroid_file >> new_centroid.x_d >> new_centroid.y_d >> new_centroid.z_d; // centroid_list.push_back( new_centroid ); //} //soma_centroid_file.close(); std::vector< itk::Index<3> > centroid_list; std::vector< itk::Index<3> > all_centroid_list; //vtkSmartPointer<vtkTable> global_centroids = ftk::LoadTable(argv[1]); vtkSmartPointer<vtkTable> global_centroids = ftk::LoadTable("D:\\11_10_selective_tracing\\Global_centroids.txt"); for(int r=0; r<(int)global_centroids->GetNumberOfRows(); ++r) { int cx = global_centroids->GetValue(r, 0).ToInt(); int cy = global_centroids->GetValue(r, 1).ToInt(); int cz = global_centroids->GetValue(r, 2).ToInt(); itk::Index<3> all_cen; all_cen[0] = cx; all_cen[1] = cy; all_cen[2] = cz; all_centroid_list.push_back(all_cen); if( (fmod((double)cx,1050)>1000) || (fmod((double)cx,1050)<50) || (fmod((double)cy,1050)>1000) || (fmod((double)cy,1050)<50)) { itk::Index<3> cen; cen[0] = cx; cen[1] = cy; cen[2] = cz; centroid_list.push_back(cen); } } std::cout << "Number of cells to be retraced : " << centroid_list.size() << "\n"; typedef itk::ImageFileReader<nucImageType> nucReaderType; typedef itk::ImageFileReader<gfpImageType> gfpReaderType; //nucReaderType::Pointer reader_nuc = nucReaderType::New(); //reader_nuc->SetFileName(argv[2]); //reader_nuc->Update(); //nucImageType::Pointer img_nuc = reader_nuc->GetOutput(); //gfpReaderType::Pointer reader_trace = gfpReaderType::New(); //reader_trace->SetFileName(argv[3]); //reader_trace->Update(); //gfpImageType::Pointer img_trace = reader_trace->GetOutput(); //uint64_t size_trace[3],size_nuc[3]; //size_nuc[0] = img_nuc->GetLargestPossibleRegion().GetSize()[0]; //size_nuc[1] = img_nuc->GetLargestPossibleRegion().GetSize()[1]; //size_nuc[2] = img_nuc->GetLargestPossibleRegion().GetSize()[2]; //size_trace[0] = img_trace->GetLargestPossibleRegion().GetSize()[0]; //size_trace[1] = img_trace->GetLargestPossibleRegion().GetSize()[1]; //size_trace[2] = img_trace->GetLargestPossibleRegion().GetSize()[2]; //if( size_trace[0]!=size_nuc[0] || size_trace[1]!=size_nuc[1] || size_trace[2]!=size_nuc[2] ) return EXIT_FAILURE; // //long int a=0; // //while( a<centroid_list.size() ){ // #pragma omp parallel for num_threads(12) // for( long int a=0; a<centroid_list.size(); ++a ){ // //for( long int a=0; a<5; ++a ){ // int x, y, z; // x = centroid_list[a][0]; // y = centroid_list[a][1]; // z = centroid_list[a][2]; // // nucImageType::IndexType start; // start[0] = ((x - 200)>0) ? (x - 200):0; // start[1] = ((y - 200)>0) ? (y - 200):0; // start[2] = ((z - 100) >0) ? (z - 100) :0; // // gfpImageType::IndexType start2; // start2[0] = ((x - 200)>0) ? (x - 200):0; // start2[1] = ((y - 200)>0) ? (y - 200):0; // start2[2] = ((z - 100) >0) ? (z - 100) :0; // // nucImageType::SizeType size; // size[0] = ((x+200)<size_nuc[0]) ? 400 : (200+size_trace[0]-x-1); // size[1] = ((y+200)<size_nuc[1]) ? 400 : (200+size_trace[1]-y-1); // size[2] = ((z+100)<size_nuc[2]) ? 200 : (100+size_trace[2]-z-1); // // gfpImageType::SizeType size2; // size2[0] = ((x+200)<size_trace[0]) ? 400 : (200+size_trace[0]-x-1); // size2[1] = ((y+200)<size_trace[1]) ? 400 : (200+size_trace[1]-y-1); // size2[2] = ((z+100)<size_trace[2]) ? 200 : (100+size_trace[2]-z-1); // // std::ostringstream output_filename_stream; // // nucImageType::RegionType desiredRegion; // desiredRegion.SetSize(size); // desiredRegion.SetIndex(start); // // gfpImageType::RegionType desiredRegion2; // desiredRegion2.SetSize(size2); // desiredRegion2.SetIndex(start2); // // typedef itk::RegionOfInterestImageFilter< nucImageType, nucImageType > ROIFilterType; // typedef itk::RegionOfInterestImageFilter< gfpImageType, gfpImageType > ROIFilterType2; // ROIFilterType::Pointer ROIfilter = ROIFilterType::New(); // ROIfilter->SetRegionOfInterest(desiredRegion); // ROIfilter->SetInput(img_nuc); // ROIfilter->Update(); // nucImageType::Pointer img = ROIfilter->GetOutput(); // // ROIFilterType2::Pointer ROIfilter2 = ROIFilterType2::New(); // ROIfilter2->SetRegionOfInterest(desiredRegion2); // ROIfilter2->SetInput(img_trace); // ROIfilter2->Update(); // gfpImageType::Pointer img_tr = ROIfilter2->GetOutput(); // // //itk::CastImageFilter<gfpImageType, nucImageType>::Pointer caster = itk::CastImageFilter<gfpImageType, nucImageType>::New(); // //caster->SetInput(img_tr); // //itk::ImageFileWriter<nucImageType>::Pointer writer2 = itk::ImageFileWriter<nucImageType>::New(); // itk::ImageFileWriter<gfpImageType>::Pointer writer2 = itk::ImageFileWriter<gfpImageType>::New(); // std::stringstream ss; // ss << "gfp_image" << x << "_" << y << "_" << z << ".mhd"; // std::string file_output; // file_output = ss.str(); // writer2->SetFileName(file_output.c_str()); // writer2->SetInput(img_tr); // writer2->Update(); // // //Run Nucleus Segmentation // clock_t startTimer = clock(); // std::cout<<"Starting segmentation\n"; // unsigned char *in_Image; // in_Image = (unsigned char *) malloc (size[0]*size[1]*size[2]); // if( in_Image == NULL ){ // std::cerr<<"Nucleus Seg failed because malloc failed\n"; // continue; // } // memset(in_Image/*destination*/,0/*value*/,size[0]*size[1]*size[2]*sizeof(unsigned char)/*num bytes to move*/); // typedef itk::ImageRegionConstIterator< nucImageType > ConstIteratorType; // ConstIteratorType pix_buf( img, img->GetRequestedRegion() ); // uint64_t ind=0; // for ( pix_buf.GoToBegin(); !pix_buf.IsAtEnd(); ++pix_buf, ++ind ) // in_Image[ind]=(pix_buf.Get()); // yousef_nucleus_seg *NucleusSeg = new yousef_nucleus_seg(); // NucleusSeg->readParametersFromFile(argv[4]); // NucleusSeg->setDataImage(in_Image,size[0],size[1],size[2],"/home/gramak/Desktop/11_10_tracing/montage_kt11306_w410DAPIdsu.mhd"); // NucleusSeg->runBinarization(); // try // { // std::cout<<"Starting seed detection\n"; // NucleusSeg->runSeedDetection(); // } // catch( bad_alloc & excp ) // { // std::cout<<"You have requested more memory than " // <<"what is currently available in this " // <<"system, please try again with a smaller " // <<"input image\n"; // } // catch( itk::ExceptionObject & excp ) // { // std::cout<<"Error: " << excp <<std::endl; // } // NucleusSeg->runClustering(); // unsigned short *output_img; ///* if(NucleusSeg->isSegmentationFinEnabled()) // { // NucleusSeg->runAlphaExpansion(); // output_img=NucleusSeg->getSegImage(); // } // else //*/ // output_img=NucleusSeg->getClustImage(); // std::cout<<"Done with nucleus segmentation for image "<<a<<std::endl; // // LabelType::Pointer image = LabelType::New(); // LabelType::PointType origin; // origin[0] = start[0]; //Is this OK? // origin[1] = start[1]; // origin[2] = start[2]; // image->SetOrigin( origin ); // LabelType::IndexType start1; // start1[0] = 0; // start1[1] = 0; // start1[2] = 0; // LabelType::SizeType size1; // size1[0] = size[0]; // size1[1] = size[1]; // size1[2] = size[2]; // LabelType::RegionType region; // region.SetSize ( size1 ); // region.SetIndex( start1 ); // image->SetRegions( region ); // image->Allocate(); // image->FillBuffer(0); // image->Update(); // // typedef itk::ImageRegionIteratorWithIndex< LabelType > IteratorType; // IteratorType iterator1(image,image->GetRequestedRegion()); // for(uint64_t i=0; i<(size[0]*size[1]*size[2]); ++i) // { // unsigned short val = (unsigned short)output_img[i]; // iterator1.Set(val); // ++iterator1; // } // // std::stringstream ss1; // ss1 << "soma_label"<< x << "_" << y << "_" << z << ".tif"; // std::string file_output1; // file_output1 = ss1.str(); // itk::ImageFileWriter<LabelType>::Pointer writer = itk::ImageFileWriter<LabelType>::New(); // writer->SetFileName(file_output1); // writer->SetInput(image); // writer->Update(); // delete NucleusSeg; // } long int a=0; int num_to_be_traced = centroid_list.size(); std::cout << "Deleting duplicated seeds.... \n"; while( a<centroid_list.size() ) { //Run Multiple Neuron Tracer int x, y, z; x = centroid_list[a][0]; y = centroid_list[a][1]; z = centroid_list[a][2]; if(x == -1) { ++a; continue; } itk::Index<3> centroid; centroid[0] = ((x - 200)>0) ? 200:x; centroid[1] = ((y - 200)>0) ? 200:y; centroid[2] = ((z - 100) >0) ? 100:z; std::stringstream ss1; ss1 << "D:\\11_10_selective_tracing\\soma_label"<< centroid_list.at(a)[0] << "_" << centroid_list.at(a)[1] << "_" << centroid_list.at(a)[2] << ".tif"; std::string file_output1; file_output1 = ss1.str(); itk::ImageFileReader<LabelType>::Pointer reader = itk::ImageFileReader<LabelType>::New(); reader->SetFileName(file_output1); reader->Update(); LabelType::Pointer image = reader->GetOutput(); std::cout << image->GetBufferedRegion().GetSize() << "\n"; typedef itk::ImageRegionIteratorWithIndex< LabelType > IteratorType; IteratorType iterator1(image,image->GetRequestedRegion()); std::vector< itk::Index<3> > soma_centroids; std::vector< itk::Index<3> > soma_centroids_to_be_del; std::vector<unsigned short> label_vec; std::vector<uint64_t> delete_index; for(uint64_t ctr =0; ctr<all_centroid_list.size() ; ++ctr) { itk::Index<3> cen = all_centroid_list[ctr]; if(cen[0] == -1) continue; if(abs((double)(cen[0]-x))<200 && abs((double)(cen[1]-y))<200 && abs((double)(cen[2]-z))<100 ) { bool centroid_not_found = true; itk::Index<3> centroid2; centroid2[0] = centroid[0] + cen[0] - x; centroid2[1] = centroid[1] + cen[1] - y; centroid2[2] = centroid[2] + cen[2] - z; LabelType::IndexType centroid_index; centroid_index[0] = centroid2[0]; centroid_index[1] = centroid2[1]; centroid_index[2] = centroid2[2]; iterator1.SetIndex( centroid_index ); unsigned short centroid_label = iterator1.Get(); for(int b=0; b<label_vec.size(); ++b) { if( label_vec.at(b)==centroid_label ) { centroid_not_found = false; break; } } if( centroid_not_found ) { label_vec.push_back( centroid_label ); soma_centroids.push_back( centroid2 ); } if( !centroid_not_found ) { delete_index.push_back( ctr ); soma_centroids_to_be_del.push_back( cen ); } } } if( delete_index.size() ) { std::sort(delete_index.begin(), delete_index.end(), myfunction); for( uint64_t b=0; b<delete_index.size(); ++b ) all_centroid_list[delete_index[b]].Fill(-1); delete_index.clear(); for( uint64_t b=0; b<soma_centroids_to_be_del.size(); ++b ) { itk::Index<3> centroid2 = soma_centroids_to_be_del.at(b); for( uint64_t c=0; c<centroid_list.size(); ++c ) { itk::Index<3> centroid3 = centroid_list.at(c); if( centroid2[0]==centroid3[0] && centroid2[1]==centroid3[1] && centroid2[2]==centroid3[2] ) { delete_index.push_back( c ); break; } } } std::sort(delete_index.begin(), delete_index.end(), myfunction); for( uint64_t b=0; b<delete_index.size(); ++b ) { centroid_list[delete_index[b]].Fill(-1); --num_to_be_traced; } std::cout<<"Number of cells to be retraced : "<<num_to_be_traced << " after "<<a<<" processed\n"; } ++a; } std::cout << "Deleting duplicated seeds done !! \n"; //std::ostringstream swc_filename_stream; //swc_filename_stream << vul_file::strip_extension(argv[3]) << "_" << x << "_" << y << "_" << z << "_ANT.swc"; //ofstream outFile; //outFile.open("D:\\11_10_selective_tracing\\append_to_swc.txt", ios::out | ios::trunc ); //if ( !outFile.is_open() ) //{ // std::cerr << "Failed to Load Document: " << outFile << std::endl; // return false; //} ////Write out the features: //for( a=0; a<centroid_list.size(); ++a ) //{ // int x, y, z; // x = centroid_list[a][0]; // y = centroid_list[a][1]; // z = centroid_list[a][2]; // if(x == -1) continue; // std::stringstream ssx, ssy, ssz; // ssx << x; ssy << y; ssz << z; // outFile << "_Trace_" + ssx.str() + "_" + ssy.str() + "_" + ssz.str() + "_ANT.swc\n"; //} //outFile.close(); #pragma omp parallel for num_threads(12) for( a=0; a<centroid_list.size(); ++a ) { int x, y, z; x = centroid_list[a][0]; y = centroid_list[a][1]; z = centroid_list[a][2]; if(x == -1) continue; std::cout<< "Tracing from seed point " << x << "_" << y << "_" << z << "\n"; itk::Index<3> centroid; centroid[0] = ((x - 200)>0) ? 200:x; centroid[1] = ((y - 200)>0) ? 200:y; centroid[2] = ((z - 100) >0) ? 100:z; std::stringstream ss1; ss1 << "D:\\11_10_selective_tracing\\soma_label"<< centroid_list.at(a)[0] << "_" << centroid_list.at(a)[1] << "_" << centroid_list.at(a)[2] << ".tif"; std::string file_output1; file_output1 = ss1.str(); itk::ImageFileReader<LabelType>::Pointer reader = itk::ImageFileReader<LabelType>::New(); reader->SetFileName(file_output1); reader->Update(); LabelType::Pointer image = reader->GetOutput(); itk::ImageFileReader<gfpImageType>::Pointer reader2 = itk::ImageFileReader<gfpImageType>::New(); std::stringstream ss; ss << "D:\\11_10_selective_tracing\\gfp_image" << x << "_" << y << "_" << z << ".mhd"; std::string file_output; file_output = ss.str(); reader2->SetFileName(file_output.c_str()); reader2->Update(); gfpImageType::Pointer img_tr = reader2->GetOutput(); std::vector< itk::Index<3> > soma_centroids; for(int ctr =0; ctr<all_centroid_list.size() ; ++ctr) { itk::Index<3> cen = all_centroid_list[ctr]; if(cen[0] == -1) continue; if(abs((double)(cen[0]-x))<=200 && abs((double)(cen[1]-y))<=200 && abs((double)(cen[2]-z))<=100 ) { itk::Index<3> centroid2; centroid2[0] = centroid[0] + cen[0] - x; //Is there a reason why x and y are flipped? centroid2[1] = centroid[1] + cen[1] - y; centroid2[2] = centroid[2] + cen[2] - z; soma_centroids.push_back(centroid2); } } MultipleNeuronTracer * MNT = new MultipleNeuronTracer(); MNT->LoadCurvImage_1(img_tr, 1); MNT->ReadStartPoints_1(soma_centroids, 1); MNT->SetCostThreshold(600); MNT->LoadSomaImage_1(image); MNT->RunTracing(); /*MNT->WriteSWCFile(std::string(swc_filename_stream.str()), 1);*/ std::stringstream ssx, ssy, ssz; ssx << x; ssy << y; ssz << z; MNT->WriteSWCFile("D:\\11_10_selective_tracing\\_Trace_" + ssx.str() + "_" + ssy.str() + "_" + ssz.str() + "_ANT.swc", 1); delete MNT; } }
int runGrAnisDiff(unsigned char* imgIn, int r, int c, int z, int iter, int timeStep, int comductance) { //pixel types typedef unsigned char InputPixelType; typedef float OutputPixelType; typedef itk::Image< InputPixelType, 3 > InputImageType; typedef itk::Image< OutputPixelType, 3 > OutputImageType; //create an ITK image from the input image OutputImageType::Pointer im; im = OutputImageType::New(); OutputImageType::PointType origin; origin[0] = 0.; origin[1] = 0.; origin[2] = 0.; im->SetOrigin( origin ); OutputImageType::IndexType start; start[0] = 0; // first index on X start[1] = 0; // first index on Y start[2] = 0; // first index on Z OutputImageType::SizeType size; size[0] = c; // size along X size[1] = r; // size along Y size[2] = z; // size along Z OutputImageType::RegionType region; region.SetSize( size ); region.SetIndex( start ); // double spacing[3]; //spacing[0] = 1; //spacing along x //spacing[1] = 1; //spacing along y //spacing[2] = sampl_ratio; //spacing along z im->SetRegions( region ); //im->SetSpacing(spacing); im->Allocate(); im->FillBuffer(0); im->Update(); //copy the input image into the ITK image typedef itk::ImageRegionIteratorWithIndex< OutputImageType > IteratorType; IteratorType iterator1(im,im->GetRequestedRegion()); for(int i=0; i<r*c*z; i++) { iterator1.Set((float)imgIn[i]); ++iterator1; } //apply gradient anisotropic diffusion typedef itk::GradientAnisotropicDiffusionImageFilter< OutputImageType, OutputImageType > FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetInput( im ); filter->SetNumberOfIterations( iter ); filter->SetTimeStep( timeStep ); filter->SetConductanceParameter( comductance ); try { filter->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << err << std::endl; return 0; } typedef itk::RescaleIntensityImageFilter< OutputImageType, InputImageType > RescaleFilterType; RescaleFilterType::Pointer rescaler = RescaleFilterType::New(); rescaler->SetOutputMinimum( 0 ); rescaler->SetOutputMaximum( 255 ); rescaler->SetInput( filter->GetOutput() ); rescaler->Update(); //overwrite the input image for now in order to save space typedef itk::ImageRegionIteratorWithIndex< InputImageType > IteratorType2; IteratorType2 iterator2(rescaler->GetOutput(),rescaler->GetOutput()->GetRequestedRegion()); for(int i=0; i<r*c*z; i++) { imgIn[i] = iterator2.Get(); ++iterator2; } return 1; }
std::vector<float> compute_ec_features( USImageType::Pointer input_image, USImageType::Pointer inp_labeled, int number_of_rois, unsigned short thresh, int surr_dist, int inside_dist ){ std::vector< float > qfied_num; std::vector< USImageType::PixelType > labelsList; std::vector< double > quantified_numbers_cell; typedef itk::ExtractImageFilter< USImageType, UShortImageType > LabelExtractType; typedef itk::ImageRegionConstIterator< UShortImageType > ConstIteratorType; typedef itk::ImageRegionIteratorWithIndex< USImageType > IteratorType; typedef itk::SignedDanielssonDistanceMapImageFilter<FloatImageType, FloatImageType > DTFilter; typedef itk::ImageRegionIteratorWithIndex< FloatImageType > IteratorTypeFloat; typedef itk::LabelGeometryImageFilter< USImageType > GeometryFilterType; typedef GeometryFilterType::LabelIndicesType labelindicestype; itk::SizeValueType sz_x, sz_y, sz_z; sz_x = input_image->GetLargestPossibleRegion().GetSize()[0]; sz_y = input_image->GetLargestPossibleRegion().GetSize()[1]; sz_z = input_image->GetLargestPossibleRegion().GetSize()[2]; if( sz_x==1 || sz_y==1 || sz_z==1 ){ LabelExtractType::Pointer deFilter = LabelExtractType::New(); USImageType::RegionType dRegion = inp_labeled->GetLargestPossibleRegion(); dRegion.SetSize(2,0); deFilter->SetExtractionRegion(dRegion); deFilter->SetInput( inp_labeled ); deFilter->SetDirectionCollapseToIdentity(); try{ deFilter->Update(); } catch( itk::ExceptionObject & excep ){ std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } //Dialate input first WholeCellSeg *dialate_filter = new WholeCellSeg; dialate_filter->set_nuc_img( deFilter->GetOutput() ); dialate_filter->set_radius( surr_dist ); dialate_filter->RunSegmentation(); UShortImageType::Pointer input_lab = dialate_filter->getSegPointer(); USImageType::Pointer input_labeled = USImageType::New(); USImageType::PointType origint; origint[0] = 0; origint[1] = 0; origint[2] = 0; input_labeled->SetOrigin( origint ); USImageType::IndexType startt; startt[0] = 0; // first index on X startt[1] = 0; // first index on Y startt[2] = 0; // first index on Z USImageType::SizeType sizet; sizet[0] = inp_labeled->GetLargestPossibleRegion().GetSize()[0]; // size along X sizet[1] = inp_labeled->GetLargestPossibleRegion().GetSize()[1]; // size along Y sizet[2] = inp_labeled->GetLargestPossibleRegion().GetSize()[2]; // size along Z USImageType::RegionType regiont; regiont.SetSize( sizet ); regiont.SetIndex( startt ); input_labeled->SetRegions( regiont ); input_labeled->Allocate(); input_labeled->FillBuffer(0); input_labeled->Update(); ConstIteratorType pix_buf1( input_lab, input_lab->GetRequestedRegion() ); IteratorType iterator2 ( input_labeled, input_labeled->GetRequestedRegion() ); iterator2.GoToBegin(); for ( pix_buf1.GoToBegin(); !pix_buf1.IsAtEnd(); ++pix_buf1 ){ iterator2.Set( pix_buf1.Get() ); ++iterator2; } std::vector< float > quantified_numbers; typedef itk::LabelGeometryImageFilter< USImageType > GeometryFilterType; typedef GeometryFilterType::LabelIndicesType labelindicestype; GeometryFilterType::Pointer geomfilt1 = GeometryFilterType::New(); geomfilt1->SetInput( input_labeled ); geomfilt1->SetCalculatePixelIndices( true ); geomfilt1->Update(); labelsList = geomfilt1->GetLabels(); bool zp=false; for( USImageType::PixelType i=0; i < labelsList.size(); ++i ){ if( labelsList[i] == 0 ){ zp=true; continue; } std::vector<float> quantified_numbers_cell; for( unsigned j=0; j<number_of_rois; ++j ) quantified_numbers_cell.push_back((float)0.0); double centroid_x = geomfilt1->GetCentroid(labelsList[i])[0]; double centroid_y = geomfilt1->GetCentroid(labelsList[i])[1]; labelindicestype indices1; indices1 = geomfilt1->GetPixelIndices(labelsList[i]); for( labelindicestype::iterator itPixind = indices1.begin(); itPixind!=indices1.end(); ++itPixind ){ IteratorType iterator1 ( input_image, input_image->GetRequestedRegion() ); iterator1.SetIndex( *itPixind ); if( iterator1.Get() < thresh ) continue; double x = iterator1.GetIndex()[0]; double y = iterator1.GetIndex()[1]; double angle = atan2((centroid_y-y),fabs(centroid_x-x)); if( (centroid_x-x)>0 ) angle += M_PI_2; else angle = M_PI+M_PI-(angle+M_PI_2); angle = ((number_of_rois-1)*angle)/(2*M_PI); double angle_fraction[1]; unsigned angular_index; if( modf( angle, angle_fraction ) > 0.5 ) angular_index = ceil( angle ); else angular_index = floor( angle ); quantified_numbers_cell[angular_index] += iterator1.Get(); } for( unsigned j=0; j<number_of_rois; ++j ) quantified_numbers.push_back(quantified_numbers_cell[j]); } unsigned qnum_sz = zp? (labelsList.size()-1) : (labelsList.size()); for( unsigned i=0; i<qnum_sz; ++i ){ unsigned counter=0; for( unsigned j=0; j<number_of_rois; ++j ){ if( quantified_numbers[(i*number_of_rois+j)] > (255.0*surr_dist) ) ++counter; } qfied_num.push_back(counter); } } else{ GeometryFilterType::Pointer geomfilt1 = GeometryFilterType::New(); geomfilt1->SetInput( inp_labeled ); geomfilt1->SetCalculatePixelIndices( true ); geomfilt1->Update(); labelsList = geomfilt1->GetLabels(); std::cout<<std::endl<<"The size is: "<<labelsList.size(); if( labelsList.size() == 1 ) { qfied_num.clear(); return qfied_num; } bool zp=false; USPixelType zero; //Check if the background is also included for( USPixelType i=0; i<labelsList.size(); ++i ) if( labelsList[i] == 0 ){ zp=true; zero = i; } USImageType::SizeType sizee; sizee[0] = inp_labeled->GetLargestPossibleRegion().GetSize()[0]; // size along X sizee[1] = inp_labeled->GetLargestPossibleRegion().GetSize()[1]; // size along Y sizee[2] = inp_labeled->GetLargestPossibleRegion().GetSize()[2]; // size along Z itk::SizeValueType roi_list_size = zp ? ((itk::SizeValueType)number_of_rois*(labelsList.size()-1)*2) : ((itk::SizeValueType)number_of_rois*labelsList.size()*2); std::vector<double> quantified_numbers_cell((roi_list_size),0.0 ); std::cout<<"Bounding boxes computed"<<std::endl; #ifdef _OPENMP itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1); #pragma omp parallel for #if _OPENMP < 200805L for( int i=0; i<labelsList.size(); ++i ) #else for( USImageType::PixelType i=0; i<labelsList.size(); ++i ) #endif #else for( USImageType::PixelType i=0; i<labelsList.size(); ++i ) #endif { itk::SizeValueType ind; if( zp && (zero==i) ) continue; if( zp && (i>zero) ) ind = i-1; else ind = i; //Get label indices labelindicestype indices1; double centroid_x,centroid_y,centroid_z; GeometryFilterType::BoundingBoxType boundbox; #pragma omp critical { indices1 = geomfilt1->GetPixelIndices(labelsList[i]); //Get Centroid centroid_x = geomfilt1->GetCentroid(labelsList[i])[0]; centroid_y = geomfilt1->GetCentroid(labelsList[i])[1]; centroid_z = geomfilt1->GetCentroid(labelsList[i])[2]; //Create an image with bounding box + 2 * outside distance + 2 //and get distance map for the label boundbox = geomfilt1->GetBoundingBox(labelsList[i]); } //Create vnl array 3xN( label indicies ) vnl_matrix<double> B(3,indices1.size()); FloatImageType::Pointer inp_lab = FloatImageType::New(); FloatImageType::PointType origint; origint[0] = 0; origint[1] = 0; origint[2] = 0; inp_lab->SetOrigin( origint ); FloatImageType::IndexType startt; startt[0] = 0; // first index on X startt[1] = 0; // first index on Y startt[2] = 0; // first index on Z FloatImageType::SizeType sizet; sizet[0] = boundbox[1]-boundbox[0]+2*surr_dist+2; // size along X sizet[1] = boundbox[3]-boundbox[2]+2*surr_dist+2; // size along Y sizet[2] = boundbox[5]-boundbox[4]+2*surr_dist+2; // size along Z FloatImageType::RegionType regiont; regiont.SetSize( sizet ); regiont.SetIndex( startt ); inp_lab->SetRegions( regiont ); inp_lab->Allocate(); inp_lab->FillBuffer(0.0); inp_lab->Update(); IteratorTypeFloat iterator444 ( inp_lab, inp_lab->GetRequestedRegion() ); //Populate matrix with deviations from the centroid for principal axes and //at the same time set up distance-transform computation itk::SizeValueType ind1=0; for( labelindicestype::iterator itPixind = indices1.begin(); itPixind!=indices1.end(); ++itPixind ){ IteratorType iterator3( input_image, input_image->GetRequestedRegion() ); iterator3.SetIndex( *itPixind ); B(0,(ind1)) = iterator3.GetIndex()[0]-centroid_x; B(1,(ind1)) = iterator3.GetIndex()[1]-centroid_y; B(2,(ind1)) = iterator3.GetIndex()[2]-centroid_z; FloatImageType::IndexType cur_in; cur_in[0] = iterator3.GetIndex()[0]-boundbox[0]+1+surr_dist; cur_in[1] = iterator3.GetIndex()[1]-boundbox[2]+1+surr_dist; cur_in[2] = iterator3.GetIndex()[2]-boundbox[4]+1+surr_dist; iterator444.SetIndex( cur_in ); iterator444.Set( 255.0 ); ++ind1; } //Compute distance transform for the current object DTFilter::Pointer dt_obj= DTFilter::New() ; dt_obj->SetInput( inp_lab ); dt_obj->SquaredDistanceOff(); dt_obj->InsideIsPositiveOff(); try{ dt_obj->Update() ; } catch( itk::ExceptionObject & err ){ std::cerr << "Error in Distance Transform: " << err << std::endl; } FloatImageType::Pointer dist_im = dt_obj->GetOutput(); //Use KLT to compute pricipal axes vnl_matrix<double> B_transp((int)indices1.size(),3); B_transp = B.transpose(); vnl_matrix<double> COV(3,3); COV = B * B_transp; double norm = 1.0/(double)indices1.size(); COV = COV * norm; //Eigen decomposition vnl_real_eigensystem Eyegun( COV ); vnl_matrix<vcl_complex<double> > EVals = Eyegun.D; double Eval1 = vnl_real(EVals)(0,0); double Eval2 = vnl_real(EVals)(1,1); double Eval3 = vnl_real(EVals)(2,2); vnl_double_3x3 EVectMat = Eyegun.Vreal; double V1[3],V2[3],EP_norm[3]; if( Eval1 >= Eval3 && Eval2 >= Eval3 ){ if( Eval1 >= Eval2 ){ V1[0] = EVectMat(0,0); V1[1] = EVectMat(1,0); V1[2] = EVectMat(2,0); V2[0] = EVectMat(0,1); V2[1] = EVectMat(1,1); V2[2] = EVectMat(2,1); } else { V2[0] = EVectMat(0,0); V2[1] = EVectMat(1,0); V2[2] = EVectMat(2,0); V1[0] = EVectMat(0,1); V1[1] = EVectMat(1,1); V1[2] = EVectMat(2,1); } } else if( Eval1 >= Eval2 && Eval3 >= Eval2 ) { if( Eval1 >= Eval3 ){ V1[0] = EVectMat(0,0); V1[1] = EVectMat(1,0); V1[2] = EVectMat(2,0); V2[0] = EVectMat(0,2); V2[1] = EVectMat(1,2); V2[2] = EVectMat(2,2); } else { V2[0] = EVectMat(0,0); V2[1] = EVectMat(1,0); V2[2] = EVectMat(2,0); V1[0] = EVectMat(0,2); V1[1] = EVectMat(1,2); V1[2] = EVectMat(2,2); } } else { if( Eval2 >= Eval3 ){ V1[0] = EVectMat(0,1); V1[1] = EVectMat(1,1); V1[2] = EVectMat(2,1); V2[0] = EVectMat(0,2); V2[1] = EVectMat(1,2); V2[2] = EVectMat(2,2); } else { V2[0] = EVectMat(0,1); V2[1] = EVectMat(1,1); V2[2] = EVectMat(2,1); V1[0] = EVectMat(0,2); V1[1] = EVectMat(1,2); V1[2] = EVectMat(2,2); } } double n_sum = sqrt( V1[0]*V1[0]+V1[1]*V1[1]+V1[2]*V1[2] ); V1[0] /= n_sum; V1[1] /= n_sum; V1[2] /= n_sum; n_sum = sqrt( V2[0]*V2[0]+V2[1]*V2[1]+V2[2]*V2[2] ); V2[0] /= n_sum; V2[1] /= n_sum; V2[2] /= n_sum; //Get the normal to the plane formed by the biggest two EVs EP_norm[0] = V1[1]*V2[2]-V1[2]*V2[1]; EP_norm[1] = V1[2]*V2[0]-V1[0]*V2[2]; EP_norm[2] = V1[0]*V2[1]-V1[1]*V2[0]; //Reassign V2 so that it is orthogonal to both EP_norm and V1 V2[0] = V1[1]*EP_norm[2]-V1[2]*EP_norm[1]; V2[1] = V1[2]*EP_norm[0]-V1[0]*EP_norm[2]; V2[2] = V1[0]*EP_norm[1]-V1[1]*EP_norm[0]; //Now we have the point normal form; EP_norm is the normal and //centroid_x, centroid_y, centroid_z is the point //The equation to the plane is EP_norm[0](x-centroid_x)+EP_norm[1](y-centroid_y)+EP_norm[2](z-centroid_z)=0 double dee = (centroid_x*EP_norm[0]+centroid_y*EP_norm[1]+centroid_z*EP_norm[2])*(-1.00); //Iterate through and assign values to each region typedef itk::ImageRegionConstIterator< FloatImageType > ConstIteratorTypeFloat; ConstIteratorTypeFloat pix_buf2( dist_im, dist_im->GetRequestedRegion() ); IteratorType iterator44( input_image, input_image->GetRequestedRegion() ); for ( pix_buf2.GoToBegin(); !pix_buf2.IsAtEnd(); ++pix_buf2 ){ //Use pixels that are only within the defined radius from the nucleus double current_distance = pix_buf2.Get(); if( (current_distance <= (double)surr_dist) && (current_distance>=(-1*inside_dist)) ){ USImageType::IndexType cur_in;//,cur_in_cpy; double n_vec[3]; cur_in[0] = pix_buf2.GetIndex()[0]+boundbox[0]-1-surr_dist; cur_in[1] = pix_buf2.GetIndex()[1]+boundbox[2]-1-surr_dist; cur_in[2] = pix_buf2.GetIndex()[2]+boundbox[4]-1-surr_dist; //cur_in_cpy[0] = cur_in[0]; cur_in_cpy[1] = cur_in[1]; cur_in_cpy[2] = cur_in[2]; if( cur_in[0] < 0 || cur_in[1] < 0 || cur_in[2] < 0 ) continue; if( cur_in[0] >= sizee[0] || cur_in[1] >= sizee[1] || cur_in[2] >= sizee[2] ) continue; iterator44.SetIndex( cur_in ); USImageType::PixelType pixel_intensity; pixel_intensity = iterator44.Get(); if( pixel_intensity < thresh ) continue; //The projection of the point on the plane formed by the fist two major axes double xxx, yyy, zzz; xxx = cur_in[0] - EP_norm[0]*((EP_norm[0]*cur_in[0]+EP_norm[1]*cur_in[1]+EP_norm[2]*cur_in[2]+dee) /(EP_norm[0]*EP_norm[0]+EP_norm[1]*EP_norm[1]+EP_norm[2]*EP_norm[2])); yyy = cur_in[1] - EP_norm[1]*((EP_norm[0]*cur_in[0]+EP_norm[1]*cur_in[1]+EP_norm[2]*cur_in[2]+dee) /(EP_norm[0]*EP_norm[0]+EP_norm[1]*EP_norm[1]+EP_norm[2]*EP_norm[2])); zzz = cur_in[2] - EP_norm[2]*((EP_norm[0]*cur_in[0]+EP_norm[1]*cur_in[1]+EP_norm[2]*cur_in[2]+dee) /(EP_norm[0]*EP_norm[0]+EP_norm[1]*EP_norm[1]+EP_norm[2]*EP_norm[2])); //The vector from the centroid to the projected point n_vec[0] = centroid_x-xxx; n_vec[1] = centroid_y-yyy; n_vec[2] = centroid_z-zzz; n_sum = sqrt( n_vec[0]*n_vec[0] + n_vec[1]*n_vec[1] + n_vec[2]*n_vec[2] ); n_vec[0] /= n_sum; n_vec[1] /= n_sum; n_vec[2] /= n_sum; //n_vec is the normalized vect in the direction of the projected point //V1 is the largest eigenvector //Get the dot and cross product between the two double doooot, crooos,fin_est_angle; doooot = n_vec[0]*V1[0]+n_vec[1]*V1[1]+n_vec[2]*V1[2]; crooos = n_vec[0]*V2[0]+n_vec[1]*V2[1]+n_vec[2]*V2[2]; fin_est_angle = atan2( crooos, doooot ); USPixelType bin_num; //Compute bin num if( fin_est_angle<0 ) fin_est_angle += (2*M_PI); bin_num = floor(fin_est_angle*number_of_rois/(2*M_PI)); //Check which side of the plane the point lies on double v_norm = (cur_in[0]-centroid_x)*(cur_in[0]-centroid_x) +(cur_in[1]-centroid_y)*(cur_in[1]-centroid_y) +(cur_in[2]-centroid_z)*(cur_in[2]-centroid_z); v_norm = sqrt( v_norm ); double doot = (cur_in[0]-centroid_x)*EP_norm[0]/v_norm + (cur_in[1]-centroid_y)*EP_norm[1]/v_norm + (cur_in[2]-centroid_z)*EP_norm[2]/v_norm; if( doot<0 ) bin_num += number_of_rois; quantified_numbers_cell.at((ind*(2*number_of_rois)+bin_num)) += pixel_intensity; } } } number_of_rois = number_of_rois*2; if( labelsList.size() == 1 ) { qfied_num.clear(); return qfied_num; } std::vector<double> quantified_numbers_cell_cpy(roi_list_size); std::copy(quantified_numbers_cell.begin(), quantified_numbers_cell.end(), quantified_numbers_cell_cpy.begin() ); //Run k-means //Most of the code is adapted from mul/mbl/mbl_k_means.cxx std::sort(quantified_numbers_cell.begin(), quantified_numbers_cell.end()); bool skipKmeans; double Positive_thresh; if( quantified_numbers_cell.at(0) == quantified_numbers_cell.at(quantified_numbers_cell.size()-1) ) skipKmeans = true; if( !skipKmeans ){ std::cout<<"Starting k-means\n"; std::cout<<"First:"<<quantified_numbers_cell.at(0)<<" Last:"<<quantified_numbers_cell.at(quantified_numbers_cell.size()-1)<<std::endl; unsigned k = 2; //Vectors and matrices for k-means std::vector< USImageType::PixelType > partition( roi_list_size, 0 ); std::vector< double > sums ( k, 0.0 ); std::vector< double > centers( k, 0.0 ); std::vector< USImageType::PixelType > nNearest( k, 0 ); //Use the elements that are evenly spaced to get the intial centers for( unsigned i=0; i<k; ++i ){ double index = ((double)(i)*roi_list_size)/(k+1); centers.at(i) = quantified_numbers_cell.at((itk::SizeValueType)index); bool duplicated; std::cout<<"Initializing centers\n"<<std::flush; if(i){ if( centers.at((i-1)) == centers.at(i) ){ duplicated = true; itk::SizeValueType ind=i+1; while( centers.at((i-1))==quantified_numbers_cell.at(ind) ) ++ind; centers.at(i) = quantified_numbers_cell.at(ind); sums.at(i) = quantified_numbers_cell.at(ind); } } if(!duplicated) sums.at(i) = quantified_numbers_cell.at((i+1)/(k+1)); ++nNearest[i]; } bool changed = true; std::cout<<"Waiting for kmeans to converge\n"<<std::flush; while(changed){ changed = false; for(itk::SizeValueType i=0; i<roi_list_size; ++i){ unsigned bestCentre = 0; double bestDist = fabs((centers.at(0)-quantified_numbers_cell.at(i))); for(unsigned j=1; j<k; ++j){ double dist = fabs((centers.at(j)-quantified_numbers_cell.at(i))); if( dist < bestDist ){ bestDist = dist; bestCentre = j; } } sums[bestCentre] += quantified_numbers_cell.at(i); ++ nNearest[bestCentre]; if( bestCentre != partition.at(i) ){ changed = true; partition.at(i) = bestCentre; } } for( unsigned j=0; j<k; ++j) centers.at(j) = sums.at(j)/nNearest.at(j); for( unsigned j=0; j<k; ++j) sums.at(j) = 0; for( unsigned j=0; j<k; ++j) nNearest.at(j) = 0; } for( unsigned i=0; i<k; ++i ) std::cout<<"Center "<<i<<" "<<centers.at(i)<<"\n"; Positive_thresh = ((centers.at(0)+centers.at(1))/2) < (255.0*thresh)? ((centers.at(0)+centers.at(1))/2) : (255.0*thresh); //Arbitrary upper thresh } else Positive_thresh = 255.0*thresh; std::cout<<"Positive_thresh "<<Positive_thresh<<"\n"; std::cout<<"Done k-means\n"; itk::SizeValueType ind = 0; for( USPixelType i=0; i<labelsList.size(); ++i ){ if( zp && (zero==i) ) continue; int num_positive_rois = 0; for( unsigned j=0; j<number_of_rois; ++j ){ itk::SizeValueType index_of_roi = ind*number_of_rois+j; if( quantified_numbers_cell_cpy.at(index_of_roi)>Positive_thresh ) ++num_positive_rois; } qfied_num.push_back(num_positive_rois); ++ind; } } std::cout<<"Done surroundedness\n"<<std::flush; return qfied_num; }