Image. fromarray() throws up error TypeError: Cannot handle this data type

I am trying to make a custom dataset, But as I convert it to PIL image, I am Getting the error:
TypeError: Cannot handle this data type

> class Gen_Data(Dataset):
> >         def __init__(self, p, transform = None):
> >                 super(Gen_Data,self).__init__()
> >                 self.data = []
> >                 self.transform = transform
> > 
> >                 for v in p:
> >                         (self.data).append(v)
> > 
> >         def __getitem__(self, index):
> >                 img = np.asarray(self.data[index],dtype=np.uint8)
> >                 print (img)
> >                 print (type(img))
> >                 img = Image.fromarray(img.astype('uint8'))
> > 
> >                 if self.transform is not None:
> >                         img  = self.transform(img)
> > 
> >                 return (img)
> > 
> >         def __len__(self):
> >                 return len(self.data)

Where p is a numpy nd array.
I am not quite understanding, how do I overcome this issue.

Traceback (most recent call last):
** File “/usr/local/torch3/lib/python3.5/site-packages/PIL/Image.py”, line 2428, in fromarray**
** mode, rawmode = _fromarray_typemap[typekey]**
KeyError: ((1, 1, 64), ‘|u1’)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
** File “pytorch_CelebA_DCGAN.py”, line 343, in **
** print (inception_score.inception_score(our_dataset, cuda=True, batch_size=32, resize=True, splits=10))**
** File “/home/bansa01/spectral_normalization/DCGAN-Pytorch2/DCGAN/inception_score.py”, line 50, in inception_score**
** for i, batch in enumerate(dataloader, 0):**
** File “/usr/local/torch3/lib/python3.5/site-packages/torch/utils/data/dataloader.py”, line 259, in next**
** batch = self.collate_fn([self.dataset[i] for i in indices])**
** File “/usr/local/torch3/lib/python3.5/site-packages/torch/utils/data/dataloader.py”, line 259, in **
** batch = self.collate_fn([self.dataset[i] for i in indices])**
** File “pytorch_CelebA_DCGAN.py”, line 37, in getitem**
** img = Image.fromarray(img.astype(‘uint8’))**
** File “/usr/local/torch3/lib/python3.5/site-packages/PIL/Image.py”, line 2431, in fromarray**
** raise TypeError(“Cannot handle this data type”)**
TypeError: Cannot handle this data type

Have you handled this problem?

maybe you can input like img = Image.fromarray(np.uint8(img)) instead of img = Image.fromarray(img.astype(‘uint8’))

1 Like

Hi there! May I ask what’s the difference between “np.uint8(img)” and “img.astype(‘uint8’)”? Cause I’ve been encountered this TypeError lately. Thanx a lot!