python与深度学习(八):CNN和fashion_mnist二

news/2024/5/21 13:55:43

目录

  • 1. 说明
  • 2. fashion_mnist的CNN模型测试
    • 2.1 导入相关库
    • 2.2 加载数据和模型
    • 2.3 设置保存图片的路径
    • 2.4 加载图片
    • 2.5 图片预处理
    • 2.6 对图片进行预测
    • 2.7 显示图片
  • 3. 完整代码和显示结果
  • 4. 多张图片进行测试的完整代码以及结果

1. 说明

本篇文章是对上篇文章训练的模型进行测试。首先是将训练好的模型进行重新加载,然后采用opencv对图片进行加载,最后将加载好的图片输送给模型并且显示结果。

2. fashion_mnist的CNN模型测试

2.1 导入相关库

在这里导入需要的第三方库如cv2,如果没有,则需要自行下载。

from tensorflow import keras
import skimage, os, sys, cv2
from PIL import ImageFont, Image, ImageDraw  # PIL就是pillow包(保存图像)
import numpy as np
# 导入tensorflow
import tensorflow as tf
# 导入keras
from tensorflow import keras
from keras.datasets import fashion_mnist

2.2 加载数据和模型

把fashion_mnist数据集进行加载,并且把训练好的模型也加载进来。

# fashion数据集列表
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# 加载fashion数据
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
# 加载cnn_fashion.h5文件,重新生成模型对象
recons_model = keras.models.load_model('cnn_fashion.h5')

2.3 设置保存图片的路径

将数据集的某个数据以图片的形式进行保存,便于测试的可视化。
在这里设置图片存储的位置。

# 创建图片保存路径
test_file_path = os.path.join(sys.path[0], 'imgs', 'test100.png')
# 存储测试数据的任意一个
Image.fromarray(x_test[100]).save(test_file_path)

在书写完上述代码后,需要在代码的当前路径下新建一个imgs的文件夹用于存储图片,如下。
在这里插入图片描述

执行完上述代码后就会在imgs的文件中可以发现多了一张图片,如下(下面测试了很多次)。
在这里插入图片描述

2.4 加载图片

采用cv2对图片进行加载,下面最后一行代码取一个通道的原因是用opencv库也就是cv2读取图片的时候,图片是三通道的,而训练的模型是单通道的,因此取单通道。

# 加载本地test.png图像
image = cv2.imread(test_file_path)
# 复制图片
test_img = image.copy()
# 将图片大小转换成(28,28)
test_img = cv2.resize(test_img, (28, 28))
# 取单通道值
test_img = test_img[:, :, 0]

2.5 图片预处理

对图片进行预处理,即进行归一化处理和改变形状处理,这是为了便于将图片输入给训练好的模型进行预测。

# 预处理: 归一化 + reshape
new_test_img = (test_img/255.0).reshape(1, 28, 28, 1)

2.6 对图片进行预测

将图片输入给训练好我的模型并且进行预测。
预测的结果是10个概率值,所以需要进行处理, np.argmax()是得到概率值最大值的序号,也就是预测的数字。

# 预测
y_pre_pro = recons_model.predict(new_test_img, verbose=1)
# 哪一类
class_id = np.argmax(y_pre_pro, axis=1)[0]
print('test.png的预测概率:', y_pre_pro)
print('test.png的预测概率:', y_pre_pro[0, class_id])
print('test.png的所属类别:', class_names[class_id])
text = str(class_names[class_id])

2.7 显示图片

对预测的图片进行显示,把预测的数字显示在图片上。
下面5行代码分别是创建窗口,设定窗口大小,显示图片,停留图片,清除内存。

# # 显示
cv2.namedWindow('img', 0)
cv2.resizeWindow('img', 500, 500)  # 自己设定窗口图片的大小
cv2.imshow('img', image)
cv2.waitKey()
cv2.destroyAllWindows()

3. 完整代码和显示结果

以下是完整的代码和图片显示结果。

