文章目录

  • 1 前言
  • 2 开发简介
  • 3 识别原理
    • 3.1 传统图像识别原理
    • 3.2 深度学习水果识别
  • 4 数据集
  • 5 部分关键代码
    • 5.1 处理训练集的数据结构
    • 5.2 模型网络结构
    • 5.3 训练模型
  • 6 识别效果
  • 7 最后

1 前言

Hi,大家好,这里是丹成学长,今天做一个 基于深度学习的水果识别demo

2 开发简介

深度学习作为机器学习领域内新兴并且蓬勃发展的一门学科, 它不仅改变着传统的机器学习方法, 也影响着我们对人类感知的理解, 已经在图像识别和语音识别等领域取得广泛的应用。 因此, 本文在深入研究深度学习理论的基础上, 将深度学习应用到水果图像识别中, 以此来提高了水果图像的识别性能。

3 识别原理

3.1 传统图像识别原理

传统的水果图像识别系统的一般过程如下图所示,主要工作集中在图像预处理和特征提取阶段。

在大多数的识别任务中, 实验所用图像往往是在严格限定的环境中采集的, 消除了外界环境对图像的影响。 但是实际环境中图像易受到光照变化、 水果反光、 遮挡等因素的影响, 这在不同程度上影响着水果图像的识别准确率。

在传统的水果图像识别系统中, 通常是对水果的纹理、 颜色、 形状等特征进行提取和识别。

3.2 深度学习水果识别

CNN 是一种专门为识别二维特征而设计的多层神经网络, 它的结构如下图所示,这种结构对平移、 缩放、 旋转等变形具有高度的不变性。

学长本次采用的 CNN 架构如图:

4 数据集

  • 数据库分为训练集(train)和测试集(test)两部分

  • 训练集包含四类apple,orange,banana,mixed(多种水果混合)四类237张图片;测试集包含每类图片各两张。图片集如下图所示。

  • 图片类别可由图片名称中提取。

训练集图片预览

测试集预览

数据集目录结构

5 部分关键代码

5.1 处理训练集的数据结构

import os
import pandas as pdtrain_dir = './Training/'
test_dir = './Test/'
fruits = []
fruits_image = []for i in os.listdir(train_dir):for image_filename in os.listdir(train_dir + i):fruits.append(i) # name of the fruitfruits_image.append(i + '/' + image_filename)
train_fruits = pd.DataFrame(fruits, columns=["Fruits"])
train_fruits["Fruits Image"] = fruits_imageprint(train_fruits)

5.2 模型网络结构

import matplotlib.pyplot as plt
import seaborn as sns
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
from glob import glob
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Activation, Dropout, Flatten, Dense
img = load_img(train_dir + "Cantaloupe 1/r_234_100.jpg")
plt.imshow(img)
plt.axis("off")
plt.show()array_image = img_to_array(img)# shape (100,100)
print("Image Shape --> ", array_image.shape)# 131个类目
fruitCountUnique = glob(train_dir + '/*' )
numberOfClass = len(fruitCountUnique)
print("How many different fruits are there --> ",numberOfClass)# 构建模型
model = Sequential()
model.add(Conv2D(32,(3,3),input_shape = array_image.shape))
model.add(Activation("relu"))
model.add(MaxPooling2D())
model.add(Conv2D(32,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D())
model.add(Conv2D(64,(3,3)))
model.add(Activation("relu"))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation("relu"))
model.add(Dropout(0.5))# 区分131类
model.add(Dense(numberOfClass)) # output
model.add(Activation("softmax"))
model.compile(loss = "categorical_crossentropy",optimizer = "rmsprop",metrics = ["accuracy"])print("Target Size --> ", array_image.shape[:2])

5.3 训练模型

