竞赛选题 深度学习的水果识别 opencv python

news2024/7/4 6:14:08

文章目录

  • 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 pd

train_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 fruit
        fruits_image.append(i + '/' + image_filename)
train_fruits = pd.DataFrame(fruits, columns=["Fruits"])
train_fruits["Fruits Image"] = fruits_image

print(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)
    break

hist = 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 pd

from keras.preprocessing.image import ImageDataGenerator,img_to_array, load_img
import cv2,matplotlib.pyplot as plt,numpy as np
from keras.preprocessing import image

train_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_class

def 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./255
    x = 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.coloradmin.cn/o/1209401.html

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

相关文章

EasyExcel入门使用教程

文章目录 简介一、工程创建🎑二、读操作🎊二、写操作🎄总结 简介 数据导入导出意义 后台管理系统是管理、处理企业业务数据的重要工具,在这样的系统中,数据的导入和导出功能是非常重要的,其主要意义包括以下…

了解STM32看门狗定时器的工作原理和原则

STM32 系列微控制器的看门狗定时器 (Watchdog Timer,WWDG) 是一种重要的硬件资源,用于检测系统的异常状态,并在发生异常时执行特定的操作,以确保系统能够正常运行。在本文中,我将详细介绍 STM32 看门狗定时器的工作原理…

Java Elasticsearch 按一定时间间隔(timeInterval)循环查询数据

最近有个需求&#xff0c;前端传入时间间隔&#xff0c;去elasticsearch按照时间间隔统计每个时间间隔内数据量。 public List<HashMap<String,Object>> getCount(RequestParam Integer time, RequestParam String selectedDatedTime) {SimpleDateFormat format n…

Oracle(2-3) Basic Oracle Net Server Side Configuration

文章目录 一、基础知识1、The Listener Process监听器进程2、Connection Methods 连接方法3、Spawn and Bequeath Conn4、Direct Hand-Off Connections 直接切换连接5、Redirection Session 重定向会话6、Simple to Complex:N-Tier 简单到复杂&#xff1a;N层7、Service Config…

双写绕过 [极客大挑战 2019]BabySQL 1

打开题目 随便输入账号密码 根据报错信息可知这是单引号的字符型注入 那我们试试万能密码 1 or 11 页面报错 1 or 11 页面报错 而且根据报错内容显示是没有我们注入上去的or的 那我们就试试 1 order by 3 # 页面报错&#xff0c;根据报错显示页面过滤掉了or和by 那我们…

Java 并发-Lock