from tensorflow import keras
import skimage, os, sys, cv2
from PIL import ImageFont, Image, ImageDraw  # PIL就是pillow包(保存图像)
import numpy as np
# 导入tensorflow
import tensorflow as tf
# 导入keras
from tensorflow import keras
from keras.datasets import fashion_mnist
# fashion数据集列表
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# 加载fashion数据
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
# 加载cnn_fashion.h5文件,重新生成模型对象
recons_model = keras.models.load_model('cnn_fashion.h5')
# 创建图片保存路径
test_file_path = os.path.join(sys.path[0], 'imgs', 'test100.png')
# 存储测试数据的任意一个
Image.fromarray(x_test[100]).save(test_file_path)
# 加载本地test.png图像
image = cv2.imread(test_file_path)
# 复制图片
test_img = image.copy()
# 将图片大小转换成(28,28)
test_img = cv2.resize(test_img, (28, 28))
# 取单通道值
test_img = test_img[:, :, 0]
# 预处理: 归一化 + reshape
new_test_img = (test_img/255.0).reshape(1, 28, 28, 1)
# 预测
y_pre_pro = recons_model.predict(new_test_img, verbose=1)
# 哪一类
class_id = np.argmax(y_pre_pro, axis=1)[0]
print('test.png的预测概率:', y_pre_pro)
print('test.png的预测概率:', y_pre_pro[0, class_id])
print('test.png的所属类别:', class_names[class_id])
text = str(class_names[class_id])
# # 显示
cv2.namedWindow('img', 0)
cv2.resizeWindow('img', 500, 500)  # 自己设定窗口图片的大小
cv2.imshow('img', image)
cv2.waitKey()
cv2.destroyAllWindows()
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
1/1 [==============================] - 0s 168ms/step
test.png的预测概率: [[2.9672831e-04 7.3040414e-05 1.4721525e-04 9.9842703e-01 4.7597905e-068.9959512e-06 1.0416918e-03 8.6147125e-09 4.2549357e-07 1.2974965e-07]]
test.png的预测概率: 0.99842703
test.png的所属类别: Dress

在这里插入图片描述

4. 多张图片进行测试的完整代码以及结果

为了测试更多的图片,引入循环进行多次测试,效果更好。

from tensorflow import keras
from keras.datasets import fashion_mnist
import skimage, os, sys, cv2
from PIL import ImageFont, Image, ImageDraw  # PIL就是pillow包(保存图像)
import numpy as np# fashion数据集列表
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# 加载mnist数据
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
# 加载cnn_fashion.h5文件,重新生成模型对象
recons_model = keras.models.load_model('cnn_fashion.h5')prepicture = int(input("input the number of test picture :"))
for i in range(prepicture):path1 = input("input the test picture path:")# 创建图片保存路径test_file_path = os.path.join(sys.path[0], 'imgs', path1)# 存储测试数据的任意一个num = int(input("input the test picture num:"))Image.fromarray(x_test[num]).save(test_file_path)# 加载本地test.png图像image = cv2.imread(test_file_path)# 复制图片test_img = image.copy()# 将图片大小转换成(28,28)test_img = cv2.resize(test_img, (28, 28))# 取单通道值test_img = test_img[:, :, 0]# 预处理: 归一化 + reshapenew_test_img = (test_img/255.0).reshape(1, 28, 28, 1)# 预测y_pre_pro = recons_model.predict(new_test_img, verbose=1)# 哪一类数字class_id = np.argmax(y_pre_pro, axis=1)[0]print('test.png的预测概率:', y_pre_pro)print('test.png的预测概率:', y_pre_pro[0, class_id])print('test.png的所属类别:', class_names[class_id])text = str(class_names[class_id])# # 显示cv2.namedWindow('img', 0)cv2.resizeWindow('img', 500, 500)  # 自己设定窗口图片的大小cv2.imshow('img', image)cv2.waitKey()cv2.destroyAllWindows()
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
input the number of test picture :2
input the test picture path:101.jpg
input the test picture num:1
1/1 [==============================] - 0s 145ms/step
test.png的预测概率: [[5.1000708e-05 2.9449904e-13 9.9993873e-01 5.5402721e-11 4.8696438e-061.2649738e-12 5.3379590e-06 6.5959898e-17 7.1223938e-10 4.0113624e-12]]
test.png的预测概率: 0.9999387
test.png的所属类别: Pullover

在这里插入图片描述

input the test picture path:102.jpg
input the test picture num:2
1/1 [==============================] - 0s 21ms/step
test.png的预测概率: [[3.01315001e-10 1.00000000e+00 1.03142118e-14 8.63922683e-114.10812981e-11 6.07313693e-22 2.31636132e-09 5.08595438e-251.02018335e-13 8.82350167e-28]]
test.png的预测概率: 1.0
test.png的所属类别: Trouser

在这里插入图片描述


http://www.mrgr.cn/p/74766672

相关文章

springboot整合myabtis+mysql

一、pom.xml <!--mysql驱动包--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--springboot与JDBC整合包--><dependency><groupId>org.springframework.b…

第十章:重新审视扩张卷积:一种用于弱监督和半监督语义分割的简单方法

0.摘要 尽管取得了显著的进展&#xff0c;弱监督分割方法仍然不如完全监督方法。我们观察到性能差距主要来自于它们在从图像级别监督中学习生成高质量的密集目标定位图的能力有限。为了缓解这样的差距&#xff0c;我们重新审视了扩张卷积[1]并揭示了它如何以一种新颖的方式被用…

开源视频监控管理平台国标GB28181视频EasyCVR电子地图功能展示优化

视频汇聚平台EasyCVR可拓展性强、视频能力灵活、部署轻快&#xff0c;可支持的主流标准协议有国标GB28181、RTSP/Onvif、RTMP等&#xff0c;以及厂家私有协议与SDK接入&#xff0c;包括海康Ehome、海大宇等设备的SDK等。视频监控综合管理平台EasyCVR可提供的视频能力包括&#…

ssh安全远程管理

目录 1、什么是ssh 2、ssh登陆 3、ssh文件传输 1、什么是ssh ssh是 Secure Shell 的缩写&#xff0c;是一个建立在应用层上的安全远程管理协议。ssh 是目前较为可靠的传输协议&#xff0c;专为远程登录会话和其他网络服务提供安全性。利用ssh 协议可以有效防止远程管理过程中…

macos下安装john the ripper并配置zip2john+破解加密zip文件

为了破解加密的zip文件&#xff0c;需要用到john进行爆破密码。 1、首先使用homebrew安装john&#xff0c;可以安装它的增强版john-jumbo: brew install john-jumbo 2、安装后可以使用 john 命令验证&#xff1a; john 3、配置zip2john的环境——.zshrc下&#xff0c;&#x…

[php-cos]ThinkPHP项目集成腾讯云储存对象COS

Cos技术文档 1、安装phpSdk 通过composer的方式安装。 1.1 在composer.json中添加 qcloud/cos-sdk-v5: >2.0 "require": {"php": ">7.2.5","topthink/framework": "^6.1.0","topthink/think-orm": "…

《吐血整理》进阶系列教程-拿捏Fiddler抓包教程(17)-Fiddler如何充当第三者再识AutoResponder标签-下

1.简介 上一篇宏哥主要讲解的一些在电脑端的操作和应用&#xff0c;今天宏哥讲解和分享一下&#xff0c;在移动端的操作和应用。其实移动端和PC端都是一样的操作&#xff0c;按照宏哥前边抓取移动端包设置好&#xff0c;就可以开始实战了。 2.界面功能解析 根据下图图标注位…

同一数据集(相同路径)的 FID 为负数

公众号&#xff1a;EDPJ 先说结论&#xff1a;这是算法中对复数取实部的结果&#xff0c;对 FID 的影响不大。 FID是从原始图像的计算机视觉特征的统计方面&#xff0c;来衡量两组图像的相似度&#xff0c;是计算真实图像和生成图像的特征向量之间距离的一种度量。 这种视觉特…

号称永不限速的它抛弃初心,网盘界从此再无净土

自从百度网盘一家独大&#xff0c;带来免费用户 KB/s 级下载体验后&#xff0c;小忆一直在期待一款免费不限速网盘。 直到阿里云盘的出现可算是满足了小忆对网盘的所有期许。 新用户初始免费容量尽管只有 100G&#xff0c;但当初通过几个简单小任务就能轻松提升至数 TB。 最重…

全方位支持图文和音视频、100+增强功能,Facebook开源数据增强库AugLy

Facebook 近日开源了数据增强库 AugLy&#xff0c;包含四个子库&#xff0c;每个子库对应不同的模态&#xff0c;每个库遵循相同的接口。支持四种模态&#xff1a;文本、图像、音频和视频。 最近&#xff0c;Facebook 开源了一个新的 Python 库——AugLy&#xff0c;该库旨在帮…

LeetCode 刷题 数据结构 数组 485 最大连续1的个数

给定一个二进制数组 nums &#xff0c; 计算其中最大连续 1 的个数。 示例 1&#xff1a; 输入&#xff1a;nums [1,1,0,1,1,1] 输出&#xff1a;3 解释&#xff1a;开头的两位和最后的三位都是连续 1 &#xff0c;所以最大连续 1 的个数是 3.示例 2: 输入&#xff1a;nums […

iOS--runtime

什么是Runtime runtime是由C和C、汇编实现的一套API&#xff0c;为OC语言加入了面向对象、运行时的功能运行时&#xff08;runtime&#xff09;将数据类型的确定由编译时推迟到了运行时平时编写的OC代码&#xff0c;在程序运行过程中&#xff0c;最终会转换成runtime的C语言代…

分享200+个关于AI的网站

分享200个关于AI的网站 欢迎大家访问&#xff1a;https://tools.haiyong.site/ai 快速导航 AI 应用AI 写作AI 编程AI 设计AI 作图AI 训练模型AI 影音编辑AI 效率助手 AI 应用 文心一言: https://yiyan.baidu.com/ 百度出品的人工智能语言模型 ChatGPT: https://chat.openai.c…

2023年值得推荐的5个数据可视化平台

之前看过一篇介绍20款国外常用的数据可视化工具后&#xff0c;很多朋友在评论区表示国内也有很多很不错的主流数据可视化平台&#xff0c;今天就来给大家介绍国内5个主流的数据可视化平台。 1、阿里云DataV DataV数据可视化是使用可视化应用的方式来分析并展示庞杂数据的产品。…

大数据课程D7——hadoop的YARN

文章作者邮箱&#xff1a;yugongshiyesina.cn 地址&#xff1a;广东惠州 ▲ 本章节目的 ⚪ 了解YARN的概念和结构&#xff1b; ⚪ 掌握YARN的资源调度流程&#xff1b; ⚪ 了解Hadoop支持的资源调度器&#xff1a;FIFO、Capacity、Fair&#xff1b; ⚪ 掌握YA…

Django实现音乐网站 ⑴

使用Python Django框架制作一个音乐网站。 目录 网站功能模块 安装django 创建项目 创建应用 注册应用 配置数据库 设置数据库配置 设置pymysql库引用 创建数据库 创建数据表 生成表迁移文件 执行表迁移 后台管理 创建管理员账户 启动服务器 登录网站 配置时区…

SpringBoot整合ActiveMQ

ActiveMQ简单使用 JMS ActiveMQ 下载安装 https://activemq.apache.org/components/classic/download/解压缩文件。进入win64目录&#xff0c;双击运行activemq.bat文件&#xff0c;运行服务 将下面的网址输入到浏览器&#xff0c;用户名和密码都是admin SpringBoot整合Act…

flutter 导出iOS问题2

问题1:The Swift pod FirebaseCoreInternal depends upon GoogleUtilities, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries) 参考 正如上图报错第三方…

Java 源码打包 降低jar大小

这里写目录标题 Idea maven 插件配置pom.xml 配置启动技巧 Idea maven 插件配置 pom.xml 配置 <build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><!-- 只…

不同局域网下使用Python自带HTTP服务进行文件共享「端口映射」

文章目录 1. 前言2. 视频教程3. 本地文件服务器搭建3.1 python的安装和设置3.2 cpolar的安装和注册 4. 本地文件服务器的发布4.1 Cpolar云端设置4.2 Cpolar本地设置 5. 公网访问测试6. 结语 1. 前言 数据共享作为和连接作为互联网的基础应用&#xff0c;不仅在商业和办公场景有…