0

I want to directly load image from memory to python in pytorch tensor format. I modified GetArrayViewFromImage() function by replacing those lines:

image_memory_view = _GetMemoryViewFromImage(image)
array_view = numpy.asarray(image_memory_view).view(dtype = dtype)

by:

image_memory_view = _GetMemoryViewFromImage(image)
array_view = torch.as_tensor(image_memory_view, dtype = dtype)

in practise it is so slow I replaced it with:

image_memory_view = _GetMemoryViewFromImage(image)
array_view = numpy.asarray(image_memory_view).view(dtype = dtype)
array_view  = torch.as_tensor(array_view)

Now I have two questions:

  1. it is much slower, and I don't really know why reading it with numpy and converting it is faster.
  2. even though I add the dtype argument and it returns a tensor with a correct dtype it reads it wrong (ex. -1000 in numpy is read as 252 no matter what torch.dtype I choose) which is not a problem when reading with numpy and converting, why is that happening?
Jarartur
  • 149
  • 1
  • 10

1 Answers1

4

While this does not directly answer your question, I strongly recommend using the torchio package, instead of dealing with these IO issues yourself (torchio uses SimpleITK under the hood).

zivy
  • 521
  • 2
  • 2
  • And to follow up, this is how you go from filepath to PyTorch tensor: `import torchio as tio; tensor = tio.ScalarImage(path).data`. – fepegar Apr 16 '21 at 15:52