How to convert a memmap to tensor

I use nibabel lib to read some 3D image, which are saved as ‘XX.nii’, After I read the image from file, the data type is <class ‘numpy.memmap’>, I want to use this image for 3D convolution, so I try to convert this data to tensor. How can I do with this problem? Please help me, there is the code as follow

import nibabel as nib
import matplotlib.pyplot as plt
import pdb
from torchvision import transforms as T
import torch
from torchvision.datasets import ImageFolder
import numpy as np

def read_data(path):
image_data = nib.load(path).get_data()
return image_data

def show_img(ori_img):
plt.imshow(ori_img[:,:,85], cmap = ‘gray’) #channel_last

path = ‘D:/wxydataset/forWang/sunjian/IOP-IXI006-p6.nii’
data = read_data(path)

Check the numpy docs:

im_array = np.array(image_data) # image_data is the memmap

im_tensor = torch.from_numpy(im_array)

Something like this should work.


Looks like you can just call:

1 Like

thx very much, it works

1 Like

Not to resuscitate this, but if someone ends up here being interested in a memmap tensor this is something that is provided by torchrl: