-
Notifications
You must be signed in to change notification settings - Fork 2
/
graphCutsAdapter.hxx
656 lines (536 loc) · 26.6 KB
/
graphCutsAdapter.hxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2015 Pol Monso Purti //
// Contact <[email protected]> for comments & bug reports //
// //
// This program is free software: you can redistribute it and/or modify //
// it under the terms of the version 3 of the GNU General Public License //
// as published by the Free Software Foundation. //
// //
// This program is distributed in the hope that it will be useful, but //
// WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //
// General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2015 Pol Monso Purti //
// Contact <[email protected]> for comments & bug reports //
// //
// This program is free software: you can redistribute it and/or modify //
// it under the terms of the version 3 of the GNU General Public License //
// as published by the Free Software Foundation. //
// //
// This program is distributed in the hope that it will be useful, but //
// WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //
// General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
//////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "itkImage.h"
#include "itkImageIterator.h"
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIterator.h"
#include "itkBinaryImageToShapeLabelMapFilter.h"
#include "itkLabelImageToShapeLabelMapFilter.h"
#include "itkRelabelComponentImageFilter.h"
#include "itkConnectedComponentImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkExtractImageFilter.h"
#include "QuickView.h"
#include "itkCustomColormapFunction.h"
#include "itkScalarToRGBColormapImageFilter.h"
#include "itkRGBPixel.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkThresholdImageFilter.h"
#include "itkRegionOfInterestImageFilter.h"
#include "itkGradientMagnitudeRecursiveGaussianImageFilter.h"
#include <ostream>
#include <random>
#include <limits>
#include "verbosityConstant.h"
#include "graphCutsAdapter.h"
#include "maxflow/graph.h"
//we assume that the input is a labelmap
template< typename TImageType >
int GraphCutsAdapter< TImageType >::getBoundingBox(const TImageType* segmentationImage,
typename TImageType::RegionType& roi,
typename TImageType::PixelType labelId)
{
typedef itk::BinaryThresholdImageFilter < TImageType, TImageType > BinaryThresholdImageFilterType;
typename BinaryThresholdImageFilterType::Pointer binaryThresholdFilter
= BinaryThresholdImageFilterType::New();
binaryThresholdFilter->SetInput(segmentationImage);
binaryThresholdFilter->SetLowerThreshold(labelId);
binaryThresholdFilter->SetUpperThreshold(labelId);
binaryThresholdFilter->SetInsideValue(255);
binaryThresholdFilter->SetOutsideValue(0);
//TODO do we need to update here or can we wait?
try {
binaryThresholdFilter->Update();
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << __LINE__ << "Error: " << error << std::endl;
return FUCKEDUP;
}
if(VerbosityConstant::verbosity >= VerbosityConstant::HIGH){
typedef itk::ImageFileWriter< TImageType > vWriterFilterType;
typename vWriterFilterType::Pointer vwriter = vWriterFilterType::New();
vwriter->SetFileName("thresholded.tif");
vwriter->SetInput(binaryThresholdFilter->GetOutput());
try {
vwriter->Update();
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << __LINE__ << "Error: " << error << std::endl;
return FUCKEDUP;
}
}
return GraphCutsAdapter< TImageType >::getBoundingBox(binaryThresholdFilter->GetOutput(),
roi);
return NAILEDIT;
}
//we assume that there's only one connected component
template< typename TImageType >
int GraphCutsAdapter< TImageType >::getBoundingBox(const TImageType* binarySegmentationImage,
typename TImageType::RegionType& roi)
{
typedef itk::BinaryImageToShapeLabelMapFilter< TImageType > BinaryImageToShapeLabelMapFilterType;
typename BinaryImageToShapeLabelMapFilterType::Pointer binaryImageToShapeLabelMapFilter = BinaryImageToShapeLabelMapFilterType::New();
binaryImageToShapeLabelMapFilter->SetInput(binarySegmentationImage);
try {
binaryImageToShapeLabelMapFilter->Update();
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << ":" << __LINE__ << "Error: " << error << std::endl;
return FUCKEDUP;
}
const unsigned int numObjects = binaryImageToShapeLabelMapFilter->GetOutput()->GetNumberOfLabelObjects();
//we assume that there's only one connected component
assert(numObjects == 1 && "getBoundingBox assumes you filtered out all other labels");
if(VerbosityConstant::verbosity >= VerbosityConstant::MEDIUM)
std::cout << "There are " << numObjects << " objects." << std::endl;
if(numObjects == 0) {
std::cerr << "0 objects present. Stop." << std::endl;
return FUCKEDUP;
}
typedef typename BinaryImageToShapeLabelMapFilterType::OutputImageType::LabelObjectType LabelObjectType;
LabelObjectType* labelObject = binaryImageToShapeLabelMapFilter->GetOutput()->GetNthLabelObject(0);
if(VerbosityConstant::verbosity >= VerbosityConstant::MEDIUM) {
std::cout << "LabelObject description:" << std::endl;
std::cout << "Object " << std::endl;
std::cout << " Bounding box " << labelObject->GetBoundingBox() << std::endl;
std::cout << " Centroid " << labelObject->GetCentroid() << std::endl;
std::cout << " Volume " << labelObject->GetPhysicalSize() << std::endl;
}
roi = labelObject->GetBoundingBox();
return NAILEDIT;
}
//we assume binary image
template< typename TImageType >
int GraphCutsAdapter< TImageType >::seedSinksImage2Coordinates(const TImageType* seedSinkROI,
std::vector< typename TImageType::IndexType >& seeds,
std::vector< typename TImageType::IndexType >& sinks) {
//extract cube or assume extracted?
if(VerbosityConstant::verbosity >= VerbosityConstant::HIGH){
typename WriterFilterType::Pointer writer = WriterFilterType::New();
writer->SetFileName("seedSinks.tif");
writer->SetInput(seedSinkROI);
try {
writer->Update();
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << __LINE__ << "Error: " << error << std::endl;
return FUCKEDUP;
}
}
//retrieve a list of coordinates from seedSink
itk::ImageRegionConstIteratorWithIndex< TImageType > it(seedSinkROI, seedSinkROI->GetLargestPossibleRegion());
for(it.GoToBegin(); !it.IsAtEnd(); ++it)
{
if(it.Get() == SEED_LABEL){
seeds.push_back( it.GetIndex() );
} else if(it.Get() == SINK_LABEL){
sinks.push_back( it.GetIndex() );
}
}
if(sinks.size() == 0 || seeds.size() == 0){
if(VerbosityConstant::verbosity >= VerbosityConstant::LOW)
std::cerr << "No seeds or sinks found." << std::endl;
return FUCKEDUP;
}
return NAILEDIT;
}
template< typename TImageType >
int GraphCutsAdapter< TImageType >::bilabelImage2LabelObjects(const TImageType* segmentationImage,
typename ShapeLabelObjectType::Pointer& labelObject1,
typename ShapeLabelObjectType::Pointer& labelObject2) {
typedef itk::LabelImageToShapeLabelMapFilter< TImageType > ImageToShapeLabelMapFilterType;
typename ImageToShapeLabelMapFilterType::Pointer imageToShapeLabelMapFilter = ImageToShapeLabelMapFilterType::New();
imageToShapeLabelMapFilter->SetInput(segmentationImage);
try {
imageToShapeLabelMapFilter->Update();
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << ":" << __LINE__ << "Error: " << error << std::endl;
return FUCKEDUP;
}
const unsigned int numObjects = imageToShapeLabelMapFilter->GetOutput()->GetNumberOfLabelObjects();
//we assume that there's only one connected component
assert(numObjects == 2 && " we assume you only have 2 labels, but there weren't.");
if(numObjects != 2) {
std::cerr << numObjects << " !=2 objects present. Stop." << std::endl;
return JUSTONEOBJECT;
}
typedef typename ImageToShapeLabelMapFilterType::OutputImageType::LabelObjectType LabelObjectType;
labelObject1 = imageToShapeLabelMapFilter->GetOutput()->GetNthLabelObject(0);
labelObject2 = imageToShapeLabelMapFilter->GetOutput()->GetNthLabelObject(1);
if(VerbosityConstant::verbosity >= VerbosityConstant::MEDIUM) {
std::cout << "BilabelImage to Label Objects:" << std::endl;
std::cout << "Object 1" << std::endl;
std::cout << " Bounding box " << labelObject1->GetBoundingBox() << std::endl;
std::cout << " Centroid " << labelObject1->GetCentroid() << std::endl;
std::cout << " Volume " << labelObject1->GetPhysicalSize() << std::endl;
std::cout << "Object 2" << std::endl;
std::cout << " Bounding box " << labelObject2->GetBoundingBox() << std::endl;
std::cout << " Centroid " << labelObject2->GetCentroid() << std::endl;
std::cout << " Volume " << labelObject2->GetPhysicalSize() << std::endl;
}
return NAILEDIT;
}
template< typename TImageType >
int GraphCutsAdapter< TImageType >::dummygraphcuts(const TImageType* segmentationImage,
const std::vector< typename GradientImageType::Pointer >& scoreImages,
const std::vector< typename TImageType::IndexType >& sources,
const std::vector< typename TImageType::IndexType >& sinks,
typename TImageType::Pointer& splittedSegmentationImage) {
//TODO remove when computing boundingbox is ready
splittedSegmentationImage->SetRegions(segmentationImage->GetLargestPossibleRegion());
splittedSegmentationImage->Allocate();
//Just checking the gradient
if(VerbosityConstant::verbosity >= VerbosityConstant::HIGH){
typedef itk::ImageFileWriter< GradientImageType > GradientWriterFilterType;
typename GradientWriterFilterType::Pointer gwriter = GradientWriterFilterType::New();
for(unsigned int i = 0; i < scoreImages.size() ; i++) {
gwriter->SetInput(scoreImages[i]);
gwriter->SetFileName("gradient" + std::to_string(i) + ".mha");
try {
gwriter->Update();
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << ":" << __LINE__ << " Error: " << error << std::endl;
return FUCKEDUP;
}
}
}
//we don't have the graphcuts yet, so let's say the result ofthe graphcut is just the sinkSeedImage
for(int i = 0; i<sources.size(); i++)
splittedSegmentationImage->SetPixel(sources[i], 128);
for(int i = 0; i<sinks.size(); i++)
splittedSegmentationImage->SetPixel(sinks[i], 255);
return NAILEDIT;
}
//TODO avoid copy of std::vectors
template< typename TImageType >
int GraphCutsAdapter< TImageType >::graphcuts(const TImageType* segmentationImage,
const std::vector< typename GradientImageType::Pointer >& scoreImages,
const std::vector< typename TImageType::IndexType >& sources,
const std::vector< typename TImageType::IndexType >& sinks,
typename TImageType::Pointer& splittedSegmentationImage) {
assert(segmentationImage->GetLargestPossibleRegion().GetSize()[0] > 0);
//TODO maybe it's ok to delegate the allocation to the client
splittedSegmentationImage->SetRegions(segmentationImage->GetLargestPossibleRegion());
splittedSegmentationImage->Allocate();
// Get the region
const typename TImageType::RegionType& region = splittedSegmentationImage->GetBufferedRegion();
int num_nodes = region.GetNumberOfPixels();
// Create the graph
typedef typename GradientImageType::PixelType GraphDataT;
typedef Graph<GraphDataT, GraphDataT, GraphDataT> GraphT;
GraphT g(num_nodes, num_nodes*6);
g.add_node(num_nodes);
// Add non-terminal edges
itk::ImageRegionConstIteratorWithIndex<TImageType> segmentation_it(segmentationImage, region);
int current_node = 0;
// Initialize iterators for score images.
std::array<itk::ImageRegionConstIterator<GradientImageType>, TImageType::ImageDimension> scores_its;
for(int n = 0; n < TImageType::ImageDimension; ++n)
scores_its[n] = itk::ImageRegionConstIterator<GradientImageType>(scoreImages[n], region);
for(;!segmentation_it.IsAtEnd(); ++segmentation_it, ++current_node,
std::for_each(scores_its.begin(), scores_its.end(), [](itk::ImageRegionConstIterator<GradientImageType>& p){++p;}))
{
if(segmentation_it.Get() == 0)
continue;
const typename TImageType::IndexType& index = segmentation_it.GetIndex();
for(int n = 0; n < TImageType::ImageDimension; ++n)
{
// Neighbour index
typename TImageType::IndexType nindex = index;
nindex[n] -= 1;
// Check if neighbour is out of bounds
if(nindex[n] < 0)
continue;
// Is it better ComputeOffsets or having an array of cached offsets?
const GraphDataT weight = scores_its[n].Get(); // + 0.5;
int nnode = segmentationImage->ComputeOffset(nindex);
g.add_edge(current_node, nnode, weight, weight);
}
}
// Add terminal edges
const GraphDataT inf = std::numeric_limits<GraphDataT>::infinity();
typename std::vector<typename TImageType::IndexType>::const_iterator seeds_it;
for(seeds_it = sources.begin(); seeds_it != sources.end(); ++seeds_it)
{
int node = segmentationImage->ComputeOffset(*seeds_it);
g.add_tweights(node, 0, inf);
}
for(seeds_it = sinks.begin(); seeds_it != sinks.end(); ++seeds_it)
{
int node = segmentationImage->ComputeOffset(*seeds_it);
g.add_tweights(node, inf, 0);
}
// Maxflow aka graph-cut
GraphDataT energy = g.maxflow();
if(VerbosityConstant::verbosity >= VerbosityConstant::HIGH)
std::cout << "Energy of the cut: " << energy << std::endl;
// Write results to splittedSegmentationImage
segmentation_it.GoToBegin();
itk::ImageRegionIterator<TImageType> result_it(splittedSegmentationImage, region);
current_node = 0;
for(; !segmentation_it.IsAtEnd(); ++segmentation_it, ++result_it, ++current_node)
{
if(segmentation_it.Get() == 0)
result_it.Set(0);
else
result_it.Set(g.what_segment(current_node) == SOURCE ? 128 : 255);
}
return NAILEDIT;
}
//template< typename TImageType >
//int GraphCutsAdapter< TImageType >::mergeRegions(std::vector<typename TImageType::RegionType *> regions,
// typename TImageType::RegionType& mergedRegion)
//{
//}
// Assumes labelMapImage is already allocated (otherwise GetLargestPossibleRegion returns size = 0)
template< typename TImageType >
int GraphCutsAdapter< TImageType >::labelObjects2Image(ShapeLabelObjectType* labelObject1,
ShapeLabelObjectType* labelObject2,
typename TImageType::Pointer& labelMapImage){
//TODO maybe there's a better way to check allocation/size
typename TImageType::RegionType region = labelMapImage->GetLargestPossibleRegion();
typename TImageType::SpacingType spacing = labelMapImage->GetSpacing();
if(region.GetSize()[0] == 0) {
std::cerr << "Label image not allocated. Using labelobjects boundingbox." << std::endl;
mergeRegions(std::vector<typename TImageType::RegionType>{labelObject1->GetBoundingBox(), labelObject2->GetBoundingBox()}, region);
}
auto segLabelMap = LabelMapType::New();
segLabelMap->SetSpacing(spacing);
segLabelMap->SetRegions(region);
segLabelMap->Allocate();
labelObject1->SetLabel(itk::NumericTraits< typename TImageType::PixelType >::max());
labelObject2->SetLabel(itk::NumericTraits< typename TImageType::PixelType >::max()/2);
segLabelMap->AddLabelObject(labelObject1);
segLabelMap->AddLabelObject(labelObject2);
auto label2volume = Label2VolumeFilter::New();
label2volume->SetInput(segLabelMap);
try {
label2volume->Update();
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << ":" << __LINE__ << " Error: " << error << std::endl;
return FUCKEDUP;
}
labelMapImage = label2volume->GetOutput();
return NAILEDIT;
}
template< typename TImageType >
int GraphCutsAdapter< TImageType >::process(const TImageType* image,
const TImageType* segmentationImage,
const std::vector< typename TImageType::IndexType >& seeds,
const std::vector< typename TImageType::IndexType >& sinks,
typename ShapeLabelObjectType::Pointer& labelObject1,
typename ShapeLabelObjectType::Pointer& labelObject2,
float shapeWeight) {
//if we allow Real Time seeds might yet not be both there
if(seeds.size() == 0 || sinks.size() == 0)
return YOUARENOTREADY;
//extract cube
typename TImageType::RegionType roi;
getBoundingBox(segmentationImage, roi);
typedef itk::RegionOfInterestImageFilter< TImageType, TImageType > ROIFilterType;
typename ROIFilterType::Pointer imageROIextractor = ROIFilterType::New();
imageROIextractor->SetRegionOfInterest(roi);
imageROIextractor->SetInput(image);
//features
typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< TImageType, GradientImageType > GradientFilterType;
typename GradientFilterType::Pointer gradientFilter = GradientFilterType::New();
gradientFilter->SetInput(imageROIextractor->GetOutput());
float sigma = 3.5; //TODO use 3.5, pass by parameter or what?
gradientFilter->SetSigma( sigma );
// gradientFilter->SetFirstOrder();
std::vector< typename GradientImageType::Pointer > gradients(TImageType::ImageDimension);
typedef itk::RegionOfInterestImageFilter< TImageType, TImageType > ROIFilterType;
typename ROIFilterType::Pointer segmentationROIextractor = ROIFilterType::New();
segmentationROIextractor->SetRegionOfInterest(roi);
segmentationROIextractor->SetInput(segmentationImage);
try {
segmentationROIextractor->Update();
// unnecessary if we have pipeline
// imageROIextractor->Update();
//TODO load from disk if available
for(unsigned int dim = 0; dim < TImageType::ImageDimension; dim++) {
// gradientFilter->SetDirection(dim);
gradientFilter->Update();
gradients[dim] = gradientFilter->GetOutput();
gradients[dim]->DisconnectPipeline();
}
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << ":" << __LINE__ << " Error: " << error << std::endl;
return FUCKEDUP;
}
typename TImageType::Pointer segmentationROI = segmentationROIextractor->GetOutput();
//remap coordinates
std::vector< typename TImageType::IndexType > remappedseeds;
std::vector< typename TImageType::IndexType > remappedsinks;
remappedseeds.reserve(seeds.size());
remappedsinks.reserve(sinks.size());
//FIXME find a way to transform offsets to indeces or a better way
// to remap the coordinates, this is ridiculous
// see http://public.kitware.com/pipermail/insight-developers/2006-December/008806.html
const typename TImageType::IndexType roiBeginIndex = roi.GetIndex();
for(unsigned int i=0; i < seeds.size(); i++) {
typename TImageType::OffsetType offset = seeds[i] - roiBeginIndex;
typename TImageType::IndexType remappedidx;
for(int dim = 0; dim < TImageType::ImageDimension; dim++)
remappedidx[dim] = offset[dim];
remappedseeds.push_back(remappedidx);
}
for(unsigned int i=0; i < sinks.size(); i++) {
typename TImageType::OffsetType offset = sinks[i] - roiBeginIndex;
typename TImageType::IndexType remappedidx;
for(int dim = 0; dim < TImageType::ImageDimension; dim++)
remappedidx[dim] = offset[dim];
remappedsinks.push_back(remappedidx);
}
//normalisation
#define TESTSPACING 0
#if TESTSPACING
typename TImageType::SpacingType spacing = image->GetSpacing();
spacing[2] = 5;
#else
const typename TImageType::SpacingType spacing = image->GetSpacing();
#endif
//TODO add the possibility to pass spacing as a parameter (as e.g. tif doesn't store it)
const float zAnisotropyFactor = 2*spacing[2]/(spacing[0] + spacing[1]);
assert(TImageType::ImageDimension > 0);
constexpr unsigned int dims = TImageType::ImageDimension;
for(unsigned int dim = 0; dim < dims; dim++)
assert(gradients[dim]->GetRequestedRegion().GetSize() == roi.GetSize());
//compute 1/p_z*(1/(1+|g|^2) + shapeWeight)
//we can also use addition filter and inverse filter (si jamais)
//x and y dimensions
for(unsigned int dim = 0; dim < dims-1; dim++) {
itk::ImageRegionIterator< GradientImageType > git( gradients[dim], gradients[dim]->GetRequestedRegion() );
while( !git.IsAtEnd()) {
const typename GradientImageType::PixelType pixel = git.Get();
git.Set( 1/(1 + pixel*pixel) + shapeWeight );
++git;
}
}
//z dimension
{
// Errors of the cut in the Z-axis seem to be harder to fix manually than those
// in the X and Y axes.
// Make cuts in the Z-axis more likely even when the anisotropy factor is 1.
// TODO: parameter?
const typename GradientImageType::PixelType zfactor = 1 / (5 * zAnisotropyFactor);
constexpr unsigned int dim = dims - 1;
itk::ImageRegionIterator< GradientImageType > git( gradients[dim], gradients[dim]->GetRequestedRegion() );
while( !git.IsAtEnd()) {
const typename GradientImageType::PixelType pixel = git.Get();
git.Set(zfactor * (1/(1 + pixel*pixel) + shapeWeight ));
++git;
}
}
if(VerbosityConstant::verbosity >= VerbosityConstant::HIGH){
std::cout << "Gradients computed. Saving." << std::endl;
for(unsigned int dim = 0; dim < dims; dim++) {
typename GradientWriterFilterType::Pointer writer = GradientWriterFilterType::New();
writer->SetInput(gradients[dim]);
writer->SetFileName("gradient" + std::to_string(dim) + ".tif");
try {
writer->Update();
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << ":" << __LINE__ << " Error: " << error << std::endl;
return FUCKEDUP;
}
}
}
//Do graphcuts
typename TImageType::Pointer cutSegmentationImage = TImageType::New();
//temporary patch
int result;
{
result = graphcuts(segmentationROI, gradients, remappedseeds, remappedsinks, cutSegmentationImage);
}
//
if(result == FUCKEDUP)
return result;
if(VerbosityConstant::verbosity >= VerbosityConstant::HIGH){
typename WriterFilterType::Pointer writer = WriterFilterType::New();
writer->SetInput(cutSegmentationImage);
writer->SetFileName("graphCutsOutput.tif");
try {
writer->Update();
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << ":" << __LINE__ << " Error: " << error << std::endl;
return FUCKEDUP;
}
}
//Transform graphcut output to labelObjects
result = bilabelImage2LabelObjects(cutSegmentationImage, labelObject1, labelObject2);
if(result == FUCKEDUP || result == JUSTONEOBJECT)
return result;
if(VerbosityConstant::verbosity >= VerbosityConstant::HIGH){
typename TImageType::Pointer labelMapImage = TImageType::New();
labelObjects2Image(labelObject1, labelObject2, labelMapImage);
typename WriterFilterType::Pointer writer = WriterFilterType::New();
writer->SetFileName("ROILabelMap.tif");
writer->SetInput(labelMapImage);
try {
writer->Update();
} catch( itk::ExceptionObject & error ) {
std::cerr << __FILE__ << ":" << __LINE__ << " Error: " << error << std::endl;
return FUCKEDUP;
}
}
//reset the indexes to its original Region
typename TImageType::OffsetType offset;
typename TImageType::IndexType index = roi.GetIndex();
for(unsigned int i = 0; i < TImageType::ImageDimension; i++)
offset[i] = index[i];
#warning Shift doesn't work correctly given that \
it does not change the bounding box. \
Setting the boundingbox does not work either, \
given that the indexes of the pixels remain unchanged. \
Therefore, we do both until the bug is solved.
#define USESHIFT
#ifdef USESHIFT
labelObject1->Shift(offset);
labelObject2->Shift(offset);
//we need to do this in order to have updated attributes.
//a bit of an overkill, so maybe consider returning a labelmap instead of two objects
// ShapeLabelMapFilter::Pointer shape = ShapeFilterType::New();
// shape->SetInput(labelMap);
// shape->Update();
//#else
typename TImageType::RegionType region1 = labelObject1->GetBoundingBox();
region1.GetModifiableIndex() += offset;
labelObject1->SetBoundingBox(region1);
typename TImageType::RegionType region2 = labelObject2->GetBoundingBox();
region2.GetModifiableIndex() += offset;
labelObject2->SetBoundingBox(region2);
#endif
return NAILEDIT;
}
//explicit instantiation will fail if the caller uses a different instantiation
template class GraphCutsAdapter<itk::Image<unsigned char, 3> >; // explicit template instantiation