keras (python)MNIST与本Map片面img AttributeError:'PngImageFile'对象没有'reshape'属性

xdyibdwo  于 2022-11-24  发布在  Python
关注(0)|答案(1)|浏览(263)

环境:谷歌协作、Python
目标:python mnist预测我自己图片
问题:AttributeError: 'PngImageFile' object has no attribute 'reshape'

更新尝试过的代码,并输出

import keras
from keras.datasets import mnist
import matplotlib.pyplot as plt
import PIL
from PIL import Image
(train_images,train_labels),(test_images,test_labels) = mnist.load_data()
train_images.shape
len(train_labels)
train_labels
test_images.shape
len(test_labels)
test_labels

'''plt.imshow(train_images[819], cmap=plt.get_cmap('gray'))
print(train_images[819])
print(train_labels[819])'''

from keras import models
from keras import layers
network = models.Sequential()
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))

network.compile(optimizer='rmsprop',
                loss='categorical_crossentropy',
                metrics=['accuracy'])

train_images = train_images.reshape((60000,28*28))
train_images = train_images.astype('float32')/255
test_images = test_images.reshape((10000,28*28))
test_images = test_images.astype('float32')/255

from keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

network.fit(train_images,train_labels,epochs=1,batch_size=128)

test_loss , test_acc = network.evaluate(test_images,test_labels)
print('test_acc:',test_acc)


network.save('m_lenet.h5')

#########

import numpy as np
from keras.models import load_model
import matplotlib.pyplot as plt
from PIL import Image

model = load_model('/content/m_lenet.h5')

picPath = '/content/00_a.png'
img = Image.open(picPath)

reIm = img.resize((28,28),Image.ANTIALIAS)

im_arr = np.array(reIm.convert("L"))

im1 = img.reshape((1,28*28))
im1 = img.astype('float32')/255

predict = model.predict_classes(im1)
print ('predict as:')
print (predict)
  • 输出:AttributeError: 'PngImageFile' object has no attribute 'reshape'
469/469 [==============================] - 6s 11ms/step - loss: 0.2553 - accuracy: 0.9258
313/313 [==============================] - 1s 3ms/step - loss: 0.1399 - accuracy: 0.9582
test_acc: 0.9581999778747559
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-41-8c95d72a4bf4> in <module>
     68 im_arr = np.array(reIm.convert("L"))
     69 
---> 70 im1 = img.reshape((1,28*28))
     71 im1 = img.astype('float32')/255
     72 

AttributeError: 'PngImageFile' object has no attribute 'reshape'

谷歌colab上的截图链接,以及我希望MNIST预测的图片
https://imgur.com/a/kTtz0ei
图片名称:“00_a.png”
文件名:'/content/00_a.png'

  • “ls”结果:
00_a.png          03_a.png  06_a.png  09_a.png
00_a__result.png  04_a.png  07_a.png  epic_num_reader_joy.model/
02_a.png          05_a.png  08_a.png  m_lenet.h5
02_b.png          05_b.png  09_a.jpg  sample_data/

“00_a.png”在那里,我右击复制路径为:'/内容/00_a.png'
使用以下代码,路径“/content/00_a.png”可以正常工作

import cv2
from  matplotlib import pyplot as plt
%matplotlib inline

im = cv2.imread("/content/00_a.png",1)  # load image as bgr
im2 = im[:,:,::-1]  # transform image to rgb
plt.imshow(im2)
plt.show()

我也在分享链接https://imgur.com/a/kTtz0ei上分享图片
我可以使用路径来调用图片(ps. cv2.imshow将失败,只有plt.show()在google colab中工作)
已尝试导出建议中的代码:

  • 我输入(im_arr)、(reIm)或(img),但它们都得到一些错误

Tensor= tf.keras.utils.img_to_array(im)(用于数组的Tensor)
我在这里截图3个结果https://imgur.com/a/TBU1YW2

import keras
from keras.datasets import mnist
import matplotlib.pyplot as plt
import PIL
from PIL import Image

(train_images,train_labels),(test_images,test_labels) = mnist.load_data()
train_images.shape
len(train_labels)
train_labels
test_images.shape
len(test_labels)
test_labels

'''plt.imshow(train_images[819], cmap=plt.get_cmap('gray'))
print(train_images[819])
print(train_labels[819])'''

from keras import models
from keras import layers
network = models.Sequential()
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))

