forked from Kitware/VTK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vtkImageToPolyDataFilter.cxx
1355 lines (1196 loc) · 40.3 KB
/
vtkImageToPolyDataFilter.cxx
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageToPolyDataFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageToPolyDataFilter.h"
#include "vtkAppendPolyData.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkEdgeTable.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkLine.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkScalarsToColors.h"
#include "vtkUnsignedCharArray.h"
#include <vector>
vtkStandardNewMacro(vtkImageToPolyDataFilter);
vtkCxxSetObjectMacro(vtkImageToPolyDataFilter, LookupTable, vtkScalarsToColors);
vtkImageToPolyDataFilter::vtkImageToPolyDataFilter()
{
this->OutputStyle = VTK_STYLE_POLYGONALIZE;
this->ColorMode = VTK_COLOR_MODE_LINEAR_256;
this->Smoothing = 1;
this->NumberOfSmoothingIterations = 40;
this->Decimation = 1;
this->DecimationError = 1.5;
this->Error = 100;
this->SubImageSize = 250;
this->Table = vtkUnsignedCharArray::New();
this->LookupTable = nullptr;
}
vtkImageToPolyDataFilter::~vtkImageToPolyDataFilter()
{
this->Table->Delete();
if (this->LookupTable)
{
this->LookupTable->Delete();
}
}
// declare helper functions
//
int vtkImageToPolyDataFilter::RequestData(vtkInformation* vtkNotUsed(request),
vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
// get the info objects
vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation* outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkImageData* input = vtkImageData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPolyData* tmpOutput;
vtkPolyData* tmpInput;
vtkAppendPolyData* append;
vtkPolyData* appendOutput;
vtkDataArray* inScalars = input->GetPointData()->GetScalars();
vtkIdType numPixels = input->GetNumberOfPoints();
int dims[3], numComp;
double origin[3], spacing[3];
vtkUnsignedCharArray* pixels;
int type;
int numPieces[2], extent[4];
int i, j, newDims[3], totalPieces, pieceNum, abortExecute = 0;
double newOrigin[3];
// Check input and initialize
vtkDebugMacro(<< "Vectorizing image...");
if (inScalars == nullptr || numPixels < 1)
{
vtkDebugMacro(<< "Not enough input to create output");
return 1;
}
append = vtkAppendPolyData::New();
tmpOutput = vtkPolyData::New();
tmpInput = vtkPolyData::New();
numComp = inScalars->GetNumberOfComponents();
type = inScalars->GetDataType();
appendOutput = append->GetOutput();
input->GetDimensions(dims);
input->GetOrigin(origin);
input->GetSpacing(spacing);
// Figure out how many pieces to break the image into (the image
// might be too big to process). The filter does a series of appends
// to join the pieces together.
numPieces[0] = ((dims[0] - 2) / this->SubImageSize) + 1;
numPieces[1] = ((dims[1] - 2) / this->SubImageSize) + 1;
totalPieces = numPieces[0] * numPieces[1];
appendOutput->Initialize(); // empty the output
append->AddInputData(tmpOutput); // output of piece
append->AddInputData(tmpInput); // output of previoius append
// Loop over this many pieces
for (pieceNum = j = 0; j < numPieces[1] && !abortExecute; j++)
{
extent[2] = j * this->SubImageSize; // the y range
extent[3] = (j + 1) * this->SubImageSize;
if (extent[3] >= dims[1])
{
extent[3] = dims[1] - 1;
}
for (i = 0; i < numPieces[0] && !abortExecute; i++)
{
extent[0] = i * this->SubImageSize; // the x range
extent[1] = (i + 1) * this->SubImageSize;
if (extent[1] >= dims[0])
{
extent[1] = dims[0] - 1;
}
vtkDebugMacro(<< "Processing #" << pieceNum);
this->UpdateProgress((double)pieceNum / totalPieces);
if (this->GetAbortExecute())
{
abortExecute = 1;
break;
}
pieceNum++;
// Figure out characteristics of current sub-image
newDims[0] = extent[1] - extent[0] + 1;
newDims[1] = extent[3] - extent[2] + 1;
newOrigin[0] = origin[0] + extent[0] * spacing[0];
newOrigin[1] = origin[1] + extent[2] * spacing[1];
newOrigin[2] = 0.0;
// Create a quantized copy of the image based on the color table
//
pixels = this->QuantizeImage(inScalars, numComp, type, dims, extent);
vtkDebugMacro(<< "Quantizing color...image size (" << newDims[0] << ", " << newDims[1]
<< ")");
// Generate polygons according to mode setting
//
if (this->OutputStyle == VTK_STYLE_PIXELIZE)
{
this->PixelizeImage(pixels, newDims, newOrigin, spacing, tmpOutput);
}
else if (this->OutputStyle == VTK_STYLE_RUN_LENGTH)
{
this->RunLengthImage(pixels, newDims, newOrigin, spacing, tmpOutput);
}
else // VTK_STYLE_POLYGONALIZE
{
this->PolygonalizeImage(pixels, newDims, newOrigin, spacing, tmpOutput);
}
// Append pieces together
//
tmpInput->CopyStructure(appendOutput);
tmpInput->GetPointData()->PassData(appendOutput->GetPointData());
tmpInput->GetCellData()->PassData(appendOutput->GetCellData());
append->Update();
// Clean up this iteration
//
pixels->Delete();
tmpInput->Initialize();
tmpOutput->Initialize();
} // for i pieces
} // for j pieces
// Create the final output contained in the append filter
output->CopyStructure(appendOutput);
output->GetPointData()->PassData(appendOutput->GetPointData());
output->GetCellData()->PassData(appendOutput->GetCellData());
append->Delete();
tmpInput->Delete();
tmpOutput->Delete();
return 1;
}
void vtkImageToPolyDataFilter::PixelizeImage(vtkUnsignedCharArray* pixels, int dims[3],
double origin[3], double spacing[3], vtkPolyData* output)
{
int numPts, numCells, i, j, id;
vtkIdType pts[4];
vtkPoints* newPts;
vtkCellArray* newPolys;
double x[3];
vtkUnsignedCharArray* polyColors;
unsigned char *ptr, *colors = pixels->GetPointer(0);
// create the points - see whether to create or append
numPts = (dims[0] + 1) * (dims[1] + 1);
newPts = vtkPoints::New();
newPts->SetNumberOfPoints(numPts);
x[2] = 0.0;
for (id = 0, j = 0; j <= dims[1]; j++)
{
x[1] = origin[1] + j * spacing[1];
for (i = 0; i <= dims[0]; i++)
{
x[0] = origin[0] + i * spacing[0];
newPts->SetPoint(id, x);
id++;
}
}
output->SetPoints(newPts);
newPts->Delete();
// create the cells and cell colors
//
numCells = dims[0] * dims[1];
newPolys = vtkCellArray::New();
newPolys->AllocateEstimate(numCells, 4);
polyColors = vtkUnsignedCharArray::New();
polyColors->SetNumberOfValues(3 * numCells); // for rgb
polyColors->SetNumberOfComponents(3);
// loop over all pixels, creating a quad per pixel.
// Note: copying point data (pixel values) to cell data (quad colors).
for (id = 0, j = 0; j < dims[1]; j++)
{
for (i = 0; i < dims[0]; i++)
{
pts[0] = i + j * (dims[0] + 1);
pts[1] = pts[0] + 1;
pts[2] = pts[1] + dims[0] + 1;
pts[3] = pts[2] - 1;
newPolys->InsertNextCell(4, pts);
ptr = colors + 3 * id;
polyColors->SetValue(3 * id, ptr[0]);
polyColors->SetValue(3 * id + 1, ptr[1]);
polyColors->SetValue(3 * id + 2, ptr[2]);
id++;
}
}
output->SetPolys(newPolys);
newPolys->Delete();
output->GetCellData()->SetScalars(polyColors);
polyColors->Delete();
}
void vtkImageToPolyDataFilter::RunLengthImage(vtkUnsignedCharArray* pixels, int dims[3],
double origin[3], double spacing[3], vtkPolyData* output)
{
int i, j;
vtkIdType pts[4], id;
vtkPoints* newPts;
vtkCellArray* newPolys;
double x[3], minX, maxX, minY, maxY;
vtkUnsignedCharArray* polyColors;
unsigned char *colors = pixels->GetPointer(0), *color;
// Setup data
newPts = vtkPoints::New();
newPolys = vtkCellArray::New();
newPolys->AllocateEstimate(dims[0] * dims[1] / 10, 4);
polyColors = vtkUnsignedCharArray::New();
polyColors->Allocate(3 * dims[0] * dims[1] / 10); // for rgb
polyColors->SetNumberOfComponents(3);
// Loop over row-by-row generating quad polygons
x[2] = 0.0;
for (j = 0; j < dims[1]; j++)
{
if (j == 0)
{
minY = origin[1];
maxY = origin[1] + 0.5 * spacing[1];
}
else if (j == (dims[1] - 1))
{
minY = origin[1] + j * spacing[1] - 0.5 * spacing[1];
maxY = origin[1] + j * spacing[1];
}
else
{
minY = origin[1] + j * spacing[1] - 0.5 * spacing[1];
maxY = origin[1] + j * spacing[1] + 0.5 * spacing[1];
}
for (i = 0; i < dims[0];)
{
if (i == 0)
{
minX = origin[0];
}
else
{
minX = origin[0] + i * spacing[0] - 0.5 * spacing[0];
}
color = colors + 3 * (i + j * dims[0]);
while (i < dims[0])
{
unsigned char* ptr = colors + 3 * (i + j * dims[0]);
if (!this->IsSameColor(color, ptr))
{
break;
}
else
{
i++;
}
}
if (i >= dims[0])
{
maxX = origin[0] + (dims[0] - 1) * spacing[0];
}
else
{
maxX = origin[0] + (i - 1) * spacing[0] + 0.5 * spacing[0];
}
// Create quad cell
x[0] = minX;
x[1] = minY;
pts[0] = newPts->InsertNextPoint(x);
x[0] = maxX;
pts[1] = newPts->InsertNextPoint(x);
x[1] = maxY;
pts[2] = newPts->InsertNextPoint(x);
x[0] = minX;
pts[3] = newPts->InsertNextPoint(x);
id = newPolys->InsertNextCell(4, pts);
polyColors->InsertValue(3 * id, color[0]);
polyColors->InsertValue(3 * id + 1, color[1]);
polyColors->InsertValue(3 * id + 2, color[2]);
}
}
output->SetPoints(newPts);
newPts->Delete();
output->SetPolys(newPolys);
newPolys->Delete();
output->GetCellData()->SetScalars(polyColors);
polyColors->Delete();
}
void vtkImageToPolyDataFilter::PolygonalizeImage(vtkUnsignedCharArray* pixels, int dims[3],
double origin[3], double spacing[3], vtkPolyData* output)
{
int numPolys;
int numPixels = dims[0] * dims[1];
// Perform connected traversal on quantized points. This builds
// the initial "polygons" in implicit form.
//
this->PolyColors = vtkUnsignedCharArray::New();
this->PolyColors->SetNumberOfComponents(3);
this->PolyColors->Allocate(5000);
numPolys = this->ProcessImage(pixels, dims);
vtkDebugMacro(<< "Visited regions..." << numPolys << " polygons");
// Build edges around the boundary of the polygons. Also identify
// junction points where 3 or 4 polygons meet.
//
vtkPoints* points = vtkPoints::New();
points->Allocate(numPixels / 2, numPixels / 2);
vtkUnsignedCharArray* pointDescr = vtkUnsignedCharArray::New();
pointDescr->Allocate(numPixels / 2, numPixels / 2);
vtkCellArray* edgeConn = vtkCellArray::New();
edgeConn->AllocateEstimate(numPixels / 2, 1);
vtkPolyData* edges = vtkPolyData::New();
edges->SetPoints(points);
edges->SetLines(edgeConn);
points->Delete();
edgeConn->Delete();
this->BuildEdges(pixels, dims, origin, spacing, pointDescr, edges);
vtkDebugMacro(<< "Edges built...");
// Now that we've got the edges, we have to build the "loops" around the
// polygons that define the polygon explicitly.
//
vtkUnsignedCharArray* polyColors = vtkUnsignedCharArray::New();
polyColors->SetNumberOfComponents(3);
polyColors->SetNumberOfValues(numPolys * 3);
this->BuildPolygons(pointDescr, edges, numPolys, polyColors);
this->PolyColors->Delete();
delete[] this->Visited;
vtkDebugMacro(<< "Constructed polygons...");
// Smooth edge network. Some points are identified as fixed, others
// move using Laplacian smoothing.
//
if (this->Smoothing)
{
this->SmoothEdges(pointDescr, edges);
vtkDebugMacro(<< "Edges smoothed...");
}
// Decimate edge network. There will be colinear vertices along edges.
// These are eliminated.
//
if (this->Decimation)
{
this->DecimateEdges(edges, pointDescr, this->DecimationError);
}
// Create output polydata. Each polyon is output with its edges.
//
this->GeneratePolygons(edges, numPolys, output, polyColors, pointDescr);
vtkDebugMacro(<< "Output generated...");
// clean up and get out
edges->Delete();
polyColors->Delete();
pointDescr->Delete();
}
// The following are private helper functions----------------------------------
//
vtkUnsignedCharArray* vtkImageToPolyDataFilter::QuantizeImage(
vtkDataArray* inScalars, int numComp, int type, int dims[3], int extent[4])
{
int numPixels, i, j, idx, id;
vtkUnsignedCharArray* pixels;
unsigned char *ptr, *ptr2, *outPixels;
unsigned char* inPixels;
// doing a portion of the image
numPixels = (extent[1] - extent[0] + 1) * (extent[3] - extent[2] + 1);
pixels = vtkUnsignedCharArray::New();
pixels->SetNumberOfValues(3 * numPixels);
outPixels = pixels->GetPointer(0);
// Figure out how to quantize
//
if (this->ColorMode == VTK_COLOR_MODE_LINEAR_256)
{
// Check scalar type
if (type != VTK_UNSIGNED_CHAR || numComp != 3)
{
vtkErrorMacro(<< "Wrong input scalar type");
return nullptr;
}
else
{
inPixels = static_cast<vtkUnsignedCharArray*>(inScalars)->GetPointer(0);
}
// Generate a color table used to quantize the points
//
if (this->GetMTime() > this->TableMTime)
{
this->BuildTable(inPixels);
}
for (id = 0, j = extent[2]; j <= extent[3]; j++)
{
for (i = extent[0]; i <= extent[1]; i++)
{
idx = i + j * dims[0];
ptr = inPixels + 3 * idx;
ptr2 = outPixels + 3 * id;
const unsigned char* color = this->GetColor(ptr);
ptr2[0] = color[0];
ptr2[1] = color[1];
ptr2[2] = color[2];
id++;
}
}
} // using build in table
else // using provided lookup table
{
if (numComp != 1 || this->LookupTable == nullptr)
{
vtkErrorMacro(<< "LUT mode requires single component scalar and LUT");
return nullptr;
}
double s;
for (id = 0, j = extent[2]; j <= extent[3]; j++)
{
for (i = extent[0]; i <= extent[1]; i++)
{
idx = i + j * dims[0];
s = inScalars->GetComponent(idx, 0);
const unsigned char* color = this->LookupTable->MapValue(s);
ptr2 = outPixels + 3 * id;
ptr2[0] = color[0];
ptr2[1] = color[1];
ptr2[2] = color[2];
id++;
}
}
}
return pixels;
}
void vtkImageToPolyDataFilter::BuildTable(unsigned char* vtkNotUsed(inPixels))
{
int red, green, blue, idx = 0;
this->Table->SetNumberOfValues(256 * 3);
// use 3-3-2 bits for rgb
for (blue = 0; blue < 256; blue += 64)
{
for (green = 0; green < 256; green += 32)
{
for (red = 0; red < 256; red += 32)
{
this->Table->SetValue(idx++, red);
this->Table->SetValue(idx++, green);
this->Table->SetValue(idx++, blue);
}
}
}
}
int vtkImageToPolyDataFilter::FillInputPortInformation(int, vtkInformation* info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkImageData");
return 1;
}
void vtkImageToPolyDataFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Output Style: ";
if (this->OutputStyle == VTK_STYLE_PIXELIZE)
{
os << indent << "Pixelize\n";
}
else if (this->OutputStyle == VTK_STYLE_RUN_LENGTH)
{
os << indent << "RunLength\n";
}
else // this->OutputStyle == VTK_STYLE_POLYGONALIZE
{
os << indent << "Polygonalize\n";
}
os << indent << "Color Mode: ";
if (this->ColorMode == VTK_STYLE_PIXELIZE)
{
os << indent << "LUT\n";
}
else // this->ColorMode == VTK_STYLE_POLYGONALIZE
{
os << indent << "Linear256\n";
}
os << indent << "Smoothing: " << (this->Smoothing ? "On\n" : "Off\n");
os << indent << "Number of Smoothing Iterations: " << this->NumberOfSmoothingIterations << "\n";
os << indent << "Decimation: " << (this->Decimation ? "On\n" : "Off\n");
os << indent << "Decimation Error: " << (this->DecimationError ? "On\n" : "Off\n");
os << indent << "Error: " << this->Error << "\n";
os << indent << "Sub-Image Size: " << this->SubImageSize << "\n";
if (this->LookupTable)
{
os << indent << "LookupTable:\n";
this->LookupTable->PrintSelf(os, indent.GetNextIndent());
}
else
{
os << indent << "LookupTable: (none)\n";
}
}
//--------------------------private helper functions---------------------------
// Determines whether two pixels are the same color
int vtkImageToPolyDataFilter::IsSameColor(unsigned char* p1, unsigned char* p2)
{
int d2 = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]) +
(p1[2] - p2[2]) * (p1[2] - p2[2]);
return (d2 > this->Error ? 0 : 1);
}
unsigned char* vtkImageToPolyDataFilter::GetColor(unsigned char* rgb)
{
// round to nearest value
int red = (rgb[0] + 16) / 32;
red = (red > 7 ? 7 : red);
int green = (rgb[1] + 16) / 32;
green = (green > 7 ? 7 : green);
int blue = (rgb[2] + 32) / 64;
blue = (blue > 3 ? 3 : blue);
return this->Table->GetPointer(3 * (red + green * 8 + blue * 64));
}
void vtkImageToPolyDataFilter::GetIJ(int id, int& i, int& j, int dims[2])
{
i = id % dims[0];
j = id / dims[0];
}
// Get the left-right-top-bottom neighboring pixels of a given pixel
// The method has been modified to return right neighbor (mode==0);
// or top neighbor (mode==1) or all neighbors (mode==2).
int vtkImageToPolyDataFilter::GetNeighbors(
unsigned char* ptr, int& i, int& j, int dims[2], unsigned char* neighbors[4], int mode)
{
int numNeis = 0;
if (mode == 0)
{
if ((i + 1) < dims[0])
{
neighbors[numNeis++] = ptr + 3; // jump over rgb
}
if ((i - 1) >= 0)
{
neighbors[numNeis++] = ptr - 3; // jump over rgb
}
}
else if (mode == 1)
{
if ((j + 1) < dims[1])
{
neighbors[numNeis++] = ptr + 3 * dims[0];
}
}
else
{
if ((i + 1) < dims[0])
{
neighbors[numNeis++] = ptr + 3; // jump over rgb
}
if ((i - 1) >= 0)
{
neighbors[numNeis++] = ptr - 3;
}
if ((j + 1) < dims[1])
{
neighbors[numNeis++] = ptr + 3 * dims[0];
}
if ((j - 1) >= 0)
{
neighbors[numNeis++] = ptr - 3 * dims[0];
}
}
return numNeis;
}
// Marks connected regions with different colors.
int vtkImageToPolyDataFilter::ProcessImage(vtkUnsignedCharArray* scalars, int dims[2])
{
int numPixels = dims[0] * dims[1];
vtkIdList *wave, *wave2, *tmpWave;
int numIds, regionNumber, i, j, k, id, x, y, numNeighbors;
unsigned char *neighbors[4], *ptr;
unsigned char* pixels = scalars->GetPointer(0);
// Collect groups of pixels together into similar colored regions. These
// will be eventually grouped into polygons and/or lines.
//
// mark all pixels unvisited
regionNumber = -1;
this->Visited = new int[numPixels];
memset(this->Visited, (int)-1, numPixels * sizeof(int));
// set up the connected traversal
wave = vtkIdList::New();
wave->Allocate(static_cast<int>(numPixels / 4.0), static_cast<int>(numPixels / 4.0));
wave2 = vtkIdList::New();
wave2->Allocate(static_cast<int>(numPixels / 4.0), static_cast<int>(numPixels / 4.0));
// visit connected pixels. Pixels are connected if they are topologically
// adjacent and they have "equal" color values.
for (i = 0; i < numPixels; i++)
{
if (this->Visited[i] == -1)
{ // start a connected wave
this->Visited[i] = ++regionNumber;
ptr = pixels + 3 * i;
this->PolyColors->InsertValue(3 * regionNumber, ptr[0]); // assign color
this->PolyColors->InsertValue(3 * regionNumber + 1, ptr[1]);
this->PolyColors->InsertValue(3 * regionNumber + 2, ptr[2]);
wave->Reset();
wave2->Reset();
// To prevent creating polygons with inner loops, we're going to start
// the wave as a "vertical" stack of pixels, and then propagate the
// wave horizontally only.
wave->InsertId(0, i);
this->GetIJ(i, x, y, dims);
while ((numNeighbors = this->GetNeighbors(ptr, x, y, dims, neighbors, 1)))
{
id = (neighbors[0] - pixels) / 3;
if (this->Visited[id] == -1 && this->IsSameColor(ptr, neighbors[0]))
{
this->Visited[id] = regionNumber;
wave->InsertNextId(id);
ptr = pixels + 3 * id;
this->GetIJ(id, x, y, dims);
}
else
{
break;
}
}
// Okay, defined vertical wave, now propagate horizontally
numIds = wave->GetNumberOfIds();
while (numIds > 0)
{
for (j = 0; j < numIds; j++) // propagate wave
{
id = wave->GetId(j);
ptr = pixels + 3 * id;
this->GetIJ(id, x, y, dims);
numNeighbors = this->GetNeighbors(ptr, x, y, dims, neighbors, 0);
for (k = 0; k < numNeighbors; k++)
{
id = (neighbors[k] - pixels) / 3;
if (this->Visited[id] == -1 && this->IsSameColor(ptr, neighbors[k]))
{
this->Visited[id] = regionNumber;
wave2->InsertNextId(id);
}
} // for each pixel neighbor
} // for pixels left in wave
numIds = wave2->GetNumberOfIds();
tmpWave = wave;
wave = wave2;
wave2 = tmpWave;
wave2->Reset();
} // while still propagating
} // if not, start wave
} // for all pixels
wave->Delete();
wave2->Delete();
return regionNumber + 1;
}
// Create polygons and place into output
void vtkImageToPolyDataFilter::GeneratePolygons(vtkPolyData* edges, int vtkNotUsed(numPolys),
vtkPolyData* output, vtkUnsignedCharArray* polyColors, vtkUnsignedCharArray* pointDescr)
{
vtkCellArray *newPolys, *inPolys;
int i, numPts;
const vtkIdType* pts = nullptr;
vtkIdType npts = 0;
// Copy the points via reference counting
//
output->SetPoints(edges->GetPoints());
// Create the polygons - points may have been decimated so these
// points have to be culled.
//
inPolys = edges->GetPolys();
newPolys = vtkCellArray::New();
newPolys->AllocateCopy(inPolys);
for (inPolys->InitTraversal(); inPolys->GetNextCell(npts, pts);)
{
newPolys->InsertNextCell(0);
numPts = 0;
for (i = 0; i < npts; i++)
{
if (pointDescr->GetValue(pts[i]) != 2)
{
newPolys->InsertCellPoint(pts[i]);
numPts++;
}
}
newPolys->UpdateCellCount(numPts);
}
output->SetPolys(newPolys);
newPolys->Delete();
output->GetCellData()->SetScalars(polyColors);
}
// Uses clipping approach to build the polygon edges
int vtkImageToPolyDataFilter::BuildEdges(vtkUnsignedCharArray* vtkNotUsed(pixels), int dims[3],
double origin[3], double spacing[3], vtkUnsignedCharArray* pointDescr, vtkPolyData* edges)
{
double x[3];
int i, j, edgeCount;
vtkIdType ptId, p0, p1, p2, p3, startId, attrId, id[8], pts[4];
vtkCellArray* edgeConn = edges->GetLines();
vtkPoints* points = edges->GetPoints();
// Build edges around perimeter of image. Note that the point ids
// The first four points are the image corners and are inserted and
// marked so that they can't be moved during smoothing.
points->InsertPoint(0, origin);
pointDescr->InsertValue(0, 1);
// Keep track of the polygons that use each edge as well as associated
// intersection points on edge (if any)
this->EdgeTable = vtkEdgeTable::New();
this->EdgeTable->InitEdgeInsertion(dims[0] * dims[1], 1);
this->EdgeUseTable = vtkEdgeTable::New();
this->EdgeUseTable->InitEdgeInsertion(dims[0] * dims[1], 1);
this->EdgeUses = vtkIntArray::New();
this->EdgeUses->SetNumberOfComponents(2);
this->EdgeUses->Allocate(4 * dims[0] * dims[1], dims[0] * dims[1]);
// Generate corner points of image
x[0] = origin[0] + (dims[0] - 1) * spacing[0];
x[1] = origin[1];
x[2] = 0.0;
points->InsertPoint(1, x);
pointDescr->InsertValue(1, 1);
x[0] = origin[0] + (dims[0] - 1) * spacing[0];
x[1] = origin[1] + (dims[1] - 1) * spacing[1];
x[2] = 0.0;
points->InsertPoint(2, x);
pointDescr->InsertValue(2, 1);
x[0] = origin[0];
x[1] = origin[1] + (dims[1] - 1) * spacing[1];
x[2] = 0.0;
points->InsertPoint(3, x);
pointDescr->InsertValue(3, 1);
// Let's create perimeter edges - bottom x edge
startId = 0;
x[1] = origin[1];
for (i = 0; i < (dims[0] - 1); i++)
{
p0 = i;
p1 = i + 1;
if (this->Visited[p0] != this->Visited[p1])
{
x[0] = origin[0] + i * spacing[0] + 0.5 * spacing[0];
ptId = points->InsertNextPoint(x);
this->EdgeTable->InsertEdge(p0, p1, ptId);
pointDescr->InsertValue(ptId, 1); // can't be smoothed
edgeConn->InsertNextCell(2);
edgeConn->InsertCellPoint(startId);
edgeConn->InsertCellPoint(ptId);
attrId = this->EdgeUseTable->InsertEdge(startId, ptId);
this->EdgeUses->InsertValue(2 * attrId, this->Visited[p0]);
this->EdgeUses->InsertValue(2 * attrId + 1, -1);
startId = ptId;
}
}
edgeConn->InsertNextCell(2); // finish off the edge
edgeConn->InsertCellPoint(startId);
edgeConn->InsertCellPoint(1);
attrId = this->EdgeUseTable->InsertEdge(startId, 1);
this->EdgeUses->InsertValue(2 * attrId, this->Visited[dims[0] - 1]);
this->EdgeUses->InsertValue(2 * attrId + 1, -1);
// Let's create perimeter edges - top x edge
startId = 3;
x[1] = origin[1] + (dims[1] - 1) * spacing[1];
for (i = 0; i < (dims[0] - 1); i++)
{
p0 = i + dims[0] * (dims[1] - 1);
p1 = p0 + 1;
if (this->Visited[p0] != this->Visited[p1])
{
x[0] = origin[0] + i * spacing[0] + 0.5 * spacing[0];
ptId = points->InsertNextPoint(x);
this->EdgeTable->InsertEdge(p0, p1, ptId);
pointDescr->InsertValue(ptId, 1); // can't be smoothed
edgeConn->InsertNextCell(2);
edgeConn->InsertCellPoint(startId);
edgeConn->InsertCellPoint(ptId);
attrId = this->EdgeUseTable->InsertEdge(startId, ptId);
this->EdgeUses->InsertValue(2 * attrId, this->Visited[p0]);
this->EdgeUses->InsertValue(2 * attrId + 1, -1);
startId = ptId;
}
}
edgeConn->InsertNextCell(2); // finish off the edge
edgeConn->InsertCellPoint(startId);
edgeConn->InsertCellPoint(2);
attrId = this->EdgeUseTable->InsertEdge(startId, 2);
this->EdgeUses->InsertValue(2 * attrId, this->Visited[dims[1] * dims[0] - 1]);
this->EdgeUses->InsertValue(2 * attrId + 1, -1);
// Let's create perimeter edges - min y edge
startId = 0;
x[0] = origin[0];
for (j = 0; j < (dims[1] - 1); j++)
{
p0 = j * dims[0];
p1 = p0 + dims[0];
if (this->Visited[p0] != this->Visited[p1])
{
x[1] = origin[1] + j * spacing[1] + 0.5 * spacing[1];
ptId = points->InsertNextPoint(x);
this->EdgeTable->InsertEdge(p0, p1, ptId);
pointDescr->InsertValue(ptId, 1); // can't be smoothed
edgeConn->InsertNextCell(2);
edgeConn->InsertCellPoint(startId);
edgeConn->InsertCellPoint(ptId);
attrId = this->EdgeUseTable->InsertEdge(startId, ptId);
this->EdgeUses->InsertValue(2 * attrId, this->Visited[p0]);
this->EdgeUses->InsertValue(2 * attrId + 1, -1);
startId = ptId;
}
}
edgeConn->InsertNextCell(2); // finish off the edge
edgeConn->InsertCellPoint(startId);
edgeConn->InsertCellPoint(3);
attrId = this->EdgeUseTable->InsertEdge(startId, 3);
this->EdgeUses->InsertValue(2 * attrId, this->Visited[(dims[1] - 1) * dims[0]]);
this->EdgeUses->InsertValue(2 * attrId + 1, -1);
// Let's create perimeter edges - max y edge
startId = 1;
x[0] = origin[0] + (dims[0] - 1) * spacing[0];
for (j = 0; j < (dims[1] - 1); j++)
{
p0 = j * dims[0] + (dims[0] - 1);
p1 = p0 + dims[0];
if (this->Visited[p0] != this->Visited[p1])
{
x[1] = origin[1] + j * spacing[1] + 0.5 * spacing[1];
ptId = points->InsertNextPoint(x);
this->EdgeTable->InsertEdge(p0, p1, ptId);
pointDescr->InsertValue(ptId, 1); // can't be smoothed
edgeConn->InsertNextCell(2);
edgeConn->InsertCellPoint(startId);
edgeConn->InsertCellPoint(ptId);
attrId = this->EdgeUseTable->InsertEdge(startId, ptId);
this->EdgeUses->InsertValue(2 * attrId, this->Visited[p0]);
this->EdgeUses->InsertValue(2 * attrId + 1, -1);
startId = ptId;
}
}
edgeConn->InsertNextCell(2); // finish off the edge
edgeConn->InsertCellPoint(startId);
edgeConn->InsertCellPoint(2);
attrId = this->EdgeUseTable->InsertEdge(startId, 2);
this->EdgeUses->InsertValue(2 * attrId, this->Visited[dims[1] * dims[0] - 1]);
this->EdgeUses->InsertValue(2 * attrId + 1, -1);
// Loop over all edges generating intersection points and outer boundary
// edge segments.
//
for (j = 1; j < (dims[1] - 1); j++) // loop over all x edges (except boundary)
{
x[1] = origin[1] + j * spacing[1];
for (i = 0; i < (dims[0] - 1); i++)
{
p0 = i + j * dims[0];
p1 = p0 + 1;
if (this->Visited[p0] != this->Visited[p1])
{
x[0] = origin[0] + i * spacing[0] + 0.5 * spacing[0];
ptId = points->InsertNextPoint(x);
this->EdgeTable->InsertEdge(p0, p1, ptId);
pointDescr->InsertValue(ptId, 0);
}