ubuntu深度学习使用TensorFlow卷积神经网络——图片数据集的制作以及制作好的数据集的使用

这篇具有很好参考价值的文章主要介绍了ubuntu深度学习使用TensorFlow卷积神经网络——图片数据集的制作以及制作好的数据集的使用。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

首先我事先准备好五分类的图片放在对应的文件夹,图片资源在我的gitee文件夹中链接如下:文件管理: 用于存各种数据https://gitee.com/xiaoxiaotai/file-management.git

 里面有imgs目录和npy目录,imgs就是存放5分类的图片的目录,里面有桂花、枫叶、五味子、银杏、竹叶5种植物,npy目录存放的是我用这些图片制作好的npy文件数据集,里面有32x32大小和64x64大小的npy文件。

接下来是数据集制作过程:

首先导入所需的库

import os
import cv2
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from mpl_toolkits.axes_grid1 import ImageGrid
%matplotlib inline
import math
from tqdm import tqdm

下面是先显示本地分类中部分图片

#先显示枫叶图片
folder_path = './datas/imgs/fengye'
# 可视化图像的个数
N = 36
# n 行 n 列
n = math.floor(np.sqrt(N))

images = []
for each_img in os.listdir(folder_path)[:N]:
    img_path = os.path.join(folder_path, each_img)
    #img_bgr = cv2.imread(img_path)
    img_bgr = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), 1) #解决路径中存在中文的问题
    img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
    images.append(img_rgb)

fig = plt.figure(figsize=(6, 8),dpi=80)
grid = ImageGrid(fig, 111,  # 类似绘制子图 subplot(111)
                 nrows_ncols=(n, n),  # 创建 n 行 m 列的 axes 网格
                 axes_pad=0.02,  # 网格间距
                 share_all=True
                 )

# 遍历每张图像
for ax, im in zip(grid, images):
    ax.imshow(im)
    ax.axis('off')

plt.tight_layout()
plt.show()

 输出结果如下:

ubuntu深度学习使用TensorFlow卷积神经网络——图片数据集的制作以及制作好的数据集的使用

 下面是输出各个图片的信息包括图片宽高、图片名、所属类别,os.chdir('../')意思是将当前路径指针指向上一个目录,可以用os.getcwd()输出当前所指路径

# 指定数据集路径
dataset_path = './datas/imgs/'
os.chdir(dataset_path)
print(os.listdir())

df = pd.DataFrame()
for fruit in tqdm(os.listdir()): # 遍历每个类别    
    os.chdir(fruit)
    for file in os.listdir(): # 遍历每张图像
        try:
            img = cv2.imread(file)
            df = df.append({'类别':fruit, '文件名':file, '图像宽':img.shape[1], '图像高':img.shape[0]}, ignore_index=True)
        except:
            print(os.path.join(fruit, file), '读取错误')
    os.chdir('../')
os.chdir('../../')
df

输出结果如下:

ubuntu深度学习使用TensorFlow卷积神经网络——图片数据集的制作以及制作好的数据集的使用

定义标签数字,因为数据集标签一般是数字,训练才更快

# 定义5个类别的标签
labels = {
    'wuweizi': 0,
    'fengye': 1,
    'guihua': 2,
    'zhuye': 3,
    'yinxing': 4
}

# 定义训练集和测试集的比例
train_ratio = 0.8

# 定义一个空列表用于存储训练集和测试集
train_data = []
test_data = []

 数据增强,我这里是将每一张图片缩小为64x64,你也可以改成32x32或者其他大小,要注意的是,大小越大数据集制作越久,得到的数据集大小越大。

# 定义数据增强的方法
def data_augmentation(img):
    # 随机裁剪
    img = cv2.resize(img, (256, 256))
    x = random.randint(0, 256 - 64)
    y = random.randint(0, 256 - 64)
    img = img[x:x+64, y:y+64]
    

    # 随机翻转
    if random.random() < 0.5:
        img = cv2.flip(img, 1)
    
    # 随机旋转
    angle = random.randint(-10, 10)
    M = cv2.getRotationMatrix2D((32, 32), angle, 1)
    img = cv2.warpAffine(img, M, (64, 64))
    
    return img
