Skip to content

PERF: Use scanline iterators in per-pixel filter loops - #7258

Merged
dzenanz merged 5 commits into
InsightSoftwareConsortium:mainfrom
dzenanz:scanline-auto-vectorization
Nov 28, 2026
Merged

dzenanz merged 5 commits into
InsightSoftwareConsortium:mainfrom
dzenanz:scanline-auto-vectorization

Conversation

@dzenanz

@dzenanz dzenanz commented Nov 27, 2026

Copy link
Copy Markdown
Member

Switch per-pixel loops in nine filters to ImageScanlineIterator, and report BinaryDilate/BinaryErode copy-loop progress per line or stage. Output is unchanged; on six compilers no filter is consistently slower.

Which loops, and why these

ImageScanlineIterator's inner loop advances a plain offset, without ImageRegionIterator's per-pixel end-of-span check and call to Increment(). Iteration order is unchanged, so results are bit-identical.

Round 1 converted 18 headers. An iterator change was kept only if it was at least 5% faster on some compiler and not consistently 5% slower on any:

  • Kept: HessianRecursiveGaussian, GradientRecursiveGaussian, HessianGaussian, FFTWInverseFFT, FFTWHalfHermitianToRealInverseFFT, FrameDifference, FrameAverage, LabelMapToBinary, BinaryErode.
  • Dropped: BinaryDilate (15% slower with AppleClang), FFTWComplexToComplexFFT, Strain, InvertDisplacementField, Opening/ClosingByReconstruction, ObjectMorphology (neutral), StructuralSimilarity (4–7% slower with Clang 18), AdaptiveNonLocalMeans (not measured).

The last commit replaces ProgressReporter::CompletedPixel() in the simple copy loops of BinaryDilate and BinaryErode with TotalProgressReporter::Completed() once per line or per stage. Other loops in those filters still report per pixel. The old includes are kept next to the new ones, because client code can depend on them transitively.

GCC 13 and Clang 18–23 vectorize the Gaussian derivative, FFTW and FrameDifference inner loops; on main they vectorize none of these loops. MSVC vectorizes none of them in either version.

Benchmark results

Whole-filter wall time of the final branch against its base, median of 3 rounds alternating the builds. Ranges cover all-thread and one-thread runs.

Filter MSVC 14.52 clang-cl 19 GCC 13.3 Clang 18 AppleClang 21 Clang 23 (arm64)
LabelMapToBinary −50/−66% −7/−13% −13% −12% −62/−66% −62/−66%
FrameDifference −4/−5% −22% (1 thread) −47% (1 thread) −45% (1 thread) −86% (1 thread) −86% (1 thread)
FrameAverage −5% −5/−16% −15% −9% −22/−24% −32/−46%
BinaryErode −36/−40% −8/−12% ~0 −7/−8% −11/−12% −11/−12%
BinaryDilate −24% −4/−8% ~0 ~0 ~0 ~0
Gaussian derivatives 0 to −8% 0 to −7% −6 to −9% −6 to −10% 0 to −5% up to −22%
FFTW inverses noise noise −4/−5% −4/−5% −5% noise

Machines: Windows (24 threads; MSVC and clang-cl), Linux i7-14700 (28 threads; GCC and Clang 18, -O3 without -march), Apple M1 (8 threads; AppleClang and Homebrew LLVM Clang). Sizes: 256³ unsigned char for the morphology and label map filters, 128³–256³ float for the Gaussian filters, 256³ complex for FFTW, 32 frames of 1024² for the video filters.

These numbers were measured with the branch on top of #7256's anchor morphology fixes, which do not touch these filters. Some filters whose source is unchanged moved by up to ±50% depending on what else was compiled in the same translation unit (inlining). Every such case was checked with mixed-header builds and is not caused by these changes.

Testing

On this base, MSVC: all 433 tests of ITKImageFeature, BoneEnhancement, ITKImageGradient, ITKVideoFiltering, ITKBinaryMathematicalMorphology, ITKMathematicalMorphology, ITKLabelMap and ITKFFT (with FFTW) pass, with no new warnings. On the previous base, the same modules also passed with GCC 13.3 and AppleClang 21.

AI assistance
  • Tool: Claude Code (claude-opus-5-5), in sessions on Windows, Linux and macOS.
  • Role: surveyed ITK for convertible loops, wrote the conversions, built the benchmark harness, ran the benchmarks and compiler vectorization reports, and selected the kept changes by the rule above.
  • All changes were built and tested locally before committing.

🤖 Generated with Claude Code

