如何使用keras加载图像并显示图像?

时间:2017-06-30 08:20:59

标签: python numpy matplotlib tensorflow keras

%matplotlib inline
from keras.preprocessing import image

import matplotlib.pyplot as plt
import numpy as np
img = np.random.rand(224,224,3)
plt.imshow(img)
plt.show()

img_path = "image.jpeg"
img = image.load_img(img_path, target_size=(224, 224))
print(type(img))

x = image.img_to_array(img)
print(type(x))
print(x.shape)
plt.imshow(x)

我有一些这样的代码应该打印图像。但它在错误的频道中显示图像。我在这里缺少什么?

2 个答案:

答案 0 :(得分:6)

这是图像缩放问题。 imshow()的输入要求它在0-1范围内,而你传递的是[0-255]范围输入。尝试将其视为:

plt.imshow(x/255.)

答案 1 :(得分:1)

这个问题有点老了,但是有一个非常舒适的方法 显示图像:

tf.keras.preprocessing.image.array_to_img(image[0]).show()

您的图片必须具有3个尺寸(如果像往常一样成批处理,则只需要desire_element)。在EagerTensors或numpy数组上工作正常。