# 定义读取图片的方法
def read_image(path):
    img = cv2.imread(path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = data_augmentation(img)
    img = img / 255.0
    return img

下面是给图片打上标签了,也就是每一张图片都给它标注属于哪一种类别(身份),这样卷积神经网络就可以在训练的时候知道类别,从而记住所属特征的标签值

# 遍历5个文件夹,读取图片并打上标签
for path, label in labels.items():
    files = os.listdir('./datas/imgs/'+path)
    random.shuffle(files)
    train_files = files[:int(len(files) * train_ratio)]
    test_files = files[int(len(files) * train_ratio):]
    for file in train_files:
        img = read_image(os.path.join('./datas/imgs/'+path, file))
        train_data.append((img, label))
    for file in test_files:
        img = read_image(os.path.join('./datas/imgs/'+path, file))
        test_data.append((img, label))
    # 工整地输出每一类别的数据个数
    print('类别:{} 训练集个数:{} 测试集数据:{}'.format(path, len(train_files), len(test_files)))

这里的输出结果:

ubuntu深度学习使用TensorFlow卷积神经网络——图片数据集的制作以及制作好的数据集的使用

现在可以看一下裁剪后的结果

df = pd.DataFrame()
for img,label in train_data: # 遍历每个类别    

#     img = cv2.imread(fruit)
    df = df.append({'类别':label, '文件名':file, '图像宽':img.shape[1], '图像高':img.shape[0]}, ignore_index=True)
df

 结果如下,我们可以看到大小已经变成64x64了,当然这是没有打乱顺序的,类别是从0开始到4:

ubuntu深度学习使用TensorFlow卷积神经网络——图片数据集的制作以及制作好的数据集的使用

接下来就是打乱顺序,这也是为了防止过拟合化

# 打乱训练集和测试集的顺序
random.shuffle(train_data)
random.shuffle(test_data)

 再次输出

df = pd.DataFrame()
for img,label in train_data: # 遍历每个类别    

#     img = cv2.imread(fruit)
    df = df.append({'类别':label, '文件名':file, '图像宽':img.shape[1], '图像高':img.shape[0]}, ignore_index=True)
df

 这一次的结果如下,类别顺序已经被打乱:

ubuntu深度学习使用TensorFlow卷积神经网络——图片数据集的制作以及制作好的数据集的使用

下面是保存训练集和测试集的数据集和标签

# 将训练集和测试集的图片和标签分别存储在numpy数组中
train_imgs = np.array([data[0] for data in train_data])
train_labels = np.array([data[1] for data in train_data])
test_imgs = np.array([data[0] for data in test_data])
test_labels = np.array([data[1] for data in test_data])

# 保存训练集和测试集
np.save('./datas/npy/32px/train_imgs_64.npy', train_imgs)
np.save('./datas/npy/32px/train_labels_64.npy', train_labels)
np.save('./datas/npy/32px/test_imgs_64.npy', test_imgs)
np.save('./datas/npy/32px/test_labels_64.npy', test_labels)

上面的数据集已经做好了,那么接下来就到模型的训练了,模型的训练我就不一一解释了,大家自己看代码,我使用的是anaconda中的jupyter工具写代码

#导库
import tensorflow as tf
import numpy as np
import os
import matplotlib.pyplot as plt
import urllib
import cv2

# 加载上面制作的数据集
train_imgs = np.load('./datas/npy/64px/train_imgs_64.npy')
train_labels = np.load('./datas/npy/64px/train_labels_64.npy')
test_imgs = np.load('./datas/npy/64px/test_imgs_64.npy')
test_labels = np.load('./datas/npy/64px/test_labels_64.npy')

#可以看看输出纬度
train_imgs.shape

#模型构建,这里我就构建一个简单模型
def creatAlexNet():
    model = tf.keras.models.Sequential([
        tf.keras.layers.Conv2D(64, kernel_size=(3, 3), strides=(1, 1), activation='relu', input_shape=(64, 64, 3)),
        tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1)),
        tf.keras.layers.Conv2D(128, kernel_size=(3, 3), strides=(1, 1), activation='relu'),
        tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1)),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(5, activation='softmax')
    ])
    return model

#加载模型
model = creatAlexNet()

#显示摘要
model.summary()


# 定义超参数
learning_rate = 0.001 #study 
batch_size = 100 #单次训练样本数(批次大小)
epochs = 20 #训练轮数

# 定义训练模式
model.compile(optimizer ='adam',#优化器
loss='sparse_categorical_crossentropy',#损失函数
              metrics=['accuracy'])#评估模型的方式

