{"id":9839,"library":"itk-filtering","title":"ITK Filtering","description":"ITK (Insight Toolkit) is an open-source, cross-platform toolkit for N-dimensional scientific image analysis, including processing, segmentation, and registration. The `itk-filtering` package bundles Python bindings for many ITK filtering modules. The current stable version is 5.4.5, with frequent maintenance releases for the 5.x series and active beta development for the upcoming 6.0 major version.","status":"active","version":"5.4.5","language":"en","source_language":"en","source_url":"https://github.com/InsightSoftwareConsortium/ITK","tags":["image-processing","medical-imaging","n-dimensional","scientific-computing","filters","computer-vision"],"install":[{"cmd":"pip install itk-filtering","lang":"bash","label":"Install core ITK and filtering modules"}],"dependencies":[{"reason":"itk-filtering is a metapackage that depends on the core ITK library and its Python bindings, providing convenience for installing many filtering modules.","package":"itk","optional":false}],"imports":[{"note":"Most common ITK functions and classes are exposed directly under the top-level `itk` module for Pythonic access. Direct module imports are rarely needed unless dealing with highly specialized or less common ITK components.","wrong":"from itk import some_filter_module","symbol":"itk","correct":"import itk"},{"note":"ITK images are templated. You must specify the pixel type (e.g., `itk.F`, `itk.UC`) and dimension count (e.g., `2`, `3`) when creating an image or a filter type. Python often handles this implicitly through factory functions (e.g., `itk.imread`), but explicit templating is necessary for direct class instantiation or advanced usage.","symbol":"Image","correct":"image = itk.Image[pixel_type, dimension_count]()"}],"quickstart":{"code":"import itk\nimport numpy as np\n\n# Create a simple 2D image (e.g., a square)\nsize = itk.Size[2]()\nsize.SetElement(0, 100)\nsize.SetElement(1, 100)\n\nstart = itk.Index[2]()\nstart.Fill(0)\n\nregion = itk.ImageRegion[2]()\nregion.SetSize(size)\nregion.SetIndex(start)\n\n# Instantiate an ITK image with unsigned char pixels (UC) and 2 dimensions\nimage = itk.Image[itk.UC, 2].New()\nimage.SetRegions(region)\nimage.Allocate()\nimage.FillBuffer(0)\n\n# Draw a white square on a black background\nfor x in range(20, 80):\n    for y in range(20, 80):\n        idx = itk.Index[2]()\n        idx.SetElement(0, x)\n        idx.SetElement(1, y)\n        image.SetPixel(idx, 255)\n\n# Apply a Median filter. The filter type is templated based on the input image type.\nmedian_filter = itk.MedianImageFilter[type(image), type(image)].New()\nmedian_filter.SetInput(image)\nmedian_filter.SetRadius(2) # Radius of 2x2 neighborhood\nmedian_filter.Update()\n\noutput_image = median_filter.GetOutput()\n\n# Convert ITK image to NumPy array for display/further processing (optional)\noutput_array = itk.GetArrayFromImage(output_image)\n\nprint(f\"Original image size: {image.GetLargestPossibleRegion().GetSize()}\")\nprint(f\"Output image size: {output_image.GetLargestPossibleRegion().GetSize()}\")\nprint(f\"Non-zero pixels in original: {np.sum(itk.GetArrayFromImage(image) > 0)}\")\nprint(f\"Non-zero pixels in filtered: {np.sum(output_array > 0)}\")\n\n# For real image processing, you'd typically read/write files like this:\n# try:\n#     itk.imwrite(output_image, \"filtered_image.png\")\n#     print(\"Filtered image saved as filtered_image.png\")\n# except Exception as e:\n#     print(f\"Could not save image: {e}. Ensure image format is supported and path is valid.\")\n# read_image = itk.imread(\"input.mha\", itk.F) # Read a medical image as float type","lang":"python","description":"This example demonstrates how to create a simple ITK image programmatically, apply a 2D Median filter, and inspect the output. It highlights the templated nature of ITK images and filters, and shows how to convert between ITK image objects and NumPy arrays for interoperability."},"warnings":[{"fix":"Review the ITK 6.0 release notes and migration guides once available. Test your code against ITK 6.0 beta releases. Adjust Python API calls as necessary, particularly for class constructors or function signatures that might have changed due to C++ template updates.","message":"ITK 6.0, currently in beta, will require C++17 and includes significant C++ code modernization and build system changes. While the Python wrappers aim for stability, users should anticipate potential breaking API changes or behavioral differences, especially for advanced use cases or custom C++ extensions, upon the stable release of ITK 6.0.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Always be mindful of image pixel types (e.g., `itk.UC` for unsigned char, `itk.F` for float) and dimensionality (e.g., `2`, `3`). Use `itk.CastImageFilter` to explicitly convert between types when needed. Often, ITK's Pythonic wrappers (`itk.median_image_filter()`) handle templating implicitly, but understanding the underlying C++ types is key for debugging.","message":"ITK images and filters are templated by pixel type and dimension. Incorrectly specifying these (or relying on implicit types that don't match your data) can lead to runtime errors or unexpected behavior. This is particularly important when instantiating filter types explicitly (e.g., `itk.MedianImageFilter[ImageType, ImageType]`).","severity":"gotcha","affected_versions":"All versions"},{"fix":"Prefer in-place operations or filters that operate on regions when possible. Leverage ITK's streaming capabilities for very large images if your pipeline supports it. Use `itk.GetArrayViewFromImage` for zero-copy access to image data in NumPy where appropriate, but be careful not to modify the view if the ITK object is meant to be immutable.","message":"ITK's memory management for large N-dimensional images can be a concern. Copying large images unnecessarily or processing them in inefficient ways can lead to high memory consumption and slow performance.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Ensure `itk` is installed by running `pip install itk` or `pip install itk-filtering` to get the core library along with the filtering components.","cause":"The core `itk` package (which includes filtering modules) is not installed in your Python environment. The `itk-filtering` package depends on `itk`.","error":"ModuleNotFoundError: No module named 'itk'"},{"fix":"Check the exact name and capitalization of the filter in the ITK documentation. For templated filters, ensure you are using the correct Pythonic factory function (e.g., `itk.median_image_filter()`) or explicitly templating the class (`itk.MedianImageFilter[ImageType, ImageType].New()`). Sometimes, a filter might be in a less common module that requires a separate `import` (e.g., `import itk.bridge.vtk` for VTK integration), though this is less common for core filtering.","cause":"You are trying to access a filter or function that does not exist or is not exposed directly under the `itk` module, or there's a typo in the name.","error":"AttributeError: module 'itk' has no attribute 'SomeFilterName'"},{"fix":"Use `itk.CastImageFilter` to explicitly convert your image to the required pixel type before applying the filter. For example, `itk.CastImageFilter[itk.UC, itk.F].New().SetInput(input_image).Update().GetOutput()` converts an unsigned char image to float.","cause":"ITK filters often expect specific input pixel types (e.g., float, unsigned char). If your image's pixel type does not match the filter's expectation or if you're chaining filters with incompatible types, this error occurs.","error":"RuntimeError: Exception thrown in SimpleITK CastImageFilter (or similar filter) ... Input image type is mismatching requested output image type."}]}