File: OneDimensionalInPlaceAccumulateFilter.txx

package info (click to toggle)
itksnap 3.6.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 22,136 kB
  • sloc: cpp: 91,089; ansic: 1,994; sh: 327; makefile: 16
file content (584 lines) | stat: -rw-r--r-- 19,225 bytes parent folder | download
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
/*=========================================================================

  Program:   ALFABIS fast medical image registration programs
  Language:  C++
  Website:   github.com/pyushkevich/greedy
  Copyright (c) Paul Yushkevich, University of Pennsylvania. All rights reserved.

  This program is part of ALFABIS: Adaptive Large-Scale Framework for
  Automatic Biomedical Image Segmentation.

  ALFABIS development is funded by the NIH grant R01 EB017255.

  ALFABIS is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  ALFABIS 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 ALFABIS.  If not, see <http://www.gnu.org/licenses/>.

=========================================================================*/
#include "OneDimensionalInPlaceAccumulateFilter.h"
#include <itkImageLinearIteratorWithIndex.h>
#include "ImageRegionConstIteratorWithIndexOverride.h"


template <class TInputImage>
OneDimensionalInPlaceAccumulateFilter<TInputImage>
::OneDimensionalInPlaceAccumulateFilter()
{
  m_Radius = 0;
  m_Dimension = 0;
  m_ComponentOffsetFront = m_ComponentOffsetBack = 0;
  m_Splitter = SplitterType::New();
  this->InPlaceOn();
}

template <class TInputImage>
const itk::ImageRegionSplitterBase *
OneDimensionalInPlaceAccumulateFilter<TInputImage>
::GetImageRegionSplitter(void) const
{
  m_Splitter->SetDirection(m_Dimension);
  return m_Splitter;
}


template <class TInputImage>
void
OneDimensionalInPlaceAccumulateFilter<TInputImage>
::SetComponentRange(int num_ignored_at_start, int num_ignored_at_end)
{
  m_ComponentOffsetFront = num_ignored_at_start;
  m_ComponentOffsetBack = num_ignored_at_end;
  this->Modified();
}

/**
 * This worker class is defined to allow partial specialization of the ThreadedGenerateData
 * based on the pixel type (float/double)
 */
template <class TPixel, class TInputImage>
class OneDimensionalInPlaceAccumulateFilterWorker
{
public:
  typedef OneDimensionalInPlaceAccumulateFilter<TInputImage> FilterType;
  typedef typename FilterType::OutputImageRegionType OutputImageRegionType;
  typedef typename FilterType::InputImageType InputImageType;
  static void ThreadedGenerateData(FilterType *filter,
                                   const OutputImageRegionType & outputRegionForThread,
                                   itk::ThreadIdType threadId);
};


