代码:img = Image.open("test.png").convert('L') img2 = img.resize((28, 28), Image.ANTIALIAS) img_array = np.array(img2),报错Expected type 'Union[ndarray, Iterable, int, float]', got 'Image' instead,如何解决?
时间: 2023-06-04 22:06:57 浏览: 65
您可以尝试将Image类型的图像转换为NumPy数组类型,可以使用np.asarray()函数进行转换,代码如下:
img = Image.open("test.png").convert('L')
img2 = img.resize((28, 28), Image.ANTIALIAS)
img_array = np.asarray(img2)
这样就可以将Image类型的图像转换为NumPy数组类型,避免了报错。
相关问题
我想用保存在params.pkl里的模型参数预测一个像素为28*28的img格式图片是什么字母,你能给我段代码吗?
可以使用以下代码对像素为 28x28 的 img 格式图片进行预测:
```
import pickle
import numpy as np
from PIL import Image
from two_layer_network import TwoLayerNet
# 读取模型参数
with open("params.pkl", "rb") as f:
params = pickle.load(f)
# 加载图片并转换成 784 维向量
img = Image.open("test.png").convert('L')
img = np.array(img.resize((28, 28)))
x = img.reshape(1, -1).astype(np.float32) / 255.0
# 使用训练好的模型参数进行预测
network = TwoLayerNet(input_size=784, hidden_size=70, output_size=26, params=params)
y = network.predict(x)
# 输出预测结果
print(chr(ord('a') + np.argmax(y)))
```
其中,test.png 是待预测的图片,需要放在当前目录下。这段代码会输出该图片预测出来的字母。注意,预测结果是一个概率向量,需要使用 np.argmax 函数找到概率最高的那个字母。
用一个神经元实现MNIST手写数字识别代码: ①直接从Tensorflow获取数据集; ②构建模型; ③训练模型; ④用测试集里的数据进行测试; 将自己制作的手写数字图片(至少3张),经过图像处理,读入程序,扔进训练好的模型中测试,查看模型的效果
好的,以下是用一个神经元实现MNIST手写数字识别的代码。请注意,这个模型的表现可能不会很好,只是为了演示用途。
```python
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# ①获取数据集
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# ②构建模型
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
# ③训练模型
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# ④测试模型
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
# 测试自己的手写数字
from PIL import Image
import numpy as np
# 读取并处理自己的手写数字图片
def read_image(image_path):
img = Image.open(image_path).convert('L')
img = img.resize((28, 28))
img_arr = np.array(img)
img_arr = img_arr.reshape((1, 784))
img_arr = img_arr.astype(np.float32)
img_arr = img_arr / 255.0 # 将像素值归一化到[0,1]之间
return img_arr
# 读取自己的手写数字图片并进行测试
img1 = read_image('1.png')
img2 = read_image('2.png')
img3 = read_image('3.png')
print(sess.run(tf.argmax(y, 1), feed_dict={x: img1}))
print(sess.run(tf.argmax(y, 1), feed_dict={x: img2}))
print(sess.run(tf.argmax(y, 1), feed_dict={x: img3}))
```
注意,这里的`1.png`、`2.png`和`3.png`是我自己生成的手写数字图片,您需要将代码中的图片路径替换为您自己的图片。