ITK Numerics

5.4.5 · active · verified Fri Apr 17

The `itk-numerics` package provides Python bindings for the Insight Toolkit's (ITK) Numerics module, offering a suite of algorithms for numerical optimization and cost function evaluation, essential for tasks like image registration and parameter fitting. ITK itself is a powerful, open-source, cross-platform toolkit for N-dimensional scientific image analysis. The current stable version of ITK is 5.4.5, with version 6.0 in active beta development, and releases typically follow a maintenance schedule for stable branches and active development for major versions.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a custom cost function and use the `GradientDescentOptimizer` to find the minimum of a simple 1D quadratic function. It showcases the typical pattern of instantiating ITK objects with `.New()` and setting parameters.

import itk
import numpy as np

# Define a simple cost function: f(x) = (x-5)^2
# This minimizes to x=5
class MyCostFunction(itk.SingleValuedCostFunction):
    def __init__(self):
        super().__init__()
        self.SetNumberOfParameters(1)

    def GetValue(self, parameters):
        x = parameters.GetElement(0)
        return (x - 5.0)**2

    def GetDerivative(self, parameters, derivative):
        x = parameters.GetElement(0)
        derivative.SetElement(0, 2.0 * (x - 5.0))

# Instantiate the cost function and optimizer
cost_function = MyCostFunction.New()
optimizer = itk.GradientDescentOptimizer.New()

# Configure the optimizer
optimizer.SetCostFunction(cost_function)
optimizer.SetLearningRate(0.1)
optimizer.SetNumberOfIterations(100)

# Set initial position for optimization
initial_position = itk.OptimizerParameters[itk.D].New()
initial_position.SetSize(1)
initial_position.SetElement(0, 0.0) # Start optimization at x=0
optimizer.SetInitialPosition(initial_position)

# Run the optimization
print(f"Initial position: {initial_position.GetElement(0):.2f}")
optimizer.StartOptimization()

final_position = optimizer.GetCurrentPosition()
print(f"Optimized position: {final_position.GetElement(0):.2f}")

view raw JSON →