template <class TPixel, class TInputImage>
void
OneDimensionalInPlaceAccumulateFilterWorker<TPixel, TInputImage>
::ThreadedGenerateData(FilterType *filter,
                       const OutputImageRegionType & outputRegionForThread,
                       itk::ThreadIdType threadId)
{
  // Get filter parameters
  int radius = filter->GetRadius();
  int dimension = filter->GetDimension();

  // Get the image
  InputImageType *image = const_cast<InputImageType *>(filter->GetInput());

  // Set up the iterator that will go through all the lines in the
  // output region. We assume that the lines span the whole length of
  // the input, i.e., the threading direction does not interfere
  typedef itk::ImageLinearIteratorWithIndex<TInputImage> IteratorBaseType;
  typedef IteratorExtenderWithOffset<IteratorBaseType> IteratorType;

  // This is the line iterator, although for even greater speed we operate
  // directly on pointers, so we only use it's NextLine functionality()
  IteratorType itLine(image, outputRegionForThread);
  itLine.SetDirection(dimension);

  // Get the number of components
  int nc = image->GetNumberOfComponentsPerPixel();

  // Get the first and last component for accumulation - these are optionally
  // specified by the user
  int c_first = filter->GetComponentOffsetFront(),
      c_last = (nc - 1) - filter->GetComponentOffsetBack();
  int n_skipped = filter->GetComponentOffsetFront() + filter->GetComponentOffsetBack();

  // Get the offset corresponding to a move along the line for this iterator
  typename IteratorType::OffsetValueType jump = itLine.GetOffset(dimension) * nc;

  // Length of the line being traversed (in whole pixels, then in components)
  int line_length = outputRegionForThread.GetSize(dimension),
      line_length_comp = line_length * nc;

  // Width of the kernel (in whole pixels, then in components)
  int kernel_width = 2 * radius + 1;

  // Allocate an array of the length of the line in components
  TPixel *line = new TPixel[line_length_comp];
  // double *line = new double[line_length_comp];
  // double *sum = new double[nc], *sum_end = sum + nc, *p_sum;

  // Allocate an array to hold the current running sum
  // OutputImageComponentType *sum = new OutputImageComponentType[nc], *sum_end = sum + nc, *p_sum;
  TPixel *sum = new TPixel[nc];

  // Pointers into the sum array for the included components
  TPixel *sum_start = sum + c_first, *sum_end = sum + c_last + 1;

  // Two versions of the code - I thought that maybe the second version (further down) would be
  // more optimized by the compiler, but if anything, I see an opposite effect (although tiny)

#ifdef _ACCUM_ITER_CODE_

  TPixel *p_sum;

  // Start iterating over lines
  for(itLine.GoToBegin(); !itLine.IsAtEnd(); itLine.NextLine())
    {
    int i;

    // Initialize the sum to zero
    for(p_sum = sum_start; p_sum < sum_end; p_sum++)
      *p_sum  = itk::NumericTraits<TPixel>::Zero;

    // Pointer to the current position in the line
    TPixel *p_line = line + c_first, *p_tail = p_line;

    // Pointer to the beginning of the scan line
    long offset_in_pixels = itLine.GetPosition() - image->GetBufferPointer();
    long offset_in_comp = offset_in_pixels * nc;
    const TPixel *p_scan_pixel = image->GetBufferPointer() + offset_in_comp + c_first, *p_scan;

    // Pointer used for writing, it will trail the scan pointer
    TPixel *p_write_pixel = const_cast<TPixel *>(p_scan_pixel), *p_write;

    // Compute the initial sum
    for(i = 0; i < radius; i++)
      {
      for(p_scan = p_scan_pixel, p_sum = sum_start;
          p_sum < sum_end;
          p_sum++, p_line++, p_scan++)
        {
        *p_sum += *p_line = *p_scan;
        }

      p_scan_pixel += jump;
      p_line += n_skipped;
      }

    // For the next Radius + 1 values, add to the sum and write
    for(; i < kernel_width; i++)
      {
      for(p_scan = p_scan_pixel, p_write = p_write_pixel, p_sum = sum_start;
          p_sum < sum_end;
          p_sum++, p_line++, p_scan++, p_write++)
        {
        *p_line = *p_scan;
        *p_sum += *p_line;
        *p_write = *p_sum;
        }

      p_scan_pixel += jump;
      p_write_pixel += jump;
      p_line += n_skipped;
      }

    // Continue until we hit the end of the scanline
    for(; i < line_length; i++)
      {
      for(p_scan = p_scan_pixel, p_write = p_write_pixel, p_sum = sum_start;
          p_sum < sum_end;
          p_sum++, p_line++, p_scan++, p_write++, p_tail++)
        {
        *p_line = *p_scan;
        *p_sum += *p_line - *p_tail;
        *p_write = *p_sum;
        }

      p_scan_pixel += jump;
      p_write_pixel += jump;
      p_line += n_skipped;
      p_tail += n_skipped;
      }

    // Fill out the last bit
    for(; i < line_length + radius; i++)
      {
      for(p_write = p_write_pixel, p_sum = sum_start;
          p_sum < sum_end;
          p_sum++, p_write++, p_tail++)
        {
        *p_sum -= *p_tail;
        *p_write = *p_sum;
        }

      p_write_pixel += jump;
      p_tail += n_skipped;
      }
    }

#else

  // Start iterating over lines
  for(itLine.GoToBegin(); !itLine.IsAtEnd(); itLine.NextLine())
    {

    int i, k, m;

    // Initialize the sum to zero
    for(int k = c_first; k <= c_last; k++)
      sum[k] = itk::NumericTraits<TPixel>::Zero;

    // Pointer to the current position in the line
    TPixel *p_line = line, *p_tail = p_line;

    // Pointer to the beginning of the scan line
    long offset_in_pixels = itLine.GetPosition() - image->GetBufferPointer();
    long offset_in_comp = offset_in_pixels * nc;

    // Where we are scanning from
    const TPixel *p_scan_pixel = image->GetBufferPointer() + offset_in_comp;

    // Pointer used for writing, it will trail the scan pointer
    TPixel *p_write_pixel = const_cast<TPixel *>(p_scan_pixel);

    // Compute the initial sum
    for(i = 0, m = 0; i < radius; i++)
      {
      for(k = c_first; k <= c_last; k++)
        {
        sum[k] += p_line[k] = p_scan_pixel[k];
        }
      p_scan_pixel += jump;
      p_line += nc;
      }

    // For the next Radius + 1 values, add to the sum and write
    for(; i < kernel_width; i++)
      {
      for(k = c_first; k <= c_last; k++)
        {
        p_write_pixel[k] = (sum[k] += p_line[k] = p_scan_pixel[k]);
        }

      p_scan_pixel += jump;
      p_write_pixel += jump;
      p_line += nc;
      }

    // Continue until we hit the end of the scanline
    for(; i < line_length; i++)
      {
      for(k = c_first; k <= c_last; k++)
        {
        p_write_pixel[k] = (sum[k] += (p_line[k] = p_scan_pixel[k]) - p_tail[k]);
        }

      p_scan_pixel += jump;
      p_write_pixel += jump;
      p_line += nc;
      p_tail += nc;
      }

    // Fill out the last bit
    for(; i < line_length + radius; i++)
      {
      for(k = c_first; k <= c_last; k++)
        {
        p_write_pixel[k] = (sum[k] -= p_tail[k]);
        }

      p_write_pixel += jump;
      p_tail += nc;
      }
    }
#endif

  delete sum;
  delete line;
}

