ANTsX / ANTsPy

A fast medical imaging analysis library in Python with algorithms for registration, segmentation, and more.
https://antspyx.readthedocs.io
Apache License 2.0
648 stars 164 forks source link

Troubles in converting ANTsImage to PIL image. #379

Open gentlezr opened 2 years ago

gentlezr commented 2 years ago

Describe the bug Hi, I have troubles in converting ANTsImage to PIL image. Please run this scripts and you can find that 'fixA2.png' is different to 'A.png' or 'fixA1.png'. It shows that ants.to_file() have some tricks I don't know.

`from PIL import Image import numpy as np import ants

path = 'A.png' to_dir = '.' img = ants.from_numpy(np.array(Image.open(path)))

Image.fromarray(np.array(img.numpy())).save(os.path.join(to_dir, 'fixA1.png')) img.to_file(os.path.join(to_dir, 'fixA2.png'))`

A.png A

fixA1.png image

fixA2.png image

cookpa commented 1 month ago

This happens because ANTsPy expects image indices in row,column (x,y) order, while PIL uses column,row (y,x). So you either need to transpose the numpy matrix, or set the header of the ANTs image - by default it assumes an identity transform between the pixel indices and physical space.

Beware also that the PNG image above has three color channels; I could not read it as RGB but I could do

img = ants.from_numpy(np.array(Image.open(path)), has_components=True)