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.

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值