目录 Lock 源码 lock() tryLock() tryLock(long time, TimeUnit unit) Lock与synchronized Lock Lock 是 java.util.concurrent.locks包 下的接口。 上图是 java.util.concurrent.locks包下主要常用的类与接口的关系。 源码 public interface Lock {void lock();void l…

Flowable串行流程移动活动

在Activiti6和Activiti7中跳转节点都要自己实现&#xff0c;Flowable增加了这个功能。 一&#xff1a;简介 串行流程是指简单的一条线的流程&#xff0c;流程中如果包含会签、排它网关也算串行流程。 节点移动有三种方式&#xff1a; 向前移动foreward。向后移动back。直接跳…

并发编程产生的根本原因和C#怎么处理并发问题?

并发编程产生的根本原因和C#怎么处理并发问题&#xff1f; 前言 对于现在很多编程语言来说&#xff0c;多线程已经得到了很好的支持&#xff0c; 以至于我们写多线程程序简单&#xff0c;但是一旦遇到并发产生的问题就会各种尝试。 因为不是明白为什么会产生并发问题&#…

Android 布局优化,看过来 ~

屏幕刷新机制 基本概念 刷新率&#xff1a;屏幕每秒刷新的次数&#xff0c;单位是 Hz&#xff0c;例如 60Hz&#xff0c;刷新率取决于硬件的固定参数。帧率&#xff1a;GPU 在一秒内绘制操作的帧数&#xff0c;单位是 fps。Android 采用的是 60fps&#xff0c;即每秒 GPU 最多…

11-13 /11-14代理模式 AOP

调用者 代理对象 目标对象 代理对象除了可以完成核心任务&#xff0c;还可以增强其他任务,无感的增强 代理模式目的: 不改变目标对象的目标方法的前提,去增强目标方法 分为:静态代理,动态代理 静态代理 有对象->前提需要有一个类&#xff0c;那么我们可以事先写好一个类&a…

ATFX汇市:美国10月CPI数据来袭,通胀率料将进一步走低

ATFX汇市&#xff1a;本周二21:30&#xff0c;美国劳工部将公布10月未季调CPI年率&#xff0c;前值为3.7%&#xff0c;预期值3.3%&#xff1b;9月未季调核心CPI年率将于同一时间公布&#xff0c;前值为4.1%&#xff0c;预期值4.1%。机构预期美国名义通胀率将显著下降&#xff0…

【JVM】Java内存溢出分析(堆溢出、栈溢出、方法区溢出、直接内存溢出)

&#x1f4eb;作者简介&#xff1a;小明java问道之路&#xff0c;2022年度博客之星全国TOP3&#xff0c;专注于后端、中间件、计算机底层、架构设计演进与稳定性建设优化&#xff0c;文章内容兼具广度、深度、大厂技术方案&#xff0c;对待技术喜欢推理加验证&#xff0c;就职于…

【极客时间-系列教程】Vim 实用技巧必知必会-更多常用命令:应对稍复杂的编辑任务

文章目录 更多常用命令&#xff1a;应对稍复杂的编辑任务光标移动文本修改文本对象选择 更多常用命令&#xff1a;应对稍复杂的编辑任务 几个基本的命令已经了解了&#xff0c;可以操作简单的任务&#xff0c;但一些很复杂的命令&#xff0c;并没有了解到&#xff0c;只知道几…

【C++】类和对象(4)--析构函数

一 概念 通过前面构造函数的学习&#xff0c;我们知道一个对象是怎么来的&#xff0c;那一个对象又是怎么没呢的&#xff1f; 析构函数&#xff1a;与构造函数功能相反&#xff0c;析构函数不是完成对对象本身的销毁&#xff0c;局部对象销毁工作是由编译器完成的。而对象在销…

发布自研大模型 夸克App将迎来全面升级

国产大模型阵营再添新锐选手。11月14日&#xff0c;阿里巴巴智能信息事业群发布全栈自研、千亿级参数的夸克大模型&#xff0c;将应用于通用搜索、医疗健康、教育学习、职场办公等众多场景。夸克App将借助自研大模型全面升级&#xff0c;加速迈向年轻人工作、学习、生活的AI助手…

Seatunnel单机和集群部署说明

编译 编译命令 mvn clean package -pl seatunnel-dist -am -Dmaven.test.skiptrue 部署 将seatunnel-dist\target目录下的apache-seatunnel-2.3.3-SNAPSHOT-bin.tar.gz上传至服务器 解压安装包到/opt/soft/seatunnel目录下 配置环境变量 export SEATUNNEL_HOME/opt/soft/s…

【MySQL】事务(下)

文章目录 1. 各个隔离级别的演示事务隔离级别 —— 读未提交事务隔离级别—— 读提交事务隔离级别 —— 可重复读事务隔离级别 —— 串行化脏读 不可重复读 幻读的理解 2. MVCC机制读写3个记录隐藏列字段undo日志模拟MVCCread view 理论 3. 读提交与 可重复读的区别两者本质区别…

分布式锁介绍

为什么需要分布式锁 在单机部署的系统中&#xff0c;使用线程锁来解决高并发的问题&#xff0c;多线程访问共享变量的问题达到数据一致性&#xff0c;如使用synchornized、ReentrantLock等。 但是在后端集群部署的系统中&#xff0c;程序在不同的JVM虚拟机中运行&#xff0c;且…

ISP 处理流程

#灵感# 摆烂时间太长了&#xff0c;感觉知识忘光光了。重新学习&#xff0c;常学常新。 因为公司文档都不让摘抄、截取&#xff0c;所以内容是工作的一些自己记录和网络内容&#xff0c;不对的欢迎批评指正。 1、ISP概述 ISP是Image Signal Processor 的简称&#xff0c;也就…

【计算机网络】VLAN原理和配置

目录 1、VLAN的原理 1.1、什么是VLAN 1.2、为什么要使用VLAN 1.3、VLAN的三种端口类型 1.4、VLAN的划分方法 2、VLAN的配置 1、VLAN的原理 1.1、什么是VLAN VLAN&#xff08;Virtual Local Area Network&#xff09;即虚拟局域网&#xff0c;是将一个物理的LAN在逻辑上…