# 加载数据集并训练模型
history = model.fit(train_imgs, train_labels, batch_size=batch_size, epochs=epochs, 
                    validation_split = 0.2)

# 评估模型
test_loss, test_acc = model.evaluate(test_imgs, test_labels, verbose=2)
print('Test accuracy:', test_acc)

#模型测试
preds = model.predict(test_imgs)
np.argmax(preds[20])

# 可视化测试
# 定义显示图像数据及其对应标签的函数
# 图像列表
label_dict={0:"wuweizi",1:"fengye",2:"guihua",3:"zhuye",4:"yinxing"}
def plot_images_labels_prediction(images,# 标签列表
                                  labels,
                                  preds,#预测值列表
                                  index,#从第index个开始显示
                                  num = 5):  # 缺省一次显示5幅
    fig=plt.gcf()#获取当前图表,Get Current Figure 
    fig.set_size_inches(12,6)#1英寸等于2.54cm 
    if num > 10:#最多显示10个子图
        num = 10
    for i in range(0, num):
        ax = plt.subplot(2,5,i+1)#获取当前要处理的子图
        plt.tight_layout()
        ax.imshow(images[index])
        title=str(i)+','+label_dict[labels[index]]#构建该图上要显示的title信息
        if len(preds)>0:
            title +='=>' + label_dict[np.argmax(preds[index])]
        ax.set_title(title,fontsize=10)#显示图上的title信息
        index += 1 
    plt.show()

plot_images_labels_prediction(test_imgs,test_labels, preds,10,30)

# 然后保存模型
model_filename ='models/plant_model.h5'
model.save(model_filename)

# 这里是从本地加载图片对模型进行测试
from PIL import Image
import numpy as np

loaded_model = tf.keras.models.load_model('models/plant_model.h5')
label_dict={0:"wuweizi",1:"fengye",2:"guihua",3:"zhuye",4:"yinxing"}

img = Image.open('./fengye.jpeg')
img = img.resize((64, 64))
img_arr = np.array(img) / 255.0
img_arr = img_arr.reshape(1, 64, 64, 3)
pred = model.predict(img_arr)
class_idx = np.argmax(pred)
plt.title("type:{}, pre_label:{}".format(label_dict[class_idx],class_idx))
plt.imshow(img, cmap=plt.get_cmap('gray'))

# 加载模型
loaded_model = tf.keras.models.load_model('models/plant_model.h5')
# 使用模型预测浏览器上的一张图片
label_dict={0:"wuweizi",1:"fengye",2:"guihua",3:"zhuye",4:"yinxing"}

# 这里是从浏览器的网址中加载图片进行识别
url = 'https://newbbs-fd.zol-img.com.cn/t_s1200x5000/g5/M00/05/08/ChMkJ1wFsOGIcMt4AAGFQDPiUhEAAtkTQCj_EoAAYVY306.jpg'
with urllib.request.urlopen(url) as url_response:
    img_array = np.asarray(bytearray(url_response.read()), dtype=np.uint8)
    img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
    img_array = cv2.resize(img, (64, 64))
    img_array = img_array / 255.0
    img_array = np.expand_dims(img_array, axis=0)
    
    predict_label = np.argmax(loaded_model.predict(img_array), axis=-1)[0]
    plt.imshow(img, cmap=plt.get_cmap('gray'))
    plt.title("Predict: {},Predict_label: {}".format(label_dict[predict_label],predict_label))
    plt.xticks([])
    plt.yticks([])

本次文章就到这里,感谢大家的支持!文章来源地址https://www.toymoban.com/news/detail-446377.html

