tensorflow minst应用 识别任意图片的数字类别
代码托管在github
https://github.com/sofiathefirst/AIcode
1.用画图工具建立一个28*28的图片
2.
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
import tensorflow as tf
import scipy.misc
import matplotlib
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
import cv2
#imread(filename[, flags]) -> retval
imgPath = '/home/q/Desktop/3.jpg' #图片路径
#默认读取的是RGB三色图,得到三维矩阵
img = cv2.imread(imgPath,cv2.IMREAD_GRAYSCALE)
cv2.imshow(str(y_test[1]),x_test[1,:,:])
cv2.waitKey(1)
cv2.imshow(str(y_test[3]),x_test[3,:,:])
cv2.waitKey(1)
cv2.destroyAllWindows()
temp = cv2.imread('/home/q/Desktop/8.jpg',cv2.IMREAD_GRAYSCALE)
#等价于img = cv2.imread('test01.jpg',cv2.IMREAD_COLOR)
#查看图像维数(719,1280,3)
print(img)
scipy.misc.imsave('/home/q/Desktop/n2.png',x_test[1,:,:])
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
temp = cv2.imread('/home/q/Desktop/n5.png',cv2.IMREAD_GRAYSCALE)
temp = 1-temp/255.0
t3 = temp.reshape(1,28,28)
print('n5.png is:',model.predict_classes(t3,1)[0])
运行结果:('n5.png is:', 5)
>>> temp = cv2.imread('/home/q/Desktop/n5.png',cv2.IMREAD_GRAYSCALE)
>>> temp = 1-temp/255.0
>>> t3 = temp.reshape(1,28,28)
>>> model.predict_classes(t3,1)
array([5])
>>> print('n5.png is:',model.predict_classes(t3,1)[0])
('n5.png is:', 5)
>>> temp = cv2.imread('/home/q/Desktop/n7.png',cv2.IMREAD_GRAYSCALE)
>>> temp.shape
(28, 28)
>>> temp = 1-temp/255.0
>>> t3 = temp.reshape(1,28,28)
>>> model.predict_classes(t3,1)
array([7])
>>> model.predict(t3,1)
array([[1.3389438e-04, 1.3672179e-04, 3.0890538e-03, 1.4885775e-03,
1.4848561e-09, 5.9592289e-06, 2.0384711e-07, 9.9512684e-01,
1.2064476e-05, 6.7144374e-06]], dtype=float32)
>>>
predict返回每个类的概率,是7的概率为99.51%,最大,所以predict_classes返回7.