AttributeError: 'memoryview' object has no attribute 'cpu' and RuntimeError: number of dims don't match in permute

Just wanted to help anybody else that runs into this issue when working with show_image in the new fastai library. I had a few issues. The first thing I ran into was AttributeError: 'memoryview' object has no attribute 'cpu'. This was because I was trying to put a numpy.ndarray into show_image which expects a tensor.

To fix this issue I had to wrap my numpy array with torch.as_tensor(numpy_image)

#At this point:
show_image(torch.as_tensor(numpy_array))

This was still failing with a new error though. This time I was getting RuntimeError: number of dims don't match in permute. I was able to fix this issue with a [None]

#Final Working Code:
show_image(torch.as_tensor(numpy_array[None]))

I hope this is able to save somebody some time!

3 Likes

show_image actually expects an Image object, which is what open_image gives you.

I had issues because I didn’t need top open the image, I already had a numpy array. I’m working on the RSNAS Pneumonia detection challenge and they give you .dcm files which have a pixel_array that you can read from them. So I needed to get it from numpy array to Image object. I ended up doing this to get that:

Image(torch.as_tensor(numpy_array[None]))

Correct. That actually seems like a handy function to have, I’ll see if I can put it somewhere.

Cool, I haven’t done much with the new library yet, but I’ll be digging into it more this weekend and I will try to at least put any issues I have and am able to solve on the forums here. So far I am really liking it, but it’s still really early and change is hard. I am really looking forward to learning more about it during Deep Learning Part 1 this fall.

@KevinB I’ve changed it so you can pass an ndarray straight to the Image ctor now.

4 Likes

Apologies for waking up this old thread (I’m novice here). I saw your commit: cast to tensor when creating Image made on 5th of Oct 2018 that added as_tensor cast for px which seemed to work pretty well. However, that was reverted back in next day’s commit BBox cast to int. Therefore, ndarray as an argument is still not working.

1 Like