Image type for an ITK image from numpy array

Here’s a piece of code I’m trying to run using pydicom and itk (using pydicom for a better dicom tag extraction since itk was failing to get some tags).

ds = pydicom.read_file(file_path)
np_image = ds.pixel_array
itk_image = itk.GetImageFromArray(np.ascontiguousarray(np_image))
lumfilter = itk.RGBToLuminanceImageFilter.New(Input=itk_image)

However, lumfilter fails since it’s expecting an RGB image itkImageRGBUC2, but the image that ITK created from the array is of type itkImageUC3. Is itkCastImageFilter the only way to go, or am I missing something?

Thanks!

Maybe itkImageRGBUC3 is not wrapped by default, so ITK implicitly converts it to scalar?

EDIT: the conversion RGB->Scalar usually uses luminance, so in this case you don’t need RGBToLuminanceImageFilter.

Also, does np.ascontiguousarray(np_image) give an RGB image?

To achieve explicit conversion to an RGB image, we can now call:

ImageType = itk.Image[itk.RGBPixel[itk.UC], 3]
itk_image = itk.PyBuffer[ImageType].GetImageFromArray(np_image)

That said, we can make this similar to the functional ITK Python filter interfaces, support passing a ttype keyword argument to the ITK NumPy interface functions. This will enable explicit specification of the type desired. For example:

ImageType = itk.Image[itk.RGBPixel[itk.UC], 3]
itk_image = itk.image_from_array(np_image, ttype=(ImageType,))

I created this issue to track this.

This just ensures it is a contiguous buffer, which is a requirement for the conversion. But, we are looking to make the conversions required implicit for ITK 5.1b02.

1 Like

Thanks Matt and Dzenan!
The PyBuffer solution worked, but the passing the ttype keyword argument would be great!!

Cheers!
Hina

1 Like

Following-up, ttype is a keyword parameter in itk-5.2rc1 for itk.image_from_array.

Awesome!
Thanks! :slight_smile:

Hope you’re doing well!

Best,
Hina

1 Like