大创项目推荐 深度学习的水果识别 opencv python

2024-01-19 08:44

本文主要是介绍大创项目推荐 深度学习的水果识别 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

这篇关于大创项目推荐 深度学习的水果识别 opencv python的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/621873

相关文章

Python调用Orator ORM进行数据库操作

《Python调用OratorORM进行数据库操作》OratorORM是一个功能丰富且灵活的PythonORM库,旨在简化数据库操作,它支持多种数据库并提供了简洁且直观的API,下面我们就... 目录Orator ORM 主要特点安装使用示例总结Orator ORM 是一个功能丰富且灵活的 python O

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

部署Vue项目到服务器后404错误的原因及解决方案

《部署Vue项目到服务器后404错误的原因及解决方案》文章介绍了Vue项目部署步骤以及404错误的解决方案,部署步骤包括构建项目、上传文件、配置Web服务器、重启Nginx和访问域名,404错误通常是... 目录一、vue项目部署步骤二、404错误原因及解决方案错误场景原因分析解决方案一、Vue项目部署步骤

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

如何通过Python实现一个消息队列

《如何通过Python实现一个消息队列》这篇文章主要为大家详细介绍了如何通过Python实现一个简单的消息队列,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录如何通过 python 实现消息队列如何把 http 请求放在队列中执行1. 使用 queue.Queue 和 reque

Python如何实现PDF隐私信息检测

《Python如何实现PDF隐私信息检测》随着越来越多的个人信息以电子形式存储和传输,确保这些信息的安全至关重要,本文将介绍如何使用Python检测PDF文件中的隐私信息,需要的可以参考下... 目录项目背景技术栈代码解析功能说明运行结php果在当今,数据隐私保护变得尤为重要。随着越来越多的个人信息以电子形

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

Python Jupyter Notebook导包报错问题及解决

《PythonJupyterNotebook导包报错问题及解决》在conda环境中安装包后,JupyterNotebook导入时出现ImportError,可能是由于包版本不对应或版本太高,解决方... 目录问题解决方法重新安装Jupyter NoteBook 更改Kernel总结问题在conda上安装了

golang内存对齐的项目实践

《golang内存对齐的项目实践》本文主要介绍了golang内存对齐的项目实践,内存对齐不仅有助于提高内存访问效率,还确保了与硬件接口的兼容性,是Go语言编程中不可忽视的重要优化手段,下面就来介绍一下... 目录一、结构体中的字段顺序与内存对齐二、内存对齐的原理与规则三、调整结构体字段顺序优化内存对齐四、内

如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解

《如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解》:本文主要介绍如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别的相关资料,描述了如何使用海康威视设备网络SD... 目录前言开发流程问题和解决方案dll库加载不到的问题老旧版本sdk不兼容的问题关键实现流程总结前言作为