# MHA Numpy

**URL:** <https://discourse.itk.org/t/mha-numpy/2400>\
**Category:** Algorithms\
**Created:** [November 13, 2019, 2:11pm UTC](https://discourse.itk.org/t/mha-numpy/2400 "2019-11-13T14:11:01Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![fraca](https://discourse.itk.org/letter_avatar_proxy/v4/letter/f/f19dbf/32.png) [@fraca](https://discourse.itk.org/u/fraca)\
**Post date:** [November 13, 2019, 2:11pm UTC](https://discourse.itk.org/t/mha-numpy/2400/1 "2019-11-13T14:11:01Z")

</div>

I’m trying to write this code in Python, but i don’t know what i have to do when i have to create an iterator to build the mask, because i don’t know what are the values of the array created from mha file.

> typedef itk::ImageRegionIterator IteratorType;  
> IteratorType maskIt(outputImage,outputImage-\>GetLargestPossibleRegion());  
> LabelPixelType backgroundValue = 0;  
> LabelPixelType foregroundValue = 1;  
> for (maskIt.GoToBegin(); !maskIt.IsAtEnd(); ++maskIt)  
> {  
> ImageType::PointType point;  
> outputImage-\>TransformIndexToPhysicalPoint(maskIt.GetIndex(),point);  
> if (maskInterpolator-\>IsInsideBuffer(point))  
> {  
> if (maskInterpolator-\>Evaluate(point) == 0)  
> {  
> maskIt.Set(backgroundValue);  
> }  
> else  
> {  
> maskIt.Set(foregroundValue);  
> }  
> }  
> else  
> {  
> maskIt.Set(backgroundValue);  
> }  
> }

---

<div class="post-metadata">

**Author:** ![dzenanz](https://discourse.itk.org/user_avatar/discourse.itk.org/dzenanz/32/1093_2.png) [@dzenanz](https://discourse.itk.org/u/dzenanz)\
**Post date:** [November 13, 2019, 2:14pm UTC](https://discourse.itk.org/t/mha-numpy/2400/2 "2019-11-13T14:14:34Z")

</div>

Image iterator are not available from Python, because accessing images via this mechanism is too slow due to wrapping overhead.

---

<div class="post-metadata">

**Author:** ![fraca](https://discourse.itk.org/letter_avatar_proxy/v4/letter/f/f19dbf/32.png) [@fraca](https://discourse.itk.org/u/fraca)\
**Post date:** [November 13, 2019, 2:17pm UTC](https://discourse.itk.org/t/mha-numpy/2400/3 "2019-11-13T14:17:56Z")

</div>

I’m using NumPy to access the file, but i don’t understand what represents elements in the array that i get with array = itk.GetArrayViewFromImage(outputImage)

---

<div class="post-metadata">

**Author:** ![dzenanz](https://discourse.itk.org/user_avatar/discourse.itk.org/dzenanz/32/1093_2.png) [@dzenanz](https://discourse.itk.org/u/dzenanz)\
**Post date:** [November 13, 2019, 2:25pm UTC](https://discourse.itk.org/t/mha-numpy/2400/4 "2019-11-13T14:25:38Z")

</div>

Array elements are intensities of pixels in the image. Try reading a super small image (lets say 3x4x5) with distinctive values, and then access that via `itk.GetArrayViewFromImage`.

---

<div class="post-metadata">

**Author:** ![fraca](https://discourse.itk.org/letter_avatar_proxy/v4/letter/f/f19dbf/32.png) [@fraca](https://discourse.itk.org/u/fraca)\
**Post date:** [November 13, 2019, 2:27pm UTC](https://discourse.itk.org/t/mha-numpy/2400/5 "2019-11-13T14:27:19Z")

</div>

Thank you so much, but when i have to use TransformIndexToPhysicalPoint what i have to put to replace maskIt.GetIndex() ?  
EDIT: the first value of the matrix is the slice number, the second is the y axe, the third is the x axe and all the elements cointaned in the matrix are the pixel values

---

<div class="post-metadata">

**Author:** ![blowekamp](https://discourse.itk.org/user_avatar/discourse.itk.org/blowekamp/32/79_2.png) [@blowekamp](https://discourse.itk.org/u/blowekamp)\
**Post date:** [November 13, 2019, 2:46pm UTC](https://discourse.itk.org/t/mha-numpy/2400/6 "2019-11-13T14:46:00Z")

</div>

Why don’t you just resample the Mask image onto the output image with the ResampleImageFilter, then apply a BinaryThresholdImageFilter?

---

<div class="post-metadata">

**Author:** ![fraca](https://discourse.itk.org/letter_avatar_proxy/v4/letter/f/f19dbf/32.png) [@fraca](https://discourse.itk.org/u/fraca)\
**Post date:** [November 13, 2019, 3:00pm UTC](https://discourse.itk.org/t/mha-numpy/2400/7 "2019-11-13T15:00:21Z")

</div>

Update:

> pixelIndex=itk.Index[2] ()  
> for z in range (array.shape[0]):#slice  
> for y in range (array.shape[1]): #Y axes  
> for x in range (array.shape[2]): #X axes  
> pixelIndex[0]=x  
> pixelIndex[1]=y  
> point=ImageType.New()  
> outputImage.TransformIndexToPhysicalPoint(pixelIndex,point)  
> if (maskInterpolator.IsInsideBuffer(point)):  
> if (maskInterpolator.Evaluate(point) == 0):  
> maskIt.Set(backgroundValue)  
> else:  
> maskIt.Set(foregroundValue)  
> else:  
> maskIt.Set(backgroundValue)

I obtain this error:

> TypeError: itkImageBase3\_TransformIndexToPhysicalPoint expected 2 arguments, got 3

This may be helpful:

> Dim=3  
> PixelType=itk.F  
> LabelPixelType=itk. US  
> ImageType=itk.Image[PixelType,Dim]

---

<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:** [November 13, 2019, 3:13pm UTC](https://discourse.itk.org/t/mha-numpy/2400/8 "2019-11-13T15:13:42Z")

</div>

@blowekamp and @dzenanz have good suggestions – the result will be simpler and faster if `itk.resample_image_filter` with `use_reference_image=True` and `reference_image=input_image` followed by a call to `itk.binary_threshold_image_filter`.

See also:

- [https://itkpythonpackage.readthedocs.io/en/latest/Quick\_start\_guide.html](https://itkpythonpackage.readthedocs.io/en/latest/Quick_start_guide.html)
- [https://itk.org/Doxygen/html/classitk\_1\_1ResampleImageFilter.html](https://itk.org/Doxygen/html/classitk_1_1ResampleImageFilter.html)
- [https://itk.org/Doxygen/html/classitk\_1\_1BinaryThresholdImageFilter.html](https://itk.org/Doxygen/html/classitk_1_1BinaryThresholdImageFilter.html)

---

<div class="post-metadata">

**Author:** ![fraca](https://discourse.itk.org/letter_avatar_proxy/v4/letter/f/f19dbf/32.png) [@fraca](https://discourse.itk.org/u/fraca)\
**Post date:** [November 13, 2019, 3:20pm UTC](https://discourse.itk.org/t/mha-numpy/2400/9 "2019-11-13T15:20:52Z")

</div>

Thank you so much, i’ll follow your tips, but i would like to understand also the previous error. Do you have any idea?

---

<div class="post-metadata">

**Author:** ![fraca](https://discourse.itk.org/letter_avatar_proxy/v4/letter/f/f19dbf/32.png) [@fraca](https://discourse.itk.org/u/fraca)\
**Post date:** [November 13, 2019, 3:32pm UTC](https://discourse.itk.org/t/mha-numpy/2400/10 "2019-11-13T15:32:44Z")

</div>

It’s a little bit different from your interpretation because i have to check if a pixel is inside or outside a ROI contained in a TIF as an image sequence. I have already created an interpolation with _itk.NearestNeighborInterpolateImageFunction_ so now i have to check if a point is inside or outside to create the mask

---

<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:** [November 13, 2019, 3:46pm UTC](https://discourse.itk.org/t/mha-numpy/2400/11 "2019-11-13T15:46:30Z")

</div>

> [@fraca](#):
>
> Thank you so much, i’ll follow your tips, but i would like to understand also the previous error. Do you have any idea?

There are two options for `TransformIndexToPhysicalPoint`, [one that accepts a reference to the `Point` for its output](https://itk.org/Doxygen/html/classitk_1_1ImageBase.html#a8360b9623d685997725c81c85716c4d2), and [one that returns the `Point` as its output](https://itk.org/Doxygen/html/classitk_1_1ImageBase.html#ae2e113c2ff7bab1a145c27a30584a2ac). References are not supported well in Python, so you want the one that returns the value. Therefore,

```auto
point = outputImage.TransformIndexToPhysicalPoint(pixelIndex)

```

> [@fraca](#):
>
> It’s a little bit different from your interpretation because i have to check if a pixel is inside or outside a ROI contained in a TIF as an image sequence. I have already created an interpolation with _itk.NearestNeighborInterpolateImageFunction_ so now i have to check if a point is inside or outside to create the mask

A call to `itk.mask_image_filter` may also be helpful:

- [ITK: itk::MaskImageFilter\< TInputImage, TMaskImage, TOutputImage \> Class Template Reference](https://itk.org/Doxygen/html/classitk_1_1MaskImageFilter.html)

---

<div class="post-metadata">

**Author:** ![fraca](https://discourse.itk.org/letter_avatar_proxy/v4/letter/f/f19dbf/32.png) [@fraca](https://discourse.itk.org/u/fraca)\
**Post date:** [November 14, 2019, 11:51am UTC](https://discourse.itk.org/t/mha-numpy/2400/12 "2019-11-14T11:51:08Z")

</div>

I followed your suggestions but i have a problem because the mask and the input image don’t occupy the same physical space, despite having assigned them identical size,origin etc. It seems that the value of the mask resets in the function **MaskImageFilter**

> maskImage=flipFilter.GetOutput()  
> maskImage.SetOrigin(reader4mm.GetOutput().GetOrigin()) \>\>\>Assignation values  
> maskImage.SetSpacing(reader4mm.GetOutput().GetSpacing())  
> maskImage.SetDirection(reader4mm.GetOutput().GetDirection())  
> #create the final mask  
> MaskFilterType=itk.MaskImageFilter[LabeledImageType,MaskImageType,LabeledImageType]  
> maskFilter=MaskFilterType.New()  
> maskFilter.SetInput(outputImage)  
> maskFilter.SetMaskImage(maskImage) \>\>\>Mask seems to reset values  
> WriterType=itk.ImageFileWriter[LabeledImageType]  
> writer=WriterType.New()  
> writer.SetFileName(path+“/mask.mha”)  
> writer.SetInput(maskFilter.GetOutput())  
> try:  
> writer.Update();  
> except Exception as error:  
> print(“EXIT FAILURE”)  
> print(error)  
> sys.exit(1)  
> print(“EXIT SUCCESS”)

---

<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:** [November 14, 2019, 4:51pm UTC](https://discourse.itk.org/t/mha-numpy/2400/13 "2019-11-14T16:51:06Z")

</div>

> [@fraca](#):
>
> maskImage=flipFilter.GetOutput()  
> maskImage.SetOrigin(reader4mm.GetOutput().GetOrigin())

When the pipeline runs, the `flipFilter` can reset the value of the output – use a `ChangeInformationImageFilter` in this case:

[https://itk.org/Doxygen/html/classitk\_1\_1ChangeInformationImageFilter.html](https://itk.org/Doxygen/html/classitk_1_1ChangeInformationImageFilter.html)

---

<div class="post-metadata">

**Author:** ![fraca](https://discourse.itk.org/letter_avatar_proxy/v4/letter/f/f19dbf/32.png) [@fraca](https://discourse.itk.org/u/fraca)\
**Post date:** [November 14, 2019, 7:27pm UTC](https://discourse.itk.org/t/mha-numpy/2400/14 "2019-11-14T19:27:57Z")

</div>

It’s possible that `ChangeInformationImageFilter` is not implemented in python? I tried to do something like this:

> maskImage=flipFilter.GetOutput()  
> origin=reader4mm.GetOutput().GetOrigin()  
> spacing=reader4mm.GetOutput().GetSpacing()  
> direction=reader4mm.GetOutput().GetDirection()  
> maskImage.SetOutputSpacing(spacing)  
> maskImage.ChangeSpacingOn()

but it says that `AttributeError: 'itkImageUC3' object has no attribute 'ChangeSpacingOn'`.  
It may be helpful to say that i used `flipFilter` (`itk.FlipImageFilter`) to change the axis of the mask and that the mask should have the same size of the output image [256,256,50] (so i have to set: origin, direction and spacing)

EDIT: i tried to not flip the axes with `flipFilter` and to mantain

> maskImage.SetOrigin(reader4mm.GetOutput().GetOrigin())  
> maskImage.SetSpacing(reader4mm.GetOutput().GetSpacing())  
> maskImage.SetDirection(reader4mm.GetOutput().GetDirection())

but when i use the function `MaskImageFilter` the values of maskImage (origin,direction,spacing) seems to be reset in the function:

> c:\p\ipp\standalone-build\itks\modules\core\common\include\itkImageToImageFilter.hxx:220:  
> itk::ERROR: MaskImageFilter(000002A7B7568450): Inputs do not occupy the same physical space!  
> InputImage Origin: [-1.6488900e+02, -7.2781100e+01, 1.9833500e+02], InputImage\_1 Origin: [0.0000000e+00, 0.0000000e+00, 4.9000000e+01]  
> Tolerance: 1.4063000e-06  
> InputImage Spacing: [1.4063000e+00, 1.4063000e+00, 4.0000020e+00], InputImage\_1 Spacing: [1.0000000e+00, 1.0000000e+00, 1.0000000e+00]  
> Tolerance: 1.4063000e-06  
> InputImage Direction: 1.0000000e+00 0.0000000e+00 0.0000000e+00  
> 0.0000000e+00 -0.0000000e+00 1.0000000e+00  
> 0.0000000e+00 -1.0000000e+00 -0.0000000e+00  
> , InputImage\_1 Direction: 1.0000000e+00 0.0000000e+00 0.0000000e+00  
> 0.0000000e+00 1.0000000e+00 0.0000000e+00  
> 0.0000000e+00 0.0000000e+00 -1.0000000e+00

but if i print `maskImage ` in the code the values of origin, dimension and direction are corrected

---

<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:** [November 15, 2019, 10:26pm UTC](https://discourse.itk.org/t/mha-numpy/2400/15 "2019-11-15T22:26:16Z")

</div>

`ChangeInformationImageFilter` is wrapped. It could be called like this:

```auto
read_image = reader4mm.GetOutput()
maskImage = itk.change_information_image_filter(flipFilter.GetOutput(),
    output_origin=read_image.GetOrigin(),
    output_spacing=read_image.GetSpacing(),
    output_direction=read_image.GetDirection()
)

```

But, depending on what you are trying to do and your data, you may want / need to use `ResampleImageFilter` as suggested earlier.