network.compile(optimizer='rmsprop',
                loss='categorical_crossentropy',
                metrics=['accuracy'])

train_images = train_images.reshape((60000,28*28))
train_images = train_images.astype('float32')/255
test_images = test_images.reshape((10000,28*28))
test_images = test_images.astype('float32')/255

from keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

network.fit(train_images,train_labels,epochs=1,batch_size=128)

test_loss , test_acc = network.evaluate(test_images,test_labels)
print('test_acc:',test_acc)


network.save('m_lenet.h5')

#########

import numpy as np
from keras.models import load_model
import matplotlib.pyplot as plt
from PIL import Image

model = load_model('/content/m_lenet.h5')

picPath = '/content/00_a.png'
img = Image.open(picPath)

# I though I resize here already
reIm = img.resize((28,28),Image.ANTIALIAS)

im_arr = np.array(reIm.convert("L"))

import torch
import tensorflow as tf

# either input (im_arr) or (reIm) or (img), but they all get some error
tensor = tf.keras.utils.img_to_array(im_arr)
im1 = tensor.reshape((1,28*28))
im1 = img.astype('float32')/255

predict = model.predict_classes(im1)
print ('predict as:')
print (predict)

已尝试导出建议中的代码:
数组= np.数组(im)
我在这里截图结果https://imgur.com/a/TBU1YW2

import keras
from keras.datasets import mnist
import matplotlib.pyplot as plt
import PIL
from PIL import Image

(train_images,train_labels),(test_images,test_labels) = mnist.load_data()
train_images.shape
len(train_labels)
train_labels
test_images.shape
len(test_labels)
test_labels

'''plt.imshow(train_images[819], cmap=plt.get_cmap('gray'))
print(train_images[819])
print(train_labels[819])'''

from keras import models
from keras import layers
network = models.Sequential()
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))

network.compile(optimizer='rmsprop',
                loss='categorical_crossentropy',
                metrics=['accuracy'])

train_images = train_images.reshape((60000,28*28))
train_images = train_images.astype('float32')/255
test_images = test_images.reshape((10000,28*28))
test_images = test_images.astype('float32')/255

from keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

network.fit(train_images,train_labels,epochs=1,batch_size=128)

test_loss , test_acc = network.evaluate(test_images,test_labels)
print('test_acc:',test_acc)


network.save('m_lenet.h5')

#########

import numpy as np
from keras.models import load_model
import matplotlib.pyplot as plt
from PIL import Image

model = load_model('/content/m_lenet.h5')

picPath = '/content/00_a.png'
img = Image.open(picPath)

reIm = img.resize((28,28),Image.ANTIALIAS)

# add tried code 
im_arr = np.array(reIm)

import torch
import tensorflow as tf

tensor = tf.convert_to_tensor(im_arr)
im1 = tensor.reshape((1,28*28))
im1 = img.astype('float32')/255

predict = model.predict_classes(im1)
print ('predict as:')
print (predict)
  • 输出:
469/469 [==============================] - 7s 13ms/step - loss: 0.2557 - accuracy: 0.9263
313/313 [==============================] - 1s 3ms/step - loss: 0.1256 - accuracy: 0.9627
test_acc: 0.9627000093460083
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-d999f75eebea> in <module>
     77 
     78 tensor = tf.convert_to_tensor(im_arr)
---> 79 im1 = tensor.reshape((1,28*28))
     80 im1 = img.astype('float32')/255
     81 

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py in __getattr__(self, name)
    443         from tensorflow.python.ops.numpy_ops import np_config
    444         np_config.enable_numpy_behavior()
--> 445       """)
    446     self.__getattribute__(name)
    447 

AttributeError: EagerTensor object has no attribute 'reshape'. 
        If you are looking for numpy-related methods, please run the following:
        from tensorflow.python.ops.numpy_ops import np_config
        np_config.enable_numpy_behavior()
1u4esq0p

1u4esq0p1#

问题不是由于路径。当你用PIL阅读图像(如Png)时,PngImageFile中的类型没有整形方法。整形是针对Tensor类的。将你读取的图像转换为你期望的适当数据格式,然后重新复制并给予给你的模型

tensor = tf.keras.utils.img_to_array(im)

array = np.array(im)
...

顺便说一句,看看你打印的错误,图像大小不能重塑到你感兴趣的大小,首先你应该调整大小,然后转换为Tensor,数组等和重塑。

相关问题