/
itkImageBufferRange.h
686 lines (556 loc) · 21.9 KB
/
itkImageBufferRange.h
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
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkImageBufferRange_h
#define itkImageBufferRange_h
#include <cassert>
#include <cstddef> // For ptrdiff_t.
#include <iterator> // For random_access_iterator_tag.
#include <limits>
#include <type_traits> // For conditional, enable_if, is_same, and is_const.
#include "itkMacro.h" // For itkNotUsed.
#include "itkDefaultPixelAccessor.h"
#include "itkDefaultPixelAccessorFunctor.h"
#include "itkDefaultVectorPixelAccessor.h"
#include "itkDefaultVectorPixelAccessorFunctor.h"
#include "itkImageRegion.h"
namespace itk
{
/**
* \class ImageBufferRange
* Modern C++11 range to iterate over the pixels of an image.
* Designed to conform to Standard C++ Iterator requirements,
* so that it can be used in range-based for loop, and passed to
* Standard C++ algorithms.
*
* The following example adds 42 to each pixel, using a range-based for loop:
\code
ImageBufferRange range{ *image };
for (auto&& pixel : range)
{
pixel = pixel + 42;
}
\endcode
*
* The following example prints the values of the pixels:
\code
for (const auto pixel : range)
{
std::cout << pixel << std::endl;
}
\endcode
*
* \author Niels Dekker, LKEB, Leiden University Medical Center
*
* \see ImageIterator
* \see ImageConstIterator
* \see IndexRange
* \see ShapedImageNeighborhoodRange
* \ingroup ImageIterators
* \ingroup ITKCommon
*/
template <typename TImage>
class ImageBufferRange final
{
private:
using PixelType = typename TImage::PixelType;
using InternalPixelType = typename TImage::InternalPixelType;
using AccessorFunctorType = typename TImage::AccessorFunctorType;
// Tells whether or not this range supports direct pixel access. If it does,
// iterator::operator*() returns a reference to the internally stored pixel,
// otherwise iterator::operator*() returns a proxy, which internally uses the
// AccessorFunctor of the image to access the pixel indirectly.
static constexpr bool SupportsDirectPixelAccess =
std::is_same_v<PixelType, InternalPixelType> &&
std::is_same_v<typename TImage::AccessorType, DefaultPixelAccessor<PixelType>> &&
std::is_same_v<AccessorFunctorType, DefaultPixelAccessorFunctor<std::remove_const_t<TImage>>>;
// Tells whether or not this range is using a pointer as iterator.
static constexpr bool UsingPointerAsIterator = SupportsDirectPixelAccess;
struct EmptyAccessorFunctor
{};
using OptionalAccessorFunctorType =
std::conditional_t<SupportsDirectPixelAccess, EmptyAccessorFunctor, AccessorFunctorType>;
// PixelProxy: internal class that aims to act like a reference to a pixel:
// It acts either like 'PixelType &' or like 'const PixelType &', depending
// on its boolean template argument, VIsConst.
// The proxy retrieves the pixel value using the AccessorFunctor from the image.
// Note: the extra TDummy argument aims to fix AppleClang 6.0.0.6000056 error
// "explicit specialization of 'PixelProxy'"and GCC 5.4.0 error "explicit
// specialization in non-namespace scope".
template <bool VIsConst, typename TDummy = void>
class PixelProxy
{};
// PixelProxy specialization for const pixel types:
// acts like 'const PixelType &'
template <typename TDummy>
class PixelProxy<true, TDummy> final
{
private:
// Reference to the internal representation of the pixel, located in the image buffer.
const InternalPixelType & m_InternalPixel;
// The accessor functor of the image.
const AccessorFunctorType m_AccessorFunctor;
public:
// Deleted member functions:
PixelProxy() = delete;
PixelProxy &
operator=(const PixelProxy &) = delete;
// Explicitly-defaulted member functions:
PixelProxy(const PixelProxy &) noexcept = default;
~PixelProxy() = default;
// Constructor, called directly by operator*() of the iterator class.
PixelProxy(const InternalPixelType & internalPixel, const AccessorFunctorType & accessorFunctor) noexcept
: m_InternalPixel{ internalPixel }
, m_AccessorFunctor(accessorFunctor)
{}
// Allows implicit conversion from non-const to const proxy.
PixelProxy(const PixelProxy<false> & pixelProxy) noexcept
: m_InternalPixel{ pixelProxy.m_InternalPixel }
, m_AccessorFunctor{ pixelProxy.m_AccessorFunctor }
{}
// Conversion operator.
operator PixelType() const noexcept { return m_AccessorFunctor.Get(m_InternalPixel); }
};
// PixelProxy specialization for non-const pixel types:
// acts like 'PixelType &'.
template <typename TDummy>
class PixelProxy<false, TDummy> final
{
private:
// The const proxy is a friend, to ease implementing conversion from
// a non-const proxy to a const proxy.
friend class PixelProxy<true>;
// Reference to the internal representation of the pixel, located in the image buffer.
InternalPixelType & m_InternalPixel;
// The accessor functor of the image.
const AccessorFunctorType m_AccessorFunctor;
public:
// Deleted member functions:
PixelProxy() = delete;
// Explicitly-defaulted member functions:
~PixelProxy() = default;
PixelProxy(const PixelProxy &) noexcept = default;
// Constructor, called directly by operator*() of the iterator class.
explicit PixelProxy(InternalPixelType & internalPixel, const AccessorFunctorType & accessorFunctor) noexcept
: m_InternalPixel{ internalPixel }
, m_AccessorFunctor(accessorFunctor)
{}
// Conversion operator.
operator PixelType() const noexcept { return m_AccessorFunctor.Get(m_InternalPixel); }
// Operator to assign a pixel value to the proxy.
PixelProxy &
operator=(const PixelType & pixelValue) noexcept
{
m_AccessorFunctor.Set(m_InternalPixel, pixelValue);
return *this;
}
// Copy-assignment operator.
PixelProxy &
operator=(const PixelProxy & pixelProxy) noexcept
{
// Note that this assignment operator only copies the pixel value.
// That is the normal behavior when a reference is assigned to another.
const PixelType pixelValue = pixelProxy;
*this = pixelValue;
return *this;
}
friend void
swap(PixelProxy lhs, PixelProxy rhs) noexcept
{
const auto lhsPixelValue = lhs.m_AccessorFunctor.Get(lhs.m_InternalPixel);
const auto rhsPixelValue = rhs.m_AccessorFunctor.Get(rhs.m_InternalPixel);
// Swap only the pixel values, not the image buffer pointers!
lhs.m_AccessorFunctor.Set(lhs.m_InternalPixel, rhsPixelValue);
rhs.m_AccessorFunctor.Set(rhs.m_InternalPixel, lhsPixelValue);
}
};
/**
* \class QualifiedIterator
* Iterator class that is either 'const' or non-const qualified.
* A non-const qualified instantiation of this template allows the pixel that
* it points to, to be modified. A const qualified instantiation does not.
*
* \note The definition of this class is private. Please use its type alias
* ImageBufferRange::iterator, or ImageBufferRange::const_iterator!
* \see ImageBufferRange
* \ingroup ImageIterators
* \ingroup ITKCommon
*/
template <bool VIsConst>
class QualifiedIterator final
{
private:
// Const and non-const iterators are friends, in order to implement the
// constructor that allow conversion from non-const to const iterator.
friend class QualifiedIterator<!VIsConst>;
// ImageBufferRange is a friend, as it should be the only one that can
// directly use the private constructor of the iterator.
friend class ImageBufferRange;
// Image type class that is either 'const' or non-const qualified, depending on QualifiedIterator and TImage.
using QualifiedImageType = std::conditional_t<VIsConst, const TImage, TImage>;
static constexpr bool IsImageTypeConst = std::is_const_v<QualifiedImageType>;
using QualifiedInternalPixelType = std::conditional_t<IsImageTypeConst, const InternalPixelType, InternalPixelType>;
// Pixel type class that is either 'const' or non-const qualified, depending on QualifiedImageType.
using QualifiedPixelType = std::conditional_t<IsImageTypeConst, const PixelType, PixelType>;
// Wraps a reference to a pixel.
class PixelReferenceWrapper final
{
public:
// Wraps the pixel reference that is specified by the first argument.
// Note: the second parameter is unused, but it is there just to support
// the use case of iterator::operator*(), which uses either
// PixelReferenceWrapper or PixelProxy, interchangeable, in a generic way.
// (PixelProxy has an explicit constructor for which the second parameter
// is its essential AccessorFunctor parameter!)
explicit PixelReferenceWrapper(QualifiedPixelType & pixel,
EmptyAccessorFunctor itkNotUsed(accessorFunctor)) noexcept
: m_Pixel(pixel)
{}
// Converts implicitly to a reference to the pixel.
operator QualifiedPixelType &() const noexcept { return m_Pixel; }
private:
QualifiedPixelType & m_Pixel;
};
// QualifiedIterator data members (strictly private):
// The accessor functor of the image.
OptionalAccessorFunctorType m_OptionalAccessorFunctor;
// Pointer to the current pixel.
QualifiedInternalPixelType * m_InternalPixelPointer = nullptr;
// Private constructor, used to create the begin and the end iterator of a range.
// Only used by its friend class ImageBufferRange.
QualifiedIterator(const OptionalAccessorFunctorType & accessorFunctor,
QualifiedInternalPixelType * const internalPixelPointer) noexcept
: // Note: Use parentheses instead of curly braces to initialize data members,
// to avoid AppleClang 6.0.0.6000056 compilation error, "no viable conversion..."
m_OptionalAccessorFunctor(accessorFunctor)
, m_InternalPixelPointer{ internalPixelPointer }
{}
public:
// Types conforming the iterator requirements of the C++ standard library:
using difference_type = ptrdiff_t;
using value_type = PixelType;
using reference = std::conditional_t<SupportsDirectPixelAccess, QualifiedPixelType &, PixelProxy<IsImageTypeConst>>;
using pointer = QualifiedPixelType *;
using iterator_category = std::random_access_iterator_tag;
/** Default-constructor, as required for any C++11 Forward Iterator. Offers
* the guarantee added to the C++14 Standard: "value-initialized iterators
* may be compared and shall compare equal to other value-initialized
* iterators of the same type."
*
* \note The other five "special member functions" are defaulted implicitly,
* following the C++ "Rule of Zero".
*/
QualifiedIterator() = default;
/** Constructor for implicit conversion from non-const to const iterator. */
template <bool VIsArgumentConst, typename = std::enable_if_t<VIsConst && !VIsArgumentConst>>
QualifiedIterator(const QualifiedIterator<VIsArgumentConst> & arg) noexcept
: // Note: Use parentheses instead of curly braces to initialize data members,
// to avoid AppleClang 6.0.0.6000056 compilation error, "no viable conversion..."
m_OptionalAccessorFunctor(arg.m_OptionalAccessorFunctor)
, m_InternalPixelPointer{ arg.m_InternalPixelPointer }
{}
/** Returns a reference to the current pixel. */
reference operator*() const noexcept
{
assert(m_InternalPixelPointer != nullptr);
using PixelWrapper = std::conditional_t<SupportsDirectPixelAccess, PixelReferenceWrapper, reference>;
return PixelWrapper{ *m_InternalPixelPointer, m_OptionalAccessorFunctor };
}
/** Prefix increment ('++it'). */
QualifiedIterator &
operator++() noexcept
{
assert(m_InternalPixelPointer != nullptr);
++m_InternalPixelPointer;
return *this;
}
/** Postfix increment ('it++').
* \note Usually prefix increment ('++it') is preferable. */
QualifiedIterator
operator++(int) noexcept
{
auto result = *this;
++(*this);
return result;
}
/** Prefix decrement ('--it'). */
QualifiedIterator &
operator--() noexcept
{
assert(m_InternalPixelPointer != nullptr);
--m_InternalPixelPointer;
return *this;
}
/** Postfix increment ('it--').
* \note Usually prefix increment ('--it') is preferable. */
QualifiedIterator
operator--(int) noexcept
{
auto result = *this;
--(*this);
return result;
}
/** Returns (it1 == it2) for iterators it1 and it2. Note that these iterators
* should be from the same range. This operator does not support comparing iterators
* from different ranges. */
friend bool
operator==(const QualifiedIterator & lhs, const QualifiedIterator & rhs) noexcept
{
return lhs.m_InternalPixelPointer == rhs.m_InternalPixelPointer;
}
/** Returns (it1 != it2) for iterators it1 and it2. */
friend bool
operator!=(const QualifiedIterator & lhs, const QualifiedIterator & rhs) noexcept
{
// Implemented just like the corresponding std::rel_ops operator.
return !(lhs == rhs);
}
/** Returns (it1 < it2) for iterators it1 and it2. */
friend bool
operator<(const QualifiedIterator & lhs, const QualifiedIterator & rhs) noexcept
{
return lhs.m_InternalPixelPointer < rhs.m_InternalPixelPointer;
}
/** Returns (it1 > it2) for iterators it1 and it2. */
friend bool
operator>(const QualifiedIterator & lhs, const QualifiedIterator & rhs) noexcept
{
// Implemented just like the corresponding std::rel_ops operator.
return rhs < lhs;
}
/** Returns (it1 <= it2) for iterators it1 and it2. */
friend bool
operator<=(const QualifiedIterator & lhs, const QualifiedIterator & rhs) noexcept
{
// Implemented just like the corresponding std::rel_ops operator.
return !(rhs < lhs);
}
/** Returns (it1 >= it2) for iterators it1 and it2. */
friend bool
operator>=(const QualifiedIterator & lhs, const QualifiedIterator & rhs) noexcept
{
// Implemented just like the corresponding std::rel_ops operator.
return !(lhs < rhs);
}
/** Does (it += d) for iterator 'it' and integer value 'n'. */
friend QualifiedIterator &
operator+=(QualifiedIterator & it, const difference_type n) noexcept
{
it.m_InternalPixelPointer += n;
return it;
}
/** Does (it -= d) for iterator 'it' and integer value 'n'. */
friend QualifiedIterator &
operator-=(QualifiedIterator & it, const difference_type n) noexcept
{
it += (-n);
return it;
}
/** Returns (it1 - it2) for iterators it1 and it2. */
friend difference_type
operator-(const QualifiedIterator & lhs, const QualifiedIterator & rhs) noexcept
{
return lhs.m_InternalPixelPointer - rhs.m_InternalPixelPointer;
}
/** Returns (it + n) for iterator 'it' and integer value 'n'. */
friend QualifiedIterator
operator+(QualifiedIterator it, const difference_type n) noexcept
{
return it += n;
}
/** Returns (n + it) for iterator 'it' and integer value 'n'. */
friend QualifiedIterator
operator+(const difference_type n, QualifiedIterator it) noexcept
{
return it += n;
}
/** Returns (it - n) for iterator 'it' and integer value 'n'. */
friend QualifiedIterator
operator-(QualifiedIterator it, const difference_type n) noexcept
{
return it += (-n);
}
/** Returns it[n] for iterator 'it' and integer value 'n'. */
reference operator[](const difference_type n) const noexcept { return *(*this + n); }
};
static constexpr bool IsImageTypeConst = std::is_const_v<TImage>;
using QualifiedInternalPixelType = std::conditional_t<IsImageTypeConst, const InternalPixelType, InternalPixelType>;
class AccessorFunctorInitializer final
{
private:
TImage & m_Image;
public:
explicit AccessorFunctorInitializer(TImage & image) noexcept
: m_Image(image)
{}
operator EmptyAccessorFunctor() const noexcept { return {}; }
operator AccessorFunctorType() const noexcept
{
AccessorFunctorType result = {};
result.SetPixelAccessor(m_Image.GetPixelAccessor());
result.SetBegin(m_Image.TImage::GetBufferPointer());
return result;
}
};
// Helper class for begin() and end(), to ease proper initialization of an
// ImageBufferRange iterator (either a 'QualifiedIterator' or a raw pixel pointer).
class IteratorInitializer final
{
private:
OptionalAccessorFunctorType m_OptionalAccessorFunctor;
QualifiedInternalPixelType * m_InternalPixelPointer;
public:
explicit IteratorInitializer(OptionalAccessorFunctorType optionalAccessorFunctor,
QualifiedInternalPixelType * internalPixelPointer) noexcept
: m_OptionalAccessorFunctor(optionalAccessorFunctor)
, m_InternalPixelPointer(internalPixelPointer)
{}
// Converts to a 'QualifiedIterator' object.
template <bool VIsConst>
operator QualifiedIterator<VIsConst>() const noexcept
{
return QualifiedIterator<VIsConst>{ m_OptionalAccessorFunctor, m_InternalPixelPointer };
}
// Converts to a raw pixel pointer.
operator QualifiedInternalPixelType *() const noexcept { return m_InternalPixelPointer; }
};
// ImageBufferRange data members (strictly private):
// The accessor functor of the image.
OptionalAccessorFunctorType m_OptionalAccessorFunctor;
// Pointer to the buffer of the image.
QualifiedInternalPixelType * m_ImageBufferPointer = nullptr;
// Image size.
SizeValueType m_NumberOfPixels = 0;
public:
using const_iterator = std::conditional_t<UsingPointerAsIterator, const InternalPixelType *, QualifiedIterator<true>>;
using iterator =
std::conditional_t<UsingPointerAsIterator, QualifiedInternalPixelType *, QualifiedIterator<IsImageTypeConst>>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
/** Explicitly-defaulted default-constructor. Constructs an empty range.
* \note The other five "special member functions" (copy-constructor,
* copy-assignment operator, move-constructor, move-assignment operator,
* and destructor) are defaulted implicitly, following the C++ "Rule of Zero".
*/
ImageBufferRange() = default;
/** Specifies a range of the pixels of an image.
* \note This constructor supports class template argument deduction (CTAD).
*/
explicit ImageBufferRange(TImage & image)
: // Note: Use parentheses instead of curly braces to initialize data members,
// to avoid AppleClang 6.0.0.6000056 compile errors, "no viable conversion..."
m_OptionalAccessorFunctor(AccessorFunctorInitializer{ image })
, m_ImageBufferPointer{ image.TImage::GetBufferPointer() }
, m_NumberOfPixels{ image.TImage::GetBufferedRegion().GetNumberOfPixels() }
{}
/** Returns an iterator to the first pixel. */
iterator
begin() const noexcept
{
return IteratorInitializer{ m_OptionalAccessorFunctor, m_ImageBufferPointer };
}
/** Returns an 'end iterator' for this range. */
iterator
end() const noexcept
{
return IteratorInitializer{
m_OptionalAccessorFunctor,
m_ImageBufferPointer + m_NumberOfPixels,
};
}
/** Returns a const iterator to the first pixel.
* Provides only read-only access to the pixel data. */
const_iterator
cbegin() const noexcept
{
return this->begin();
}
/** Returns a const 'end iterator' for this range. */
const_iterator
cend() const noexcept
{
return this->end();
}
/** Returns a reverse 'begin iterator' for this range. */
reverse_iterator
rbegin() const noexcept
{
return reverse_iterator(this->end());
}
/** Returns a reverse 'end iterator' for this range. */
reverse_iterator
rend() const noexcept
{
return reverse_iterator(this->begin());
}
/** Returns a const reverse 'begin iterator' for this range. */
const_reverse_iterator
crbegin() const noexcept
{
return this->rbegin();
}
/** Returns a const reverse 'end iterator' for this range. */
const_reverse_iterator
crend() const noexcept
{
return this->rend();
}
/** Returns the size of the range, that is the number of pixels. */
size_t
size() const noexcept
{
return m_NumberOfPixels;
}
/** Tells whether the range is empty. */
bool
empty() const noexcept
{
return m_NumberOfPixels == 0;
}
/** Subscript operator. Allows random access, to the nth pixel.
* \note The return type QualifiedIterator<false>::reference is equivalent to
* iterator::reference.
*/
typename QualifiedIterator<false>::reference operator[](const size_t n) const noexcept
{
assert(n < this->size());
assert(n <= static_cast<size_t>(std::numeric_limits<ptrdiff_t>::max()));
return this->begin()[static_cast<ptrdiff_t>(n)];
}
};
// Deduction guide to avoid compiler warnings (-wctad-maybe-unsupported) when using class template argument deduction.
template <typename TImage>
ImageBufferRange(TImage &)->ImageBufferRange<TImage>;
/** Creates a range to iterate over the pixels of the specified image.
* Returns an empty range when the specified argument is a nullptr (which
* is a valid use case).
*/
template <typename TImage>
ImageBufferRange<TImage>
MakeImageBufferRange(TImage * const image)
{
if (image == nullptr)
{
return {};
}
else
{
return ImageBufferRange<TImage>{ *image };
}
}
} // namespace itk
#endif