// ### PY, 05/18/2016: checked again, this SSE code is not causing any differences in float/double
//                     processing, safe to keep as is!
#ifdef __SSE__

#include <xmmintrin.h>

#ifdef WIN32
inline void allocate_aligned(int elements, float ** pointer)
{
  *pointer = (float *)_aligned_malloc(elements * sizeof(float), 16);
  if (*pointer == NULL)
  {
    std::cerr << "_aligned_malloc returned NULL input " << elements * sizeof(float) << std::endl;
    throw std::string("_aligned_malloc allocation error");
  }
}
#else
inline void allocate_aligned(int elements, float ** pointer)
{
  int rc = posix_memalign( (void **) pointer, 16, elements * sizeof(float));
  if(rc != 0)
  {
    std::cerr << "posix_memalign return value " << rc << " input " << elements * sizeof(float) << std::endl;
    throw std::string("posix_memalign allocation error");
  }
}
#endif

/**
 * A specialization of the threaded generate data method for floating point images that uses
 * SSE intrinsics for faster computation
 */
template <class TInputImage>
class OneDimensionalInPlaceAccumulateFilterWorker<float, TInputImage>
{
public:
  typedef OneDimensionalInPlaceAccumulateFilter<TInputImage> FilterType;
  typedef typename FilterType::OutputImageRegionType OutputImageRegionType;
  typedef typename FilterType::InputImageType InputImageType;
  static void ThreadedGenerateData(FilterType *filter,
                                   const OutputImageRegionType & outputRegionForThread,
                                   itk::ThreadIdType threadId);
};

