软著项目推荐 深度学习的水果识别 opencv python

文章目录

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

0 前言

🔥 优质竞赛项目系列,今天要分享的是

🚩 深度学习的水果识别 opencv python

该项目较为新颖,适合作为竞赛课题方向,学长非常推荐!

🥇学长这里给一个题目综合评分(每项满分5分)

  • 难度系数:3分
  • 工作量:3分
  • 创新点:4分

🧿 更多资料, 项目分享:

https://gitee.com/dancheng-senior/postgraduate

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 最后

🧿 更多资料, 项目分享:

https://gitee.com/dancheng-senior/postgraduate

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/201107.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

TA-Lib学习研究笔记(九)——Pattern Recognition (5)

TA-Lib学习研究笔记(九)——Pattern Recognition (5) 最全面的形态识别的函数的应用,通过使用A股实际的数据,验证形态识别函数,用K线显示出现标志的形态走势,由于入口参数基本上是o…

geemap学习笔记020:如何搜索Earth Engine Python脚本

前言 本节内容比较简单,但是对于自主学习比较重要,JavaScript提供了很多的示例代码,为了便于学习,geemap将其转为了Python代码。 Earth Engine Python脚本 import ee import geemapee.Initialize()geemap.ee_search() #搜索Ear…

函数递归。

文章目录 前言一、什么是递归二、递归的限制条件三、递归举例1.求n的阶乘2. 举例2:顺序打印一个整数的每一位 四、递归的优劣总结 前言 不多废话了,直接开始。 一、什么是递归 递归是学习C语言函数绕不开的⼀个话题,那什么是递归呢&#xf…

Leetcode—383.赎金信【简单】

2023每日刷题(五十) Leetcode—383.赎金信 实现代码 class Solution { public:int arr[26] {0};int arr2[26] {0};bool canConstruct(string ransomNote, string magazine) {int len ransomNote.size();int len2 magazine.size();for(int i 0; i …

uniapp 微信小程序连接蓝牙卡死 uni.onNeedPrivacyAuthorization

解决方法,需要同意隐私保护协议,否则不能开启蓝牙权限和定位权限,会导致连接蓝牙失败

k8s之镜像拉取时使用secret

k8s之secret使用 一、说明二、secret使用2.1 secret类型2.2 创建secret2.3 配置secret 一、说明 从公司搭建的网站镜像仓库,使用k8s部署服务时拉取镜像失败,显示未授权: 需要在拉取镜像时添加认证信息. 关于secret信息,参考: https://www.…

【100天精通Python】Day75:Python机器学习-第一个机器学习小项目_鸾尾花分类项目(上)

目录 1 机器学习中的Helloworld _鸾尾花分类项目 2 导入项目所需类库和鸾尾花数据集 2.1 导入类库 2.2 scikit-learn 库介绍 (1)主要特点: (2)常见的子模块: 3 导入鸾尾花数据集 3.1 概述数据 3.…

NB-IoT BC260Y Open CPU SDK⑨timer定时器的应用

NB-IoT BC260Y Open CPU SDK⑨timer定时器的应用 1、BC260Y_CN_AA模块 定时器的介绍2、 定时器的用法3、定时器相关API的介绍定时器 API 函数介绍时间 API函数介绍3、软件设计4、实例分析5、以下是调试的结果:1、BC260Y_CN_AA模块 定时器的介绍 BC260Y-CN QuecOpen 模块支持两…

基于Java SSM框架实现网络视频播放器管理系统项目【项目源码+论文说明】计算机毕业设计

基于java的SSM框架实现网络视频播放器管理系统演示 摘要 21世纪的今天,随着社会的不断发展与进步,人们对于信息科学化的认识,已由低层次向高层次发展,由原来的感性认识向理性认识提高,管理工作的重要性已逐渐被人们所…

MacOS 14挂载NTFS 硬盘的最佳方式(免费)

categories: [Tips] tags: MacOS 写在前面 众所周知, MacOS 上面插入 NTFS磁盘格式的话, 磁盘可以向 Mac 写入数据, 但是 Mac 上的数据不能写入磁盘(这是因为 MacOS 的内核扩展禁用了 NTFS 这个格式, 可能是出于安全性或其他原因) 之前一直是使用某 pojie 的 NTFS 工具的, 虽然…

Windows循环检测,直到网络通/断后执行指定命令

前言 前几天,一个朋友让我帮他做个脚本或者批处理,要实现的功能很简单:开机时检测网络是否联通,如果联通了就执行一个指定的程序,然后脚本就可以退出了。 批处理的解决方法 手动操作时,我们通常使用ping…

回溯算法:复原IP地址 子集 子集II

93.复原IP地址 思路: 与分割回文串相似,复原ip地址是将给定字符串分割成点分十进制的四段,切割问题就可以使用回溯搜索法把所有可能性搜出来。回溯三部曲: 递归参数:除了传入的需要分割的字符串,仍然需要…

C# WPF上位机开发(图形显示软件)

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing 163.com】 在实际应用中,有一种情况就是,我们需要经常对数据进行图形化显示,这样会比较直观一点。比如经济统计里面的同比…

波奇学C++:类型转换和IO流

隐式类型转换 int i0; double pi; 强制类型转换 int* pnullptr; int a(int)p; 单参数构造函数支持隐式类型转换 class A { public:A(string a):_a(a){} private:string _a; }; A a("xxxx"); //"xxx" const char* 隐式转换为string 多参数也可以通过{…

【对象数组根据属性排序】

// sort使用的排序方法 // 传入对象数组用于排序的对象的属性,升序/降序 function compare(property, sortType "asc") {debugger// 如果不是 asc,desc,不做下一步比较if (!(sortType "desc" || sortType "asc")) {return;}return function (…

阿里云账号注册完成实名认证免费领取云服务器4台

注册阿里云,免费领云服务器,每月280元额度,3个月试用时长,可快速搭建网站/小程序,部署开发环境,开发多种企业应用,共3步骤即可免费领取阿里云服务器,阿里云服务器网aliyunfuwuqi.com…

mysql pxc高可用离线部署(三)

pxc学习流程 mysql pxc高可用 单主机 多主机部署(一) mysql pxc 高可用多主机离线部署(二) mysql pxc高可用离线部署(三) mysql pxc高可用 跨主机部署pxc 本文使用docker进行安装,主机间通过…

4-Tornado高并发原理

核心原理就是协程epoll事件循环,再使用协程之后,开销是特别的小,那具体如何提供高并发的呢? 异步非阻塞IO 这意味我们整套开发的模式不在与原来一样,正因为不再一样,所以有时我们在理解代码时就有可能会比…

网络安全威胁——中间人攻击

中间人攻击 1. 定义2. 中间人攻击如何工作3. 常见中间人攻击类型4. 如何防止中间人攻击 1. 定义 中间人攻击(Man-in-the-Middle Attack,简称MITM),是一种会话劫持攻击。攻击者作为中间人,劫持通信双方会话并操纵通信过…

6、Broker消息处理流程(六)

前面分析完Broker启动会启动RemotingServer服务同时会注册Processor处理器,接着分析Producer进行消息的发送,当Producer发送完消息后就得到Broker去接收Producer发送的消息了。 Producer发送给Broker消息时候,发送的请求code为SEND_MESSAGE(这…