train_datagen = ImageDataGenerator(rescale= 1./255,shear_range = 0.3,horizontal_flip=True,zoom_range = 0.3)test_datagen = ImageDataGenerator(rescale= 1./255)
epochs = 100
batch_size = 32
train_generator = train_datagen.flow_from_directory(train_dir,target_size= array_image.shape[:2],batch_size = batch_size,color_mode= "rgb",class_mode= "categorical")test_generator = test_datagen.flow_from_directory(test_dir,target_size= array_image.shape[:2],batch_size = batch_size,color_mode= "rgb",class_mode= "categorical")for data_batch, labels_batch in train_generator:print("data_batch shape --> ",data_batch.shape)print("labels_batch shape --> ",labels_batch.shape)breakhist = model.fit_generator(generator = train_generator,steps_per_epoch = 1600 // batch_size,epochs=epochs,validation_data = test_generator,validation_steps = 800 // batch_size)#保存模型 model_fruits.h5
model.save('model_fruits.h5')

顺便输出训练曲线

#展示损失模型结果
plt.figure()
plt.plot(hist.history["loss"],label = "Train Loss", color = "black")
plt.plot(hist.history["val_loss"],label = "Validation Loss", color = "darkred", linestyle="dashed",markeredgecolor = "purple", markeredgewidth = 2)
plt.title("Model Loss", color = "darkred", size = 13)
plt.legend()
plt.show()#展示精确模型结果
plt.figure()
plt.plot(hist.history["accuracy"],label = "Train Accuracy", color = "black")
plt.plot(hist.history["val_accuracy"],label = "Validation Accuracy", color = "darkred", linestyle="dashed",markeredgecolor = "purple", markeredgewidth = 2)
plt.title("Model Accuracy", color = "darkred", size = 13)
plt.legend()
plt.show()

6 识别效果

from tensorflow.keras.models import load_model
import os
import pandas as pdfrom keras.preprocessing.image import ImageDataGenerator,img_to_array, load_img
import cv2,matplotlib.pyplot as plt,numpy as np
from keras.preprocessing import imagetrain_datagen = ImageDataGenerator(rescale= 1./255,shear_range = 0.3,horizontal_flip=True,zoom_range = 0.3)model = load_model('model_fruits.h5')
batch_size = 32
img = load_img("./Test/Apricot/3_100.jpg",target_size=(100,100))
plt.imshow(img)
plt.show()array_image = img_to_array(img)
array_image = array_image * 1./255
x = np.expand_dims(array_image, axis=0)
images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print(classes)
train_dir = './Training/'train_generator = train_datagen.flow_from_directory(train_dir,target_size= array_image.shape[:2],batch_size = batch_size,color_mode= "rgb",class_mode= "categorical”)
print(train_generator.class_indices)

fig = plt.figure(figsize=(16, 16))
axes = []
files = []
predictions = []
true_labels = []
rows = 5
cols = 2# 随机选择几个图片
def getRandomImage(path, img_width, img_height):"""function loads a random image from a random folder in our test path"""folders = list(filter(lambda x: os.path.isdir(os.path.join(path, x)), os.listdir(path)))random_directory = np.random.randint(0, len(folders))path_class = folders[random_directory]file_path = os.path.join(path, path_class)file_names = [f for f in os.listdir(file_path) if os.path.isfile(os.path.join(file_path, f))]random_file_index = np.random.randint(0, len(file_names))image_name = file_names[random_file_index]final_path = os.path.join(file_path, image_name)return image.load_img(final_path, target_size = (img_width, img_height)), final_path, path_classdef draw_test(name, pred, im, true_label):BLACK = [0, 0, 0]expanded_image = cv2.copyMakeBorder(im, 160, 0, 0, 300, cv2.BORDER_CONSTANT, value=BLACK)cv2.putText(expanded_image, "predicted: " + pred, (20, 60), cv2.FONT_HERSHEY_SIMPLEX,0.85, (255, 0, 0), 2)cv2.putText(expanded_image, "true: " + true_label, (20, 120), cv2.FONT_HERSHEY_SIMPLEX,0.85, (0, 255, 0), 2)return expanded_image
IMG_ROWS, IMG_COLS = 100, 100# predicting images
for i in range(0, 10):path = "./Test"img, final_path, true_label = getRandomImage(path, IMG_ROWS, IMG_COLS)files.append(final_path)true_labels.append(true_label)x = image.img_to_array(img)x = x * 1./255x = np.expand_dims(x, axis=0)images = np.vstack([x])classes = model.predict_classes(images, batch_size=10)predictions.append(classes)class_labels = train_generator.class_indices
class_labels = {v: k for k, v in class_labels.items()}
class_list = list(class_labels.values())for i in range(0, len(files)):image = cv2.imread(files[i])image = draw_test("Prediction", class_labels[predictions[i][0]], image, true_labels[i])axes.append(fig.add_subplot(rows, cols, i+1))plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))plt.grid(False)plt.axis('off')
plt.show()

7 最后

毕业设计 : 题目:基于深度学习的水果识别 设计 开题 技术相关推荐

  1. 毕业设计之 --- 基于深度学习的行人重识别(person reid)

    文章目录 0 前言 1 技术背景 2 技术介绍 3 重识别技术实现 3.1 数据集 3.2 行人检测 3.2 Person REID 3.2.1 算法原理 3.2.2 算法流程图 4 实现效果 5 部 ...

  2. 基于深度学习的水果检测与识别系统(Python界面版,YOLOv5实现)

    摘要:本博文介绍了一种基于深度学习的水果检测与识别系统,使用YOLOv5算法对常见水果进行检测和识别,实现对图片.视频和实时视频中的水果进行准确识别.博文详细阐述了算法原理,同时提供Python实现代 ...

  3. 毕业设计 基于深度学习的动物识别 - 卷积神经网络 机器视觉 图像识别

    文章目录 0 前言 1 背景 2 算法原理 2.1 动物识别方法概况 2.2 常用的网络模型 2.2.1 B-CNN 2.2.2 SSD 3 SSD动物目标检测流程 4 实现效果 5 部分相关代码 5 ...

  4. [实训题目EmoProfo]基于深度学习的表情识别服务搭建(一)

    基于深度学习的表情识别服务搭建(一) 文章目录 基于深度学习的表情识别服务搭建(一) 背景 识别服务设计 实现方式的选择 dlib性能验证 功能实现 小结 背景 之前我完成了终端和服务端之间交流的全部 ...

  5. 毕业设计-基于深度学习的人脸识别方法

    目录 前言 课题背景和意义 实现技术思路 一.人脸识别介绍 二.基于深度学习的人脸识别方法 实现效果图样例 最后 前言

  6. 花卉识别python_基于深度学习的花卉识别系统设计与实现

    杨美艳 任富顺 顾志东 摘   要:深度学习是机器学习的一种前沿发展,设计主要利用谷歌的tensorflow框架,实现了对十种花卉的分类和识别.通过已有的大量的花卉图片素材,编写卷积神经网络对花卉图片 ...

  7. 基于MATLAB花卉识别系统,基于深度学习的花卉识别系统设计与实现

    杨美艳 任富顺 顾志东 摘   要:深度学习是机器学习的一种前沿发展,设计主要利用谷歌的tensorflow框架,实现了对十种花卉的分类和识别.通过已有的大量的花卉图片素材,编写卷积神经网络对花卉图片 ...

  8. 基于深度学习的口罩识别与检测PyTorch实现

    基于深度学习的口罩识别与检测PyTorch实现 1. 设计思路 1.1 两阶段检测器:先检测人脸,然后将人脸进行分类,戴口罩与不戴口罩. 1.2 一阶段检测器:直接训练口罩检测器,训练样本为人脸的标注 ...

  9. 基于深度学习的脑电图识别 综述篇(三)模型分析

    作者|Memory逆光 本文由作者授权分享 导读 脑电图(EEG)是一个复杂的信号,一个医生可能需要几年的训练并利用先进的信号处理和特征提取方法,才能正确解释其含义.而如今机器学习和深度学习的发展,大 ...

  10. 基于深度学习的脑电图识别 综述篇(二)数据采样及处理

    作者|Memory逆光 本文由作者授权分享 导读 脑电图(EEG)是一个复杂的信号,一个医生可能需要几年的训练并利用先进的信号处理和特征提取方法,才能正确解释其含义.而如今机器学习和深度学习的发展,大 ...

最新文章

  1. python输入文字如何定义文字_python如何实现手动输入文字
  2. ARM入门笔记(9)
  3. c语言程序设计和数据结构,C语言程序设计与数据结构实践 闵光太主编.pdf
  4. 经典面试题(17):以下代码将输出的结果是什么?
  5. Qt仿win7自动顶部最大化左侧右侧半屏效果
  6. linux中c语言延时毫秒函数,linux下写个C语言程序,要求有0.5微秒以下的延时,要怎样写...
  7. Java 泛型 extends T 和 super T 详解
  8. 系统详细设计过程指南
  9. Pycharm制作搞怪弹窗(声音强制最大,屏幕亮度强制最亮,按钮躲避,弹窗炸弹)
  10. 尝试运行项目时出错,无法启动程序 , 由于应用程序配置不正确,未能启动此应用程序。请查看清单文件以查找可能的错误。
  11. 音视频入门系列-视频封装格式篇(TS)
  12. 阿里云企业做网站备案流程
  13. 考研英语(四)——名词性从句
  14. 《老路用得上的商学课》21-30学习笔记
  15. 编写一个模拟超市购物程序。
  16. Nagios之配置介绍
  17. 配置python命令tab键自动补全
  18. DevOps成就卓越
  19. 无源测向与时差定位技术研究matlab,无源定位系统中的时差测量研究
  20. TRR 立志做最简单、易上手、易扩展、易维护的TP反射注释路由架构

热门文章

  1. 无处不在的人生压力让人变得孤独抑郁
  2. 美国弗吉尼亚大学计算机科学,弗吉尼亚大学计算机科学专业怎么样?
  3. 别看 DNS 污染闹得欢,现在我用 CoreDNS 将它拉清单
  4. Add-Migration
  5. 最新AZ自动发卡网源码-全网首发
  6. MySQL判断是否在同一天
  7. 计算机思维是运用计算机科学的什么,计算思维是运用计算机科学的基础概念进行问题求解、系统设计以及人类行为理解等涵盖计算机科学之广度的一系列计算机的思维活动。...
  8. TCP通讯中发送文件
  9. YOLOv3训练自己的数据详细步骤
  10. 安防大数据在智慧城市建设中的地位与深度应用