0
# Image Filtering
1
2
Comprehensive filtering operations including smoothing, sharpening, noise reduction, and mathematical operations for image enhancement and preprocessing.
3
4
## Capabilities
5
6
### Smoothing Filters
7
8
Reduce noise and smooth images using various kernel-based approaches.
9
10
```python { .api }
11
def Gaussian(image: Image, sigma: float = 1.0, useImageSpacing: bool = True) -> Image:
12
"""
13
Gaussian smoothing filter
14
15
Args:
16
image: Input image
17
sigma: Standard deviation of Gaussian kernel
18
useImageSpacing: Use image spacing in kernel computation
19
20
Returns:
21
Smoothed image
22
"""
23
24
def DiscreteGaussian(image: Image, variance: list = [1.0, 1.0],
25
maximumKernelWidth: int = 32, maximumError: float = 0.01) -> Image:
26
"""
27
Discrete Gaussian smoothing with precise kernel control
28
29
Args:
30
image: Input image
31
variance: Variance per dimension
32
maximumKernelWidth: Maximum kernel size
33
maximumError: Maximum approximation error
34
35
Returns:
36
Smoothed image
37
"""
38
39
def Median(image: Image, radius: list = [1, 1, 1]) -> Image:
40
"""
41
Median filtering for noise reduction
42
43
Args:
44
image: Input image
45
radius: Kernel radius per dimension
46
47
Returns:
48
Median filtered image
49
"""
50
51
def Mean(image: Image, radius: list = [1, 1, 1]) -> Image:
52
"""
53
Mean filtering (box filter)
54
55
Args:
56
image: Input image
57
radius: Kernel radius per dimension
58
59
Returns:
60
Mean filtered image
61
"""
62
63
def Bilateral(image: Image, domainSigma: float = 4.0, rangeSigma: float = 50.0,
64
numberOfRangeGaussianSamples: int = 100) -> Image:
65
"""
66
Bilateral filtering preserving edges while smoothing
67
68
Args:
69
image: Input image
70
domainSigma: Spatial kernel standard deviation
71
rangeSigma: Range kernel standard deviation
72
numberOfRangeGaussianSamples: Range sampling resolution
73
74
Returns:
75
Edge-preserving smoothed image
76
"""
77
```
78
79
**Usage Examples:**
80
81
```python
82
import SimpleITK as sitk
83
84
# Load noisy image
85
image = sitk.ReadImage('noisy_image.png')
86
87
# Gaussian smoothing
88
smooth_gaussian = sitk.Gaussian(image, sigma=2.0)
89
90
# Median filtering for salt-and-pepper noise
91
smooth_median = sitk.Median(image, radius=[2, 2])
92
93
# Bilateral filtering to preserve edges
94
smooth_bilateral = sitk.Bilateral(image, domainSigma=5.0, rangeSigma=50.0)
95
96
# Compare results
97
sitk.Show(image, "Original")
98
sitk.Show(smooth_gaussian, "Gaussian")
99
sitk.Show(smooth_median, "Median")
100
sitk.Show(smooth_bilateral, "Bilateral")
101
```
102
103
### Mathematical Operations
104
105
Perform arithmetic and mathematical operations on images.
106
107
```python { .api }
108
def Add(image1: Image, image2: Image) -> Image:
109
"""Add two images pixel-wise"""
110
111
def Add(image: Image, constant: float) -> Image:
112
"""Add constant to all pixels"""
113
114
def Subtract(image1: Image, image2: Image) -> Image:
115
"""Subtract second image from first"""
116
117
def Subtract(image: Image, constant: float) -> Image:
118
"""Subtract constant from all pixels"""
119
120
def Multiply(image1: Image, image2: Image) -> Image:
121
"""Multiply two images pixel-wise"""
122
123
def Multiply(image: Image, constant: float) -> Image:
124
"""Multiply all pixels by constant"""
125
126
def Divide(image1: Image, image2: Image) -> Image:
127
"""Divide first image by second"""
128
129
def Divide(image: Image, constant: float) -> Image:
130
"""Divide all pixels by constant"""
131
132
def Abs(image: Image) -> Image:
133
"""Absolute value of image"""
134
135
def Square(image: Image) -> Image:
136
"""Square of image values"""
137
138
def Sqrt(image: Image) -> Image:
139
"""Square root of image values"""
140
141
def Exp(image: Image) -> Image:
142
"""Exponential of image values"""
143
144
def Log(image: Image) -> Image:
145
"""Natural logarithm of image values"""
146
147
def Sin(image: Image) -> Image:
148
"""Sine of image values"""
149
150
def Cos(image: Image) -> Image:
151
"""Cosine of image values"""
152
153
def Pow(image: Image, exponent: float) -> Image:
154
"""Raise image values to power"""
155
```
156
157
**Usage Examples:**
158
159
```python
160
import SimpleITK as sitk
161
162
# Load images
163
image1 = sitk.ReadImage('image1.nii')
164
image2 = sitk.ReadImage('image2.nii')
165
166
# Basic arithmetic
167
sum_image = sitk.Add(image1, image2)
168
diff_image = sitk.Subtract(image1, image2)
169
ratio_image = sitk.Divide(image1, image2)
170
171
# Operations with constants
172
normalized = sitk.Divide(image1, 255.0)
173
shifted = sitk.Add(image1, 100)
174
scaled = sitk.Multiply(image1, 2.5)
175
176
# Mathematical functions
177
magnitude = sitk.Sqrt(sitk.Add(sitk.Square(image1), sitk.Square(image2)))
178
log_image = sitk.Log(sitk.Add(image1, 1)) # Add 1 to avoid log(0)
179
```
180
181
### Comparison and Logic Operations
182
183
Compare images and perform logical operations.
184
185
```python { .api }
186
def Greater(image1: Image, image2: Image) -> Image:
187
"""Element-wise greater than comparison"""
188
189
def GreaterEqual(image1: Image, image2: Image) -> Image:
190
"""Element-wise greater than or equal comparison"""
191
192
def Less(image1: Image, image2: Image) -> Image:
193
"""Element-wise less than comparison"""
194
195
def LessEqual(image1: Image, image2: Image) -> Image:
196
"""Element-wise less than or equal comparison"""
197
198
def Equal(image1: Image, image2: Image) -> Image:
199
"""Element-wise equality comparison"""
200
201
def NotEqual(image1: Image, image2: Image) -> Image:
202
"""Element-wise inequality comparison"""
203
204
def And(image1: Image, image2: Image) -> Image:
205
"""Logical AND of binary images"""
206
207
def Or(image1: Image, image2: Image) -> Image:
208
"""Logical OR of binary images"""
209
210
def Xor(image1: Image, image2: Image) -> Image:
211
"""Logical XOR of binary images"""
212
213
def Not(image: Image) -> Image:
214
"""Logical NOT of binary image"""
215
```
216
217
**Usage Examples:**
218
219
```python
220
import SimpleITK as sitk
221
222
# Load images
223
image1 = sitk.ReadImage('scan1.nii')
224
image2 = sitk.ReadImage('scan2.nii')
225
226
# Create masks based on comparison
227
high_intensity_mask = sitk.Greater(image1, 100)
228
difference_mask = sitk.Greater(sitk.Abs(sitk.Subtract(image1, image2)), 50)
229
230
# Combine masks
231
combined_mask = sitk.And(high_intensity_mask, difference_mask)
232
233
# Apply mask
234
result = sitk.Multiply(image1, sitk.Cast(combined_mask, image1.GetPixelID()))
235
```
236
237
### Convolution and Correlation
238
239
Apply custom kernels and compute correlations.
240
241
```python { .api }
242
def Convolution(image: Image, kernel: Image, normalize: bool = False) -> Image:
243
"""
244
Convolution with custom kernel
245
246
Args:
247
image: Input image
248
kernel: Convolution kernel
249
normalize: Normalize kernel to sum to 1
250
251
Returns:
252
Convolved image
253
"""
254
255
def NormalizedCorrelation(image: Image, template: Image) -> Image:
256
"""
257
Normalized cross-correlation template matching
258
259
Args:
260
image: Input image
261
template: Template to match
262
263
Returns:
264
Correlation map
265
"""
266
267
def LaplacianSharpening(image: Image, useImageSpacing: bool = True) -> Image:
268
"""
269
Laplacian sharpening filter
270
271
Args:
272
image: Input image
273
useImageSpacing: Use image spacing in computation
274
275
Returns:
276
Sharpened image
277
"""
278
```
279
280
**Usage Examples:**
281
282
```python
283
import SimpleITK as sitk
284
import numpy as np
285
286
# Create custom kernel
287
kernel_array = np.array([[-1, -1, -1],
288
[-1, 8, -1],
289
[-1, -1, -1]], dtype=np.float32)
290
kernel = sitk.GetImageFromArray(kernel_array)
291
292
# Apply convolution
293
image = sitk.ReadImage('input.png')
294
sharpened = sitk.Convolution(image, kernel, normalize=True)
295
296
# Template matching
297
template = sitk.ReadImage('template.png')
298
correlation_map = sitk.NormalizedCorrelation(image, template)
299
```
300
301
### Gradient and Derivative Filters
302
303
Compute image gradients and derivatives for edge detection and feature analysis.
304
305
```python { .api }
306
def GradientMagnitude(image: Image, useImageSpacing: bool = True) -> Image:
307
"""
308
Compute gradient magnitude
309
310
Args:
311
image: Input image
312
useImageSpacing: Use image spacing in gradient computation
313
314
Returns:
315
Gradient magnitude image
316
"""
317
318
def GradientMagnitudeRecursiveGaussian(image: Image, sigma: float = 1.0) -> Image:
319
"""
320
Gradient magnitude with Gaussian smoothing
321
322
Args:
323
image: Input image
324
sigma: Gaussian smoothing parameter
325
326
Returns:
327
Smoothed gradient magnitude
328
"""
329
330
def Laplacian(image: Image, useImageSpacing: bool = True) -> Image:
331
"""
332
Laplacian operator (second derivatives)
333
334
Args:
335
image: Input image
336
useImageSpacing: Use image spacing in computation
337
338
Returns:
339
Laplacian filtered image
340
"""
341
342
def SobelEdgeDetection(image: Image) -> Image:
343
"""
344
Sobel edge detection
345
346
Args:
347
image: Input image
348
349
Returns:
350
Edge magnitude image
351
"""
352
353
def CannyEdgeDetection(image: Image, lowerThreshold: float = 0.0,
354
upperThreshold: float = 0.0, variance: list = [2.0, 2.0]) -> Image:
355
"""
356
Canny edge detection with hysteresis thresholding
357
358
Args:
359
image: Input image
360
lowerThreshold: Lower threshold for edge linking
361
upperThreshold: Upper threshold for edge detection
362
variance: Gaussian smoothing variance per dimension
363
364
Returns:
365
Binary edge image
366
"""
367
```
368
369
**Usage Examples:**
370
371
```python
372
import SimpleITK as sitk
373
374
# Load image
375
image = sitk.ReadImage('brain.nii')
376
377
# Gradient-based edge detection
378
gradient_mag = sitk.GradientMagnitude(image)
379
gradient_smooth = sitk.GradientMagnitudeRecursiveGaussian(image, sigma=1.5)
380
381
# Laplacian edge detection
382
laplacian = sitk.Laplacian(image)
383
384
# Canny edge detection
385
edges = sitk.CannyEdgeDetection(image,
386
lowerThreshold=10,
387
upperThreshold=50,
388
variance=[2.0, 2.0])
389
390
# Display results
391
sitk.Show(gradient_mag, "Gradient Magnitude")
392
sitk.Show(edges, "Canny Edges")
393
```
394
395
### Noise Reduction Filters
396
397
Advanced noise reduction techniques preserving important image features.
398
399
```python { .api }
400
def CurvatureFlow(image: Image, timeStep: float = 0.05, numberOfIterations: int = 5) -> Image:
401
"""
402
Curvature flow smoothing
403
404
Args:
405
image: Input image
406
timeStep: Evolution time step
407
numberOfIterations: Number of iterations
408
409
Returns:
410
Smoothed image
411
"""
412
413
def CurvatureAnisotropicDiffusion(image: Image, timeStep: float = 0.0625,
414
conductanceParameter: float = 3.0,
415
numberOfIterations: int = 5) -> Image:
416
"""
417
Anisotropic diffusion smoothing
418
419
Args:
420
image: Input image
421
timeStep: Evolution time step
422
conductanceParameter: Edge preservation parameter
423
numberOfIterations: Number of iterations
424
425
Returns:
426
Edge-preserving smoothed image
427
"""
428
429
def GradientAnisotropicDiffusion(image: Image, timeStep: float = 0.0625,
430
conductanceParameter: float = 3.0,
431
numberOfIterations: int = 5) -> Image:
432
"""
433
Gradient-based anisotropic diffusion
434
435
Args:
436
image: Input image
437
timeStep: Evolution time step
438
conductanceParameter: Edge preservation parameter
439
numberOfIterations: Number of iterations
440
441
Returns:
442
Edge-preserving smoothed image
443
"""
444
445
def PatchBasedDenoising(image: Image, kernelBandwidthSigma: float = 400.0,
446
patchRadius: int = 4, numberOfIterations: int = 1) -> Image:
447
"""
448
Patch-based denoising (Non-Local Means style)
449
450
Args:
451
image: Input image
452
kernelBandwidthSigma: Similarity kernel bandwidth
453
patchRadius: Patch size radius
454
numberOfIterations: Number of iterations
455
456
Returns:
457
Denoised image
458
"""
459
```
460
461
**Usage Examples:**
462
463
```python
464
import SimpleITK as sitk
465
466
# Load noisy image
467
noisy_image = sitk.ReadImage('noisy_mri.nii')
468
469
# Curvature flow smoothing
470
smoothed_flow = sitk.CurvatureFlow(noisy_image,
471
timeStep=0.05,
472
numberOfIterations=10)
473
474
# Anisotropic diffusion (preserves edges)
475
smoothed_aniso = sitk.CurvatureAnisotropicDiffusion(noisy_image,
476
timeStep=0.0625,
477
conductanceParameter=3.0,
478
numberOfIterations=5)
479
480
# Patch-based denoising
481
denoised_patch = sitk.PatchBasedDenoising(noisy_image,
482
kernelBandwidthSigma=400.0,
483
patchRadius=4)
484
485
# Compare results
486
sitk.Show(noisy_image, "Original Noisy")
487
sitk.Show(smoothed_aniso, "Anisotropic Diffusion")
488
sitk.Show(denoised_patch, "Patch-based Denoising")
489
```
490
491
## Advanced Filtering Patterns
492
493
### Filter Chaining
494
495
```python
496
import SimpleITK as sitk
497
498
# Chain multiple filters
499
image = sitk.ReadImage('input.nii')
500
501
# Noise reduction → Enhancement → Edge detection
502
processed = (image
503
.pipe(lambda x: sitk.Bilateral(x, domainSigma=5, rangeSigma=50))
504
.pipe(lambda x: sitk.LaplacianSharpening(x))
505
.pipe(lambda x: sitk.CannyEdgeDetection(x, 10, 50)))
506
507
# Alternative explicit chaining
508
step1 = sitk.Bilateral(image, domainSigma=5, rangeSigma=50)
509
step2 = sitk.LaplacianSharpening(step1)
510
edges = sitk.CannyEdgeDetection(step2, 10, 50)
511
```
512
513
### Multi-scale Processing
514
515
```python
516
import SimpleITK as sitk
517
518
def multiscale_enhancement(image, scales=[1.0, 2.0, 4.0]):
519
"""Multi-scale image enhancement"""
520
enhanced_scales = []
521
522
for sigma in scales:
523
# Smooth at current scale
524
smoothed = sitk.Gaussian(image, sigma=sigma)
525
526
# Compute Laplacian
527
laplacian = sitk.Laplacian(smoothed)
528
529
# Take absolute value
530
enhanced = sitk.Abs(laplacian)
531
enhanced_scales.append(enhanced)
532
533
# Combine scales
534
result = enhanced_scales[0]
535
for enhanced in enhanced_scales[1:]:
536
result = sitk.Add(result, enhanced)
537
538
return result
539
540
# Apply multi-scale enhancement
541
image = sitk.ReadImage('vessels.nii')
542
enhanced = multiscale_enhancement(image)
543
```
544
545
### Custom Filter Implementation
546
547
```python
548
import SimpleITK as sitk
549
import numpy as np
550
551
def custom_unsharp_mask(image, sigma=1.0, amount=1.0):
552
"""Custom unsharp masking filter"""
553
# Smooth the image
554
smoothed = sitk.Gaussian(image, sigma=sigma)
555
556
# Compute high-frequency component
557
high_freq = sitk.Subtract(image, smoothed)
558
559
# Add scaled high-frequency back to original
560
sharpened = sitk.Add(image, sitk.Multiply(high_freq, amount))
561
562
return sharpened
563
564
# Apply custom filter
565
image = sitk.ReadImage('blurry.png')
566
sharpened = custom_unsharp_mask(image, sigma=2.0, amount=1.5)
567
```