The inner loop of ImageScanlineIterator advances a plain offset, without
ImageRegionIterator's per-pixel end-of-span check and call to Increment().
GCC and Clang vectorize these loops; MSVC does not.
The inner loop of ImageScanlineIterator advances a plain offset, without
ImageRegionIterator's per-pixel end-of-span check and call to Increment().
GCC and Clang vectorize these loops; MSVC does not.
The inner loop of ImageScanlineIterator advances a plain offset, without
ImageRegionIterator's per-pixel end-of-span check and call to Increment().
The inner loop of ImageScanlineIterator advances a plain offset, without
ImageRegionIterator's per-pixel end-of-span check and call to Increment().
GCC and Clang vectorize the frame difference loop; MSVC does not.
@github-actions github-actions Bot added type:Performance Improvement in terms of compilation or execution time area:Filtering Issues affecting the Filtering module area:Video Issues affecting the Video module labels Nov 27, 2026
@dzenanz
dzenanz marked this pull request as ready for review November 27, 2026 21:19
@greptile-apps

greptile-apps Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5 · The PR appears safe to merge, with a non-blocking dilation progress issue.RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes affect performance and progress updates in several image-processing workflows.

The PR appears safe to merge, with a non-blocking dilation progress issue.

Findings

  1. P2 Dilation progress stops short ▶

Summary

Replaces per-pixel region loops with scanline loops in nine filters and batches progress reports in binary morphology.

  • Gaussian filters copy derivative results one row at a time.
  • FFTW inverse filters normalize output pixels one row at a time.
  • Label-map conversion copies background pixels one row at a time.
  • Video filters average and compare frame pixels one row at a time.
  • Binary morphology reports copy progress by stage or scanline.

Reviews (1) · Last reviewed commit: "PERF: Report binary dilate and erode cop..." · Reviewed by Greptile

…tage

ProgressReporter::CompletedPixel() adds a counter update and a branch to
every iteration of these copy loops. TotalProgressReporter::Completed()
reports the pixels of a whole line, or of a whole copy stage, at once.

Unlike ProgressReporter, TotalProgressReporter does not set the progress
to 1 when destroyed, and the border tracking stage can report fewer
pixels than its share, so GenerateData() now ends with UpdateProgress(1).

@hjmjohnson hjmjohnson left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this looks correct. I checked that each pair of scanline iterators walks identical regions (including the adaptor requested regions in the three Gaussian filters) and that adaptor Get/Set still go through the pixel accessor. I found no blocking issue; everything below is a nit.

  • Test for the progress fix (nit): SimpleFilterWatcher only fails when no progress event arrives at all, so removing UpdateProgress(1.0f) would not fail any test. Checking filter->GetProgress() == 1.0f after Update() in itkBinaryDilateImageFilterTest and itkBinaryErodeImageFilterTest would cover it.
  • Description (nit): the swap to TotalProgressReporter changes the reporter for every loop in those two filters, and it no longer sets progress to 1 when destroyed, which is why UpdateProgress(1.0f) was added. One sentence in the description would say so. A whole-stage Completed(N) also checks for abort once per copy stage instead of about every 1%; that is fine for these cheap loops.
  • Commit bodies (nit): "ImageRegionIterator's per-pixel end-of-span check and call to Increment()." is 74 characters and appears in four commits; prose-budget.md asks for 72.

Comment on lines +455 to +456
// The border tracking stage reports fewer pixels than it was allotted.
this->UpdateProgress(1.0f);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: two small points on the Greptile fix, which is needed (UpdateOutputData sets 1.0 only after an abort).

  1. progress is destroyed after this call, and ~TotalProgressReporter() then adds its leftover pixels. IncrementProgress wraps past the maximum and clamps back, so observers get a second ProgressEvent at 1.0. Putting the reporter in an inner block that ends before this line would avoid it.
  2. In erode, the tracking stage counts neighbors when it tags them, including ones in the padded band, so it can report more or fewer than its share, not only fewer. The same comment is in both filters:
Suggested change
// The border tracking stage reports fewer pixels than it was allotted.
this->UpdateProgress(1.0f);
// The border tracking stage does not report exactly its allotted pixels.

Reasoned from the code, not run.

Comment on lines +468 to +469
// The border tracking stage reports fewer pixels than it was allotted.
this->UpdateProgress(1.0f);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: same as on BinaryDilate: the comment wording, and the second ProgressEvent at 1.0 from the reporter's destructor.

Suggested change
// The border tracking stage reports fewer pixels than it was allotted.
this->UpdateProgress(1.0f);
// The border tracking stage does not report exactly its allotted pixels.

@dzenanz
dzenanz merged commit e350d93 into InsightSoftwareConsortium:main Nov 28, 2026
19 checks passed
@blowekamp

Copy link
Copy Markdown
Member

Nice!

@dzenanz
dzenanz deleted the scanline-auto-vectorization branch November 30, 2026 16:04
@dzenanz

dzenanz commented Nov 30, 2026

Copy link
Copy Markdown
Member Author

I somehow merged this without seeing your second round of reviews, Hans. I will address them in a follow-up PR.

@hjmjohnson

Copy link
Copy Markdown
Member

I somehow merged this without seeing your second round of reviews, Hans. I will address them in a follow-up PR.

No problem :).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:Filtering Issues affecting the Filtering module area:Video Issues affecting the Video module type:Performance Improvement in terms of compilation or execution time

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants