日常学习记录——pycharm+tensorflow简单图像识别
日常学习记录——pycharm+tensorflow简单图像识别
- 写在前面
- 1 实验代码
- 2 实验结果
- 2.1 测试集的正确率
- 2.2 单个预测结果
- 2.3 集体预测结果
- 总结与标记
写在前面
使用pycharm+tensorflow实现对bus和taxi数据集进行识别和分类,具体参考文献如下:
1 具体实现教程: Python深度学习之图像识别。
2 开发平台搭建教程:Win-10 安装 TensorFlow-GPU。
3 实验数据集来源:深度学习训练自己的数据集(车辆图像识别分类)。
1 实验代码
import os
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from sklearn.model_selection import train_test_split# 导入bus图片
filedir = 'E:/My Word/Downloads/train/bus/'
os.listdir(filedir)
file_list1 = []
for root, dirs, files in os.walk(filedir):for file in files:if os.path.splitext(file)[1] == '.jpg':file_list1.append(os.path.join(root, file))print(root, file)print(len(root))# 批量改变图片像素
for filename in file_list1:try:im = Image.open(filename)new_im = im.resize((128, 128))new_im.save('E:/My Word/CNN/bus_128/' + filename[31:-4] + '.jpg')print('图片' + filename[12:-4] + '.jpg' + '像素转换完成')except OSError as e:print(e.args)# 重新建立新图像列表
filedir = 'E:/My Word/CNN/bus_128/'
os.listdir(filedir)file_list_1 = []
for root, dirs, files in os.walk(filedir):for file in files:if os.path.splitext(file)[1] == '.jpg':file_list_1.append(os.path.join(root, file))# 导入taxi图片
filedir = 'E:/My Word/Downloads/train/taxi/'
os.listdir(filedir)
file_list2 = []
for root, dirs, files in os.walk(filedir):for file in files:if os.path.splitext(file)[1] == '.jpg':file_list2.append(os.path.join(root, file))print(root, file)print(len(root))# 批量改变图片像素
for filename in file_list2:try:im = Image.open(filename)new_im = im.resize((128, 128))new_im.save('E:/My Word/CNN/taxi_128/' + filename[31:-4] + '.jpg')print('图片' + filename[12:-4] + '.jpg' + '像素转换完成')except OSError as e:print(e.args)# 重新建立新图像列表
filedir = 'E:/My Word/CNN/taxi_128/'
os.listdir(filedir)file_list_2 = []
for root, dirs, files in os.walk(filedir):for file in files:if os.path.splitext(file)[1] == '.jpg':file_list_2.append(os.path.join(root, file))# 合并列表数据
file_list_all = file_list_1 + file_list_2# 将图片数据转为数组
M = []
width, height = 0, 0
for filename in file_list_all:im = Image.open(filename)width, height = im.sizeim_L = im.convert("L")Core = im_L.getdata()arr1 = np.array(Core, dtype='float32') / 255.0np.shape(arr1)list_img = arr1.tolist()M.extend(list_img)X = np.array(M).reshape(len(file_list_all), width, height)
np.shape(X)class_names = ['bus', 'taxi']
# 用字典存储标签信息
dict_label = {0: 'bus', 1: 'taxi'}
print(dict_label[0])
print(dict_label[1])
# 用列表输入标签,0表示bus,1表示taxi
label = [0] * len(file_list_1) + [1] * len(file_list_2)
y = np.array(label)# 按照4:1划分训练集和数据集
train_images, test_images, train_labels, test_labels = train_test_split(X, y, test_size=0.2, random_state=0)# 显示来自训练集的前25个图像,并显示类名
# 验证数据格式是否正确,准备构建神经网络
plt.figure(figsize=(10, 10))
for i in range(25):plt.subplot(5, 5, i + 1)plt.xticks([])plt.yticks([])plt.grid(False)plt.imshow(train_images[i], cmap=plt.cm.binary)plt.xlabel(class_names[train_labels[i]])
plt.show()# 训练神经网络
# 第一个输入层有128个节点
# 第二层是两个节点的softmax层——返回2个概率分数的数组,其和为1.
# 每个节点包含一个分数,表示当前图像属于两个类别的概率。
model = keras.Sequential([keras.layers.Flatten(input_shape=(128, 128)),keras.layers.Dense(128, activation=tf.nn.relu),keras.layers.Dense(2, activation=tf.nn.softmax)
])model.compile(optimizer=tf.keras.optimizers.Adam(),loss='sparse_categorical_crossentropy',metrics=['accuracy'])model.fit(train_images, train_labels, epochs=5)
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)# 定义画图函数
def plot_image(i, predictions_array, true_label, img):predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]plt.grid(False)plt.xticks([])plt.yticks([])plt.imshow(img, cmap=plt.cm.binary)predicted_label = np.argmax(predictions_array)if predicted_label == true_label:color = '#00bc57'else:color = 'red'plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],100 * np.max(predictions_array),class_names[true_label]),color=color)def plot_value_array(i, predictions_array, true_label):predictions_array, true_label = predictions_array[i], true_label[i]plt.grid(False)plt.xticks([])plt.yticks([])thisplot = plt.bar(range(len(class_names)), predictions_array,color='#FF7F0E', width=0.2)plt.ylim([0, 1])predicted_label = np.argmax(predictions_array)thisplot[predicted_label].set_color('red')thisplot[true_label].set_color('#00bc57')# 预测单个
i = 29
plt.figure(figsize=(6, 3))
plt.subplot(1, 2, 1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1, 2, 2)
plot_value_array(i, predictions, test_labels)
plt.show()# 集中预测
num_rows = 7
num_cols = 4
num_images = num_rows * num_cols
plt.figure(figsize=(2 * 2 * num_cols, 2 * num_rows))
for i in range(num_images):plt.subplot(num_rows, 2 * num_cols, 2 * i + 1)plot_image(i, predictions, test_labels, test_images)plt.subplot(num_rows, 2 * num_cols, 2 * i + 2)plot_value_array(i, predictions, test_labels)
plt.show()
2 实验结果
2.1 测试集的正确率
2.2 单个预测结果
对测试集第29张图片进行预测和判断:
2.3 集体预测结果
对测试集前32张图片进行预测:
总结与标记
1、总结:今天花了很多时间在配置开发环境上面,具体代码实现的时间和开发环境搭建的时间是差不多的。
2、标记:目前只是对bus和taxi进行了二分类识别的情况。
日常学习记录——pycharm+tensorflow简单图像识别相关推荐
- 日常学习记录——决策树根节点的选择
日常学习记录--决策树根节点的选择 1 数据集 2 根节点的选择 1 信息增益的计算 2 计算单列属性信息熵 3 计算各属性信息增益 3 存在问题与反思 1 数据集 本例使用的是经过预处理的模糊数据集 ...
- 日常学习记录一_mcufly串口下载
MCUFLY下载 环境是STM32f407 第一部分 操作步骤 板卡部分注意板卡的引脚,boot0接高电平,boot1接低电平. 电脑打开mcufly,电脑通过usb串口线,连接STM32的USART ...
- 深度学习篇之tensorflow(2) ---图像识别
tensorflow处理图像识别 图像识别 图像识别的关键点及特点 卷积神经网络原理 视觉生物学研究 神经网络优势 卷积层 池化层 正则化层 卷积神经网络实例 样本数据读取 urlretrieve() ...
- Java开发指导记录表_java 日常学习记录
前言:记录自己初学java 遇到的问题. 环境(win10 开始安装的IDEA,net 开发者 )学习网址:http://how2j.cn/stage/14.html (不是打广告) 特别是对初学 ...
- Python学习记录 使用tensorflow 2.8 完成猫狗识别 使用keras构建CNN神经网络
猫狗识别 项目数据分为带标签和不带标签 带标签:25000张 不带标签:12500张 文章目录 猫狗识别 数据分类处理 图像增强预处理 编写神经网络结构 设置模型保存路径 输入样本进入模型进行训练 加 ...
- 日常学习记录——目前学习记录总结
1 已了解或已实践内容 1. 机器学习算法相关 常用的两个算法库:sklearn.imbalanced-learn. 决策树算法--基于信息熵.基于信息增益.基于Gini指数 模糊决策树算法--决策树 ...
- react脚手架日常学习记录
文章目录 一. 初始化React脚手架 1.基础相关 2.创建项目 3.脚手架项目结构 4.流程相关 二. 规范相关 三. input相关 四. react父子组件传值 五. TodoList案例小总 ...
- 懒癌患者的学习记录之JAVA简单选择排序
简单选择排序 简单选择排序基本思虑 1.简单来说就是找到数组中最小的放到0,第二小的放到1,以此类推. 2.首先假设第0个值为最小 3.然后从他后面的值找到比他小的,设那个值为最小,以此类推,直到最后 ...
- 懒癌患者的学习记录之JAVA简单插入排序
简单插入排序 简单插入排序的基本思路 1.将数组的前n个数视为一个有序数列(先将第一个数视为有序数列,然后前两个数,再前三个数) 2.将第n+1与前面的所有数进行比较,找到该数所在位置将其插入(其他数 ...
最新文章
- free崩溃原因2021
- python库的使用手册_​Python 常用库之 psutil 使用指南
- 【bug记录】getDeviceId: The user 10002 does not meet the requirements to access device identifiers.
- synology smb_用于在Synology NAS上测试Spring Boot Web应用程序的JUnit模拟文件
- axios post请求
- [译] 学习 Spring Security(四):使用邮箱激活新账户
- python3扬州大学校园网认证登录与下线
- netty实现gmssl_gmssl java api 编译
- 关于ccs软件的简单使用
- 测试高中低音的软件6,分别用什么音乐来测试设备的高中低音。
- [模板] 洛谷 P1137 旅行计划 (拓扑排序)
- 疯狂原始人手游怎么用电脑玩 疯狂原始人手游PC电脑版教程
- 胡适致迷茫大学生:成不在一时,功必不唐捐
- 基于阻抗控制的工业机器人轨迹跟踪系统 Simulink/Simscape 仿真
- Jsp+Servlet+Mysql简单的登录
- 【Midjourney教程】设计麻瓜也能10分钟上架一套表情包
- 惠普计算机使用方法,惠普笔记本电脑功能键(HP/联想等笔记本键盘fn键使用说明大全)...
- 小米android手机密码忘了怎么解锁,小米手机锁屏密码忘了怎么办
- ems苹果专线投递速度_“高功率脉冲磁控溅射”新工艺:苹果 iPhone 12 Pro 金色版图赏 - 苹果,iPhone...
- dbms chapter3