Set default pixel type for a resample filter in python

Hello community,

I don’t manage to create an arbitrary pixel from a numpy scalar. I would like to transform the numpy scalar to a pixel, using fill if pixel has multiple modalities

px_type = itk.template(itk_image)[1][0]
px_trait = itk.NumericTraits[px_type]
if self.background_value == 'max':
    background_value = px_trait.max()
elif self.background_value == 'min':
    background_value = px_trait.min()
elif np.isscalar(self.background_value):
    # How to do here ??
    background_value = np.ndarray.item(np.asanyarray(self.background_value).astype(np_image.dtype))
    raise NameError('background_value type not recognized. Should be min, max or a scalar.')

# resampler
resampler = itk.ResampleImageFilter.New(Input=itk_image)

I guess I’m missing something, any help ?

Hi @asertyuio,

How about:

elif np.isscalar(self.background_value):
    if hasattr(px_type, 'Fill'):
        background_value = px_type()
        background_value = self.background_value

Great, thanks Matt ! hasattr(px_type, 'Fill') is what I was missing.

Is there a problem if self.background_value is not the same data type as the pixel?

Is it possible I instanciate a single pixel from px_type when it is a scalar ? Basically get a scalar the same type as the one in the image, without knowing the type in advance.

1 Like

:+1: great to hear!

No – there is implicit type conversion in this case. But, it is helpful to be aware of this type conversion.

One possibility is to use the Python int and float datatypes. Python just has these scalars, unlike ITK or NumPy, which support the sized variants.