How to convert a memmap to tensor

(wxystudio) #1

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
plt.show()

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

(tymokvo) #2

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.

EDIT:

Looks like you can just call:

torch.from_numpy(image_data) 
1 Like
(wxystudio) #3

thx very much, it works

1 Like