plt.imshow() gives TypeError: Image data of dtype object cannot be converted to float using PyTorch
I am trying to create a custom Dataset Processor for a set of images. However, when I try to view the images in my dataset, I get hit with the TypeError: Image data of dtype object cannot be converted to float. 

I tried to check if I am passing in a PIL Image into the plt.imshow() function and I am.

class DatasetProcessing(Dataset):

    def __init__(self, input_data, output_data, transform=None): 
        self.transform = transform
        self.input_data = 
        input_data.reshape((-1,64,64)).astype(np.float32)[:,:,:,None]
        self.output_data = output_data 

    def __getitem__(self, index): 
        return self.transform(self.input_data[index]), self.output_data[index]

    def __len__(self): 
        return len(list(self.input_data))

transform = transforms.Compose([transforms.ToPILImage()])


dset_train = DatasetProcessing(X_slices_train, Y_train, transform)


train_loader = torch.utils.data.DataLoader(dset_train, batch_size=4, 
                                      shuffle=True, num_workers=4) 

plt.figure(figsize = (16, 4))
for num, x in enumerate(dset_train):
    plt.subplot(1,6,num+1)
    plt.axis('off')
    print(x)
    plt.imshow(np.asarray(x))
    plt.title(y_train[num])


I expected to get pictures of my dataset, but instead I get the following error message:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-10-8b8caac49d97&gt; in &lt;module&gt;
      4     plt.axis('off')
      5     print(x)
----&gt; 6     plt.imshow(np.asarray(x))
      7     plt.title(y_train[num])

~/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, data, **kwargs)
   2675         filternorm=filternorm, filterrad=filterrad, imlim=imlim,
   2676         resample=resample, url=url, **({"data": data} if data is not
-&gt; 2677         None else {}), **kwargs)
   2678     sci(__ret)
   2679     return __ret

~/anaconda3/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
   1587     def inner(ax, *args, data=None, **kwargs):
   1588         if data is None:
-&gt; 1589             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1590 
   1591         bound = new_sig.bind(ax, *args, **kwargs)

~/anaconda3/lib/python3.7/site-packages/matplotlib/cbook/deprecation.py in wrapper(*args, **kwargs)
    367                 f"%(removal)s.  If any parameter follows {name!r}, they "
    368                 f"should be pass as keyword, not positionally.")
--&gt; 369         return func(*args, **kwargs)
    370 
    371     return wrapper

~/anaconda3/lib/python3.7/site-packages/matplotlib/cbook/deprecation.py in wrapper(*args, **kwargs)
    367                 f"%(removal)s.  If any parameter follows {name!r}, they "
    368                 f"should be pass as keyword, not positionally.")
--&gt; 369         return func(*args, **kwargs)
    370 
    371     return wrapper

~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)
   5658                               resample=resample, **kwargs)
   5659 
-&gt; 5660         im.set_data(X)
   5661         im.set_alpha(alpha)
   5662         if im.get_clip_path() is None:

~/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in set_data(self, A)
    676                 not np.can_cast(self._A.dtype, float, "same_kind")):
    677             raise TypeError("Image data of dtype {} cannot be converted to "
--&gt; 678                             "float".format(self._A.dtype))
    679 
    680         if not (self._A.ndim == 2

TypeError: Image data of dtype object cannot be converted to float


Your dset_train yields self.transform(self.input_data[index]), self.output_data[index] if understood correctly self.transform(self.input_data[index]) is an image tensor (data) and self.output_data[index] is a label, but here: 

plt.imshow(np.asarray(x))


you are passing unpacked x which is actually (data, label)

So, you need to unpack it first:

plt.figure(figsize = (16, 4))
for num, x in enumerate(dset_train):
    data, label = x
    plt.subplot(1,6,num+1)
    plt.axis('off')
    print(x)
    plt.imshow(np.asarray(data))
    plt.title(y_train[num])


EDIT:


  Why I have to unpack x?


You're inheriting from PyTorch's Dataset, and according to docs:


  All datasets that represent a map from keys to data samples should subclass it. All subclasses should overrite __getitem__(), supporting fetching a data sample for a given key.


In your defined DatasetProcessing class __getitem__() returns a tuple of 2 items: self.transform(self.input_data[index]) and self.output_data[index], the first one is data, the second one is appropriate label. And that's why you need to unpack it like data, y = x, because your DatasetProcessing dataset yields data and a label.


  Is there any documentation/tutorials you can link me to?


I can recommend you this links:


Data Loading and Processing Tutorial
Dataset docs 
torch.utils.data docs

