当前位置: 首页 > news >正文

基于YOLOv8目标检测与chef-transformer(T5)从图像创建食谱

前言

在本文中,将演示如何使用从Roboflow获得的开源产品数据来训练我的YOLOv8模型,然后将其与从Hugging Face获得的chef-transformer(T5)模型集成。应用程序的主要目标是将检测到的对象参数化地发送到语言模型,并在NLP和CV之间建立关系。
在这里插入图片描述

YOLOv8 目标检测

YOLOv8是由ultralytics公司在2023年1月10日开源的一款重量级更新版本,作为YOLOv5的继承者,它支持图像分类、物体检测和实例分割等任务。在开源之前,YOLOv8就已经受到了用户的热切期待。作为一个SOTA(State of the Art)模型,YOLOv8在前代YOLO系列的成功基础上,引入了多项创新,旨在进一步提升模型的性能和灵活性。这些创新包括一个全新的骨干网络、一个无Anchor的检测头,以及一个新型的损失函数,使得模型能够在从CPU到GPU的各种硬件平台上流畅运行。

ultralytics公司并没有将这个开源库命名为YOLOv8,而是选择了“ultralytics”这个名称。这样做的原因是,公司希望将这个库定位为一个算法框架,而不仅仅是一个特定的算法。ultralytics的主要特点是其可扩展性,它不仅能够支持YOLO系列模型,还旨在兼容非YOLO模型,并能够广泛应用于分类、分割、姿态估计等多种任务。

环境安装

conda create -n yolov8 python=3.8
activate ylolv8
conda install pytorch==2.0.0 torchvision==0.15.0 torchaudio==2.0.0 pytorch-cuda=11.7 -c pytorch -c nvidia
pip install ultralytics

从Roboflow获取YOLOv8训练数据

Roboflow 是一个资源丰富的平台,拥有超过2亿张图像和20多万个数据集,为训练模型提供了广泛的选择。它能够满足对水果和蔬菜图像数据的需求,以便训练我的模型。此外,Roboflow 提供了 Roboflow Health Check 模块,这是一个功能强大的模块,允许在训练模型之前进行深入分析。这有助于更好地理解所需数据,并确保使用最恰当的数据集。
在这里插入图片描述

导入库并定义需求

import os
import streamlit as st
from ultralytics import YOLO
from IPython.display import display, Image
from langchain import PromptTemplate, HuggingFaceHub, LLMChain

模型推理

使用模型预测测试图像,并将检测到的对象类别存储在变量中。

model = YOLO('C:\\Users\\batuh\\Desktop\\last_pr_best.pt')
results = model.predict(source='test.jpeg', conf=0.50, save = True)
unique_names = set()
names = model.names
for r in results:for c in r.boxes.cls:unique_names.add(names[int(c)])print(unique_names)

以这种方式返回唯一类别并将像这样将它们传递给语言模型。

{'Potato', 'Garlic', 'Onion', 'Tomato', 'Green Chili'}

语言模型

pip install transformers

在语言模型中使用检测到的对象

使用Langchain库来训练了超过200万食谱的语言模型。在这里,将的YOLO模型检测到的对象作为文本输入,以便生成菜谱。

template = """Question: {question}: """
prompt = PromptTemplate(template=template, input_variables=["question"])llm_chain = LLMChain(prompt=prompt, llm=HuggingFaceHub(repo_id="flax-community/t5-recipe-generation", model_kwargs={"temperature": 0.3, "max_length": 512}))question = ', '.join(unique_names)
recipe = llm_chain.run(question)

得到了一个不错的炸三角食谱,如下:

'title: samosas ingredients: 1 large potato 1 tbsp minced garlic 1 tbsp minced onion 1 tbsp minced tomato 1 tbsp minced green chili answer the call 1 tbsp do cook. directions: cut the potato into small cubes. add the minced garlic, minced onion, minced tomato, and minced green chili. mix well. heat a griddle or frying pan over medium heat. place the samosas on the griddle and cook until golden brown on both sides.'

使用Streamlit创建界面

使用Streamlit创建了一个交互式界面,Streamlit是一个开源的Python库,可以轻松创建和共享机器学习和数据科学项目的Web应用程序。

