1
1

More than 3 years have passed since last update.

toimage (from PIL.Image import fromarray as toimage)で出たエラーを解消する方法

Last updated at Posted at 2020-01-04
for i in range(100):
  img = toimage(X_test[i])
  label = results[i].argmax()
  plt.subplot(10, 10, pos)
  plt.imshow(img)
  plt.axis('off')
  plt.title(cifar10_labels[label])
  pos += 1        
plt.show()

を実行してイメージをJupyter notebookに表示させようとしたら、以下のようなエラーが出た。

KeyError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/PIL/Image.py in fromarray(obj, mode)
2415 typekey = (1, 1) + shape[2:], arr['typestr']
-> 2416 mode, rawmode = _fromarray_typemap[typekey]
2417 except KeyError:

KeyError: ((1, 1, 3), '<f4')

During handling of the above exception, another exception occurred:

TypeError Traceback (most recent call last)
1 frames
/usr/local/lib/python3.6/dist-packages/PIL/Image.py in fromarray(obj, mode)
2417 except KeyError:
2418 # print(typekey)
-> 2419 raise TypeError("Cannot handle this data type")
2420 else:
2421 rawmode = mode

TypeError: Cannot handle this data type

コードを以下のように変えると問題が解決した。

for i in range(100):
  scale = 255.0 / np.max(X_test[i])
  img = toimage(np.uint8(X_test[i]*scale))
  label = results[i].argmax()
  plt.subplot(10, 10, pos)
  plt.imshow(img)
  plt.axis('off')
  plt.title(cifar10_labels[label])
  pos += 1        
plt.show()
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1