到了这里,关于ubuntu深度学习使用TensorFlow卷积神经网络——图片数据集的制作以及制作好的数据集的使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 鱼类识别Python+深度学习人工智能+TensorFlow+卷积神经网络算法

    鱼类识别系统。使用Python作为主要编程语言开发,通过收集常见的30种鱼类(‘墨鱼’, ‘多宝鱼’, ‘带鱼’, ‘石斑鱼’, ‘秋刀鱼’, ‘章鱼’, ‘红鱼’, ‘罗非鱼’, ‘胖头鱼’, ‘草鱼’, ‘银鱼’, ‘青鱼’, ‘马头鱼’, ‘鱿鱼’, ‘鲇鱼’, ‘鲈鱼’, ‘鲍鱼’, ‘鲑

    2024年02月02日
    浏览(60)
  • 40 深度学习(四):卷积神经网络|深度可分离卷积|colab和kaggle的基础使用

    卷积神经网络的基本结构 1: (卷积层+(可选)池化层) * N+全连接层 * M(N=1,M=0) 卷积层的输入和输出都是矩阵,全连接层的输入和输出都是向量,在最后一层的卷积上,把它做一个展平,这样就可以和全连接层进行运算了,为什么卷积要放到前面,因为展平丧失了维度信息,因

    2024年02月08日
    浏览(29)
  • 深度学习:使用卷积神经网络CNN实现MNIST手写数字识别

    本项目基于pytorch构建了一个深度学习神经网络,网络包含卷积层、池化层、全连接层,通过此网络实现对MINST数据集手写数字的识别,通过本项目代码,从原理上理解手写数字识别的全过程,包括反向传播,梯度下降等。 卷积神经网络是一种多层、前馈型神经网络。从功能上

    2024年02月13日
    浏览(32)
  • 深度学习——使用卷积神经网络改进识别鸟与飞机模型

    验证下,是否获取成功 使用 DataLoader 封装数据集 我们打算放弃 nn.Sequential 带来的灵活性。使用更自由的子类化 nn.Module 。 为了子类化 nn.Module ,我们至少需要定义一个 forward() 函数,该函数用于接收模块的输入并返回输出,这便是模块计算的之处。 在 Pytorch 中,如果使用标准

    2023年04月08日
    浏览(32)
  • 从零使用TensorFlow搭建CNN(卷积)神经网络

    🍅 写在前面 👨‍🎓 博主介绍:大家好,这里是hyk写算法了吗,一枚致力于学习算法和人工智能领域的小菜鸟。 🔎个人主页:主页链接(欢迎各位大佬光临指导) ⭐️近期专栏:机器学习与深度学习                        LeetCode算法实例 本节内容主要向大家

    2023年04月22日
    浏览(35)
  • 深度神经网络基础——深度学习神经网络基础 & Tensorflow在深度学习的应用

    Tensorflow入门(1)——深度学习框架Tesnsflow入门 环境配置 认识Tensorflow 深度学习框架Tesnsflow 线程+队列+IO操作 文件读取案例 神经网络的种类: 基础神经网络:单层感知器,线性神经网络,BP神经网络,Hopfield神经网络等 进阶神经网络:玻尔兹曼机,受限玻尔兹曼机,递归神经

    2024年02月16日
    浏览(30)
  • AI:162-如何使用Python进行图像识别与处理深度学习与卷积神经网络的应用

    本文收录于专栏:精通AI实战千例专栏合集 从基础到实践,深入学习。无论你是初学者还是经验丰富的老手,对于本专栏案例和项目实践都有参考学习意义。 每一个案例都附带关键代码,详细讲解供大家学习,希望可以帮到大家。正在不断更新中~ 在当今数字化时代,图像处

    2024年04月26日
    浏览(40)
  • 深度学习|卷积神经网络

    卷积神经网络(Convolutional Neural Network,CNN)是一种深度学习神经网络结构,主要用于 图像识别 、 计算机视觉 等领域。该结构在处理图像等高维数据时表现出色,因为它具有共享权重和局部感知的特点,一方面减少了权值的数量使得网络易于优化,另一方面降低了模型的复

    2024年02月11日
    浏览(30)
  • 深度学习,卷积神经网络

      CV领域发展 CV领域是计算机视觉(Computer Vision)领域的简称。 计算机视觉是指利用计算机模拟人类视觉系统的科学,让计算机具有类似于人类在观察外界的视觉、图像的能力,包括图像处理、图像分析、图像理解等。 计算机视觉领域发展有以下特点: 视觉系统的出现和不

    2024年02月15日
    浏览(41)
  • 【深度学习】6-1 卷积神经网络 - 卷积层

    卷积神经网络(Convolutional Neural Network, CNN )。 CNN 被用于图像识别、语音识别等各种场合,在图像识别的比赛中,基于深度学习的方法几乎都以 CNN 为基础。 首先,来看一下 CNN 的网络结构,了解 CNN 的大致框架。CNN 和之前介绍的神经网络一样,可以像乐高积木一样通过组装层

    2024年02月10日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包