import os
import streamlit as st
from ultralytics import YOLO
from IPython.display import display, Image
from langchain import PromptTemplate, HuggingFaceHub, LLMChainmodel_path = 'C:\\Users\\batuh\\Desktop\\last_pr_best.pt'st.set_page_config(page_title="Recipe Generator",  page_icon="🍳",     layout="wide",      initial_sidebar_state="expanded"    
)st.title("Recipe Generator :female-cook:")
st.subheader("Upload an image to generate a recipe for the detected objects.")
st.markdown(f"""<style>body {{background-color: darkgreen;}}</style>""",unsafe_allow_html=True,)def predict_objects_and_generate_recipe(image_path, model_path, define_conf):os.environ['HUGGINGFACEHUB_API_TOKEN'] = 'Your-Key'# YOLO model ile nesneleri tanımamodel = YOLO(model_path)results = model.predict(source=image_path, conf=define_conf, save=True)names = model.namesunique_names = set()for r in results:for c in r.boxes.cls:unique_names.add(names[int(c)])return unique_namesdef generate_recipe_using_language_model(unique_names):template = """Question: {question}: """prompt = PromptTemplate(template=template, input_variables=["question"])llm_chain = LLMChain(prompt=prompt, llm=HuggingFaceHub(repo_id="flax-community/t5-recipe-generation", model_kwargs={"temperature": 0.3, "max_length": 512}))question = ', '.join(unique_names)recipe = llm_chain.run(question)return recipeimage_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
conf_threshold = st.slider("Confidence Threshold", 0.1, 1.0, 0.25)if image_file is not None:temp_dir = 'temp'os.makedirs(temp_dir, exist_ok=True)  image_path = os.path.join(temp_dir, image_file.name)  with open(image_path, 'wb') as f:f.write(image_file.read())unique_names = predict_objects_and_generate_recipe(image_path, model_path, conf_threshold)recipe = generate_recipe_using_language_model(unique_names)title = recipe.split('ingredients:')[0]ingredients = recipe.split('directions:')[0].split('ingredients:')[1].split('answer the call 1 do cook.')[0].split(' ')directions = (recipe.split('directions:')[1].split('add salt and pepper to taste.')[0])full_recipe = '{}\n\n\nIngredients :\n{}\nDirections :\n{}'.format(title.capitalize().title(),'\n'.join(['    {}'.format(ingredient).title() for ingredient in ingredients]),'    {}'.format(directions).capitalize())st.image(image_path)st.markdown("""<style>.big-font {font-size:60px !important;}</style>""", unsafe_allow_html=True)st.write("Recipe:")st.write('<p class="big-font">'+full_recipe+'</p>', unsafe_allow_html=True, fontsize = 100)

借助Streamlit库,可以更改置信度阈值,并创建一个漂亮的界面,将上传图像中检测到的对象与我们的语言模型结合起来。
在这里插入图片描述

备注

原本地址:https://medium.com/@batuhansenerr/yolov8-and-chef-transformer-t5-to-create-recipe-from-image-ae10c0e83656

相关文章:

  • C++结尾
  • 随记——机器学习
  • 如何一个月速通——2024年网络工程师,软考老鸟备考经验分享!
  • Android 通过自定义注解实现Activity间跳转时登录路由的自动拦截
  • Qt_文件操作
  • 了解独享IP的概念及其独特优势
  • 微信小程序如何使用自定义的字体
  • 解决macOS MySQL安装后不能远程访问的问题
  • golang雪花算法实现64位的ID
  • 无人机侦测:频谱无线电侦测设备技术详解
  • OSPFv3协议几类LSA介绍
  • redis序列化数据时,如何包含clsss类型信息?
  • 多线程计算π
  • 力扣9.25
  • 51单片机如何判断浮点数nan
  • Docker 笔记(1):介绍、镜像、容器及其基本操作
  • React-flux杂记
  • ReactNative开发常用的三方模块
  • 阿里云ubuntu14.04 Nginx反向代理Nodejs
  • 算法---两个栈实现一个队列
  • 腾讯优测优分享 | Android碎片化问题小结——关于闪光灯的那些事儿
  • 原创:新手布局福音!微信小程序使用flex的一些基础样式属性(一)
  • 在Mac OS X上安装 Ruby运行环境
  • ​​​​​​​STM32通过SPI硬件读写W25Q64
  • # Java NIO(一)FileChannel
  • #14vue3生成表单并跳转到外部地址的方式
  • #我与Java虚拟机的故事#连载08:书读百遍其义自见
  • #预处理和函数的对比以及条件编译
  • (6)添加vue-cookie
  • (备份) esp32 GPIO
  • (笔记)Kotlin——Android封装ViewBinding之二 优化
  • (苍穹外卖)day03菜品管理
  • (附源码)spring boot儿童教育管理系统 毕业设计 281442
  • (附源码)计算机毕业设计ssm-Java网名推荐系统
  • (函数)颠倒字符串顺序(C语言)
  • (源码分析)springsecurity认证授权
  • (转) Face-Resources
  • (转)关于pipe()的详细解析
  • (自用)交互协议设计——protobuf序列化
  • .[backups@airmail.cc].faust勒索病毒的最新威胁:如何恢复您的数据?
  • .NET CLR基本术语
  • .NET delegate 委托 、 Event 事件
  • .Net 访问电子邮箱-LumiSoft.Net,好用
  • .NET/C# 避免调试器不小心提前计算本应延迟计算的值
  • .NET/C# 使用反射调用含 ref 或 out 参数的方法
  • .net专家(高海东的专栏)
  • @Builder注释导致@RequestBody的前端json反序列化失败,HTTP400
  • @private @protected @public
  • [Algorithm][动态规划][子序列问题][最长递增子序列][摆动序列]详细讲解
  • [Android Studio 权威教程]断点调试和高级调试
  • [bzoj2957]楼房重建
  • [C# 开发技巧]如何使不符合要求的元素等于离它最近的一个元素
  • [C#][opencvsharp]opencvsharp sift和surf特征点匹配
  • [C][数据结构][树]详细讲解
  • [CISCN2021 Quals]upload(PNG-IDAT块嵌入马)