template <class TInputImage>
void
OneDimensionalInPlaceAccumulateFilterWorker<float, TInputImage>
::ThreadedGenerateData(FilterType *filter,
                       const OutputImageRegionType & outputRegionForThread,
                       itk::ThreadIdType threadId)
{
  // Get filter parameters
  int dimension = filter->GetDimension();
  int radius = filter->GetRadius();
  int skip_front = filter->GetComponentOffsetFront();
  int skip_back = filter->GetComponentOffsetBack();

  // Get the image
  InputImageType *image = const_cast<InputImageType *>(filter->GetInput());

  // Set up the iterator that will go through all the lines in the
  // output region. We assume that the lines span the whole length of
  // the input, i.e., the threading direction does not interfere
  typedef itk::ImageLinearIteratorWithIndex<InputImageType> IteratorBaseType;
  typedef IteratorExtenderWithOffset<IteratorBaseType> IteratorType;

  // This is the line iterator, although for even greater speed we operate
  // directly on pointers, so we only use it's NextLine functionality()
  IteratorType itLine(image, outputRegionForThread);
  itLine.SetDirection(dimension);

  // Get the number of components
  int nc = image->GetNumberOfComponentsPerPixel();

  // Get the first and last component for accumulation - these are optionally
  // specified by the user. The remaining components are left untouched
  int c_first = skip_front, c_last = (nc - 1) - skip_back;
  int n_skipped = skip_front + skip_back;

  // Get the offset corresponding to a move along the line for this iterator
  typename IteratorType::OffsetValueType jump = itLine.GetOffset(dimension) * nc;

  // Length of the line being traversed (in whole pixels, then in components)
  int line_length = outputRegionForThread.GetSize(dimension);

  // Width of the kernel (in whole pixels, then in components)
  int kernel_width = 2 * radius + 1;

  // We want some alignment for SIMD purposes. So we need to make a stride be a factor of 16 bytes
  int nc_used = nc - n_skipped;
  int bytes_per_pixel = sizeof(float) * nc_used;

  // Round up, so it works out to 16 bytes
  int align_stride = 4 * sizeof(float);
  int padded_bytes_per_pixel = (bytes_per_pixel % align_stride) == 0
      ? bytes_per_pixel : align_stride * (1 + bytes_per_pixel / align_stride);

  // Number of chunks of four components per pixel
  int nc_padded = padded_bytes_per_pixel / sizeof(float);

  // The following arrays are allocated temporarily
  float *scanline, *tailline, *sum_align;

  // This is a byte-aligned copy of the pixel column from the image
  allocate_aligned(line_length * nc_padded, &scanline);

  // This is a second aligned copy
  allocate_aligned(line_length * nc_padded, &tailline);

  // End of the scanline
  float *p_scanline_end = scanline + line_length * nc_padded;

  // Aligned sum array - where the sums are computed
  allocate_aligned(nc_padded, &sum_align);

  // Start iterating over lines
  for(itLine.GoToBegin(); !itLine.IsAtEnd(); itLine.NextLine())
    {
    int i, k;

    // Pointer to the beginning of the scan line
    long offset_in_pixels = itLine.GetPosition() - image->GetBufferPointer();
    long offset_in_comp = offset_in_pixels * nc;

    // Get the pointer to first component in first pixel
    const float *p_scan_pixel = image->GetBufferPointer() + offset_in_comp + c_first;

    // Registers
    __m128 m_line, m_tail, m_sum_cur, m_sum_new;

    // Copy the contents of the image into the aligned line
    float *p_copy = scanline;
    const float *p_src = p_scan_pixel;
    for(; p_copy < p_scanline_end; p_copy += nc_padded, p_src += jump)
      {
#ifndef WIN32
      __builtin_prefetch(p_src + 5 * jump, 0, 0);
#endif 

      for (i = 0; i < nc_used; i++)
        p_copy[i] = p_src[i];
      }

    // Make a copy of the scan line
    for(p_src = scanline, p_copy = tailline; p_src < p_scanline_end; p_copy+=4, p_src+=4)
      {
      m_line = _mm_load_ps(p_src);
      _mm_store_ps(p_copy, m_line);
      }

    // Clear the sum array at the beginning
    for(k = 0; k < nc_padded; k++)
      sum_align[k] = 0.0;

    // Pointer to the current position in the line
    float *p_line = scanline, *p_tail = tailline;

    // Pointer used for writing, it will trail the scan pointer
    float *p_write_pixel = scanline;

    // Pointer used for writing, it will trail the scan pointer
    float *p_sum_end = sum_align + nc_padded, *p_sum;

    // Compute the initial sum
    for(i = 0; i < radius; i++)
      {
      for(p_sum = sum_align; p_sum < p_sum_end; p_sum+=4, p_line+=4)
        {
        m_line = _mm_load_ps(p_line);
        m_sum_cur = _mm_load_ps(p_sum);
        m_sum_new = _mm_add_ps(m_sum_cur, m_line);
        _mm_store_ps(p_sum, m_sum_new);
        }
      }

    // For the next Radius + 1 values, add to the sum and write
    for(; i < kernel_width; i++)
      {
      for(p_sum = sum_align; p_sum < p_sum_end; p_sum+=4, p_line+=4, p_write_pixel+=4)
        {
        m_line = _mm_load_ps(p_line);
        m_sum_cur = _mm_load_ps(p_sum);
        m_sum_new = _mm_add_ps(m_sum_cur, m_line);
        _mm_store_ps(p_sum, m_sum_new);
        _mm_store_ps(p_write_pixel, m_sum_new);
        }
      }

    // Continue until we hit the end of the scanline
    for(; i < line_length; i++)
      {
      for(p_sum = sum_align; p_sum < p_sum_end; p_sum+=4, p_line+=4, p_tail+=4, p_write_pixel+=4)
        {
        m_line = _mm_load_ps(p_line);
        m_tail = _mm_load_ps(p_tail);
        m_sum_cur = _mm_load_ps(p_sum);
        m_sum_new = _mm_add_ps(m_sum_cur, _mm_sub_ps(m_line, m_tail));
        _mm_store_ps(p_sum, m_sum_new);
        _mm_store_ps(p_write_pixel, m_sum_new);
        }
      }

    // Fill out the last bit
    for(; i < line_length + radius; i++)
      {
      for(p_sum = sum_align; p_sum < p_sum_end; p_sum+=4, p_tail+=4, p_write_pixel+=4)
        {
        m_tail = _mm_load_ps(p_tail);
        m_sum_cur = _mm_load_ps(p_sum);
        m_sum_new = _mm_sub_ps(m_sum_cur, m_tail);
        _mm_store_ps(p_sum, m_sum_new);
        _mm_store_ps(p_write_pixel, m_sum_new);
        }
      }

    // Copy the accumulated pixels back into the main image
    float *p_copy_back = const_cast<float *>(p_scan_pixel);
    const float *p_src_back = scanline;
    for(; p_src_back < p_scanline_end; p_src_back += nc_padded, p_copy_back += jump)
      {
#ifndef WIN32
      __builtin_prefetch(p_copy_back + 5 * jump, 1, 0);
#endif
      for(i = 0; i < nc_used; i++)
        p_copy_back[i] = p_src_back[i];
      }
    }

  // Free allocated memory
  free(tailline);
  free(scanline);
  free(sum_align);
}

