0

0

使用OpenAi的食品识别和营养估算

霞舞

霞舞

发布时间:2025-02-11 08:50:01

|

826人浏览过

|

来源于dev.to

转载

这是您可以在短短20分钟内使用openai构建简单的食物识别和营养估算应用程序的方法 它的工作原理

>图像编码:图像被转换为​​base64格式,以通过openai的api处理。

>食物识别提示:该应用将图像发送到openai,以识别食物及其各自的数量。

营养估计:使用另一个提示来估计基于确定的食品及其数量的营养价值。

> 显示结果:使用gradio显示出估计的卡路里,蛋白质,脂肪和碳水化合物的值。

>

这是一个非常简单的代码,可以改进/更好地组织起来,但是想法是说明它可以轻松地创建一个简单的poc。 如果您正在从事有趣的项目,请在

上与我联系

from openai import OpenAI
from pydantic import BaseModel
import base64
from typing import List
import gradio as gr

def encode_image(image_path):
  with open(image_path, "rb") as image_file:
    return base64.b64encode(image_file.read()).decode('utf-8')

openai_api_key = "key"
client = OpenAI(api_key=openai_api_key)

"""pydantic models to record food items and nutrient information, 
not necessary but helpful if you intend to create apis 
or use the data in other ways.
"""
class Food(BaseModel):
    name: str
    quantity: str

class Items(BaseModel):
    items: List[Food]

class Nutrient(BaseModel):
    steps: List[str]
    reasons: str
    kcal: str
    fat: str
    proteins: str
    carbohydrates: str


def recognize_items(image):
    """This function takes an image and returns a list of recognized food items along with their count and the nutrition. 
    """
    #first recognize items and quantities
    messages = [
        {
        "role": "user",
        "content": [
            {
            "type": "text",
            "text": f"You are an expert in recognising individual food items and their quantity. Give count(number) for countable items and an estimate for liquid/mixed or non countable items.  For example if you have one burger,two pastries, 2 pav, bhaji and dal in an image, you return burger,pastry,pav, bhaji and dal along with the count or estimates without any duplicates. For non countable items give an estimate in grams while explaining like 'looks 1 teaspoon of sauce, so around 5-8 grams' or 'looks 1 serving of bhaji, so around 150-200gms'. Given the image below, recognise food items with their quantity.",
            }
        ],
        }
    ]

    base64_image = encode_image(image)
    dic = {
                "type": "image_url",
                "image_url": {
                    "url":  f"data:image/jpeg;base64,{base64_image}",
                    "detail": "low"
                },
            }
    messages[0]["content"].append(dic)
    response = client.beta.chat.completions.parse(
    model="gpt-4o-mini",
    messages=messages,
    response_format=Items,
    max_tokens=300,
    temperature=0.1
    )
    foods = response.choices[0].message.parsed

    res = ""
    for food in foods.items:
        res=res+food.name+ " "+food.quantity+"\n"

    #now estimate nutrition, we can use a separate model for this task
    messages = [
        {
        "role": "user",
        "content": [
            {
            "type": "text",
            "text": f"You are an expert in estimating information regarding nutririon given the food items and thier quantities. Think step by step considering the given food items and their quantities, and give an estimated range(lowest - highest) of kcal, range(lowest - highest) of fat, range of proteins(lowest - highest) and carbohydrates(lowest - highest). Ignore contributions from minor items. Ensure your estimations are solely based on the provided quantities.  Return steps,reasons and estimations if this food was consumed. \n\nfood and quantity consumed by user: {res} \n\n.",
            }
        ],
        }
    ]
    dic = {
                "type": "image_url",
                "image_url": {
                    "url":  f"data:image/jpeg;base64,{base64_image}",
                    "detail": "low"
                },
            }
    messages[0]["content"].append(dic)
    response = client.beta.chat.completions.parse(
    model="gpt-4o-mini",
    messages=messages,
    response_format=Nutrient,
    max_tokens=500,
    temperature=0.1
    )
    nuts = response.choices[0].message.parsed
    steps = " ".join(nuts.steps)
    res=res+"\n"+steps+"\n\ncalories: "+nuts.kcal+" \nfats: "+nuts.fat+" \nproteins: "+nuts.proteins+" \ncarbohydrates: "+nuts.carbohydrates+"\n"+nuts.reasons+"\n"+"*These are estimations based on image. They might not be perfect or accurate. Please calculate based on the food you consume for a more precise estimate."
    return res


with gr.Blocks() as demo:
    foods=None
    with gr.Row():
        image_input = gr.Image(label="Upload Image",height=300,width=300,type="filepath")

    with gr.Row() as but_row:
        submit_btn = gr.Button("Detect food and quantity")

    with gr.Row() as text_responses_row: 
        text_response_1 = gr.Textbox(label="Detected food and quantity",scale=1)

    submit_btn.click(
        recognize_items,
        inputs=[image_input],
        outputs=[text_response_1]
    )

if __name__ == "__main__":
    demo.launch() 

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
2026赚钱平台入口大全
2026赚钱平台入口大全

2026年最新赚钱平台入口汇总,涵盖任务众包、内容创作、电商运营、技能变现等多类正规渠道,助你轻松开启副业增收之路。阅读专题下面的文章了解更多详细内容。

33

2026.01.31

高干文在线阅读网站大全
高干文在线阅读网站大全

汇集热门1v1高干文免费阅读资源,涵盖都市言情、京味大院、军旅高干等经典题材,情节紧凑、人物鲜明。阅读专题下面的文章了解更多详细内容。

32

2026.01.31

无需付费的漫画app大全
无需付费的漫画app大全

想找真正免费又无套路的漫画App?本合集精选多款永久免费、资源丰富、无广告干扰的优质漫画应用,涵盖国漫、日漫、韩漫及经典老番,满足各类阅读需求。阅读专题下面的文章了解更多详细内容。

36

2026.01.31

漫画免费在线观看地址大全
漫画免费在线观看地址大全

想找免费又资源丰富的漫画网站?本合集精选2025-2026年热门平台,涵盖国漫、日漫、韩漫等多类型作品,支持高清流畅阅读与离线缓存。阅读专题下面的文章了解更多详细内容。

7

2026.01.31

漫画防走失登陆入口大全
漫画防走失登陆入口大全

2026最新漫画防走失登录入口合集,汇总多个稳定可用网址,助你畅享高清无广告漫画阅读体验。阅读专题下面的文章了解更多详细内容。

11

2026.01.31

php多线程怎么实现
php多线程怎么实现

PHP本身不支持原生多线程,但可通过扩展如pthreads、Swoole或结合多进程、协程等方式实现并发处理。阅读专题下面的文章了解更多详细内容。

1

2026.01.31

php如何运行环境
php如何运行环境

本合集详细介绍PHP运行环境的搭建与配置方法,涵盖Windows、Linux及Mac系统下的安装步骤、常见问题及解决方案。阅读专题下面的文章了解更多详细内容。

0

2026.01.31

php环境变量如何设置
php环境变量如何设置

本合集详细讲解PHP环境变量的设置方法,涵盖Windows、Linux及常见服务器环境配置技巧,助你快速掌握环境变量的正确配置。阅读专题下面的文章了解更多详细内容。

0

2026.01.31

php图片如何上传
php图片如何上传

本合集涵盖PHP图片上传的核心方法、安全处理及常见问题解决方案,适合初学者与进阶开发者。阅读专题下面的文章了解更多详细内容。

2

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号