# Wrap ITK image pointers with pybind11 and mix with the itk python package

**URL:** https://discourse.itk.org/t/wrap-itk-image-pointers-with-pybind11-and-mix-with-the-itk-python-package/2880
**Category:** Engineering
**Tags:** python
**Created:** [March 29, 2020, 1:30am UTC](https://discourse.itk.org/t/wrap-itk-image-pointers-with-pybind11-and-mix-with-the-itk-python-package/2880 "2020-03-29T01:30:00Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![phcerdan](https://discourse.itk.org/user_avatar/discourse.itk.org/phcerdan/32/286_2.png) [@phcerdan](https://discourse.itk.org/u/phcerdan)
#### Post date: [March 29, 2020, 1:30am UTC](https://discourse.itk.org/t/wrap-itk-image-pointers-with-pybind11-and-mix-with-the-itk-python-package/2880/1 "2020-03-29T01:30:01Z")

</div>

Hi there, I am wrapping to python a library that I maintain [SGEXT](https://github.com/phcerdan/SGEXT) using [pybind11](https://github.com/pybind/pybind11). I have wrapped the algorithms in the library, but I also wanted to wrap high level functions which use ITK, not only internally, but in the interface as inputs or outputs.

I was checking how hard would it be to just wrap `itk::SmartPointer<TImage>` with `pybind11`, which is the only thing in the interface that is usually needed. This is the returning type of the filters functions `an_itk_filter.GetOutput()`, and the input type of `an_itk_filter.SetInput(img_ptr)`.

It turns out that wasn’t that hard!  
I added functions in my wrapping to export and import from `numpy` and use the regular `itk` python functions `itk.GetArrayFromImage` and `itk.GetImageFromArray` to interact with the `itk` package.

This is work in progress, right now I am copying the data, I would also like to offer a `view` version, where no data is copied. But it is encouraging being able to mix both frameworks in python with no much effort.  
I am sure this might be useful for others, please find details in the following commit where the `ITK` wrapping is added using `pybind11`.

> <https://github.com/phcerdan/SGEXT/commit/d3a2533d9a87508417d0b26dda069e518d20e691>

---

<div class="post-metadata">

### Author: ![matt.mccormick](https://discourse.itk.org/user_avatar/discourse.itk.org/matt.mccormick/32/7_2.png) [@matt.mccormick](https://discourse.itk.org/u/matt.mccormick)
#### Post date: [March 30, 2020, 6:44pm UTC](https://discourse.itk.org/t/wrap-itk-image-pointers-with-pybind11-and-mix-with-the-itk-python-package/2880/2 "2020-03-30T18:44:53Z")

</div>

Amazing work @phcerdan! Quite elegant. 🌞