#endif // _NCC_SSE_


/**
 * Default implementaton of the threaded generate data method
 */
template <class TInputImage>
void
OneDimensionalInPlaceAccumulateFilter<TInputImage>
::ThreadedGenerateData(
    const OutputImageRegionType & outputRegionForThread,
    itk::ThreadIdType threadId)
{
  typedef OneDimensionalInPlaceAccumulateFilterWorker<OutputImageComponentType, InputImageType> WorkerType;
  WorkerType::ThreadedGenerateData(this, outputRegionForThread, threadId);
}




template <class TInputImage>
typename TInputImage::Pointer
AccumulateNeighborhoodSumsInPlace(TInputImage *image, const typename TInputImage::SizeType &radius,
                                  int num_ignored_at_start, int num_ignored_at_end)
{
  typedef OneDimensionalInPlaceAccumulateFilter<TInputImage> AccumFilterType;

  typename itk::ImageSource<TInputImage>::Pointer pipeTail;
  for(int dir = 0; dir < TInputImage::ImageDimension; dir++)
    {
    typename AccumFilterType::Pointer accum = AccumFilterType::New();
    accum->SetInput(pipeTail.IsNull() ? image : pipeTail->GetOutput());
    accum->SetDimension(dir);
    accum->SetRadius(radius[dir]);
    accum->SetComponentRange(num_ignored_at_start, num_ignored_at_end);
    pipeTail = accum;

    accum->Update();
    }

  return pipeTail->GetOutput();
}