gpt4 book ai didi

python - 如何在不保存到文件的情况下处理来自电报机器人的图像

转载 作者:行者123 更新时间:2023-12-05 03:55:49 25 4
gpt4 key购买 nike

我的电报机器人设计用于图像分类,因此我需要先读取用户的图像,例如,在执行任何操作之前使用 cv2.imread(telegram_image.jpeg, 1)在其上处理和运行我的模型。有没有一种方法可以做到这一点而不必从电报机器人下载图像文件?

这是我目前的代码:

bot = telegram.Bot(token=TOKEN)
@app.route('/{}'.format(TOKEN), methods=['POST'])
def start():
# retrieve the message in JSON and then transform it to Telegram object
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.message.chat.id
msg_id = update.message.message_id
imageId = update.message.photo[len(update.message.photo)-1].file_id

我正尝试在 Heroku 上部署(使用 Flask),但之前尝试使用 update.message.photo[-1].get_file().download() 下载文件时遇到问题.代码运行没有错误,但我无法在任何地方找到图像文件。

抱歉,我对此很陌生,非常感谢任何帮助或建议,谢谢!

最佳答案

我建议使用 python-telegram-bot为此,如果您还没有的话。 wiki 很棒,避免使用 Flask。

您可以避免将文件保存到磁盘,并使用 BytesIO 将其存储在内存中。处理消息的函数可能如下所示:

from io import BytesIO

def photo(update: Update, context: CallbackContext):
file = context.bot.get_file(update.message.photo[-1].file_id)
f = BytesIO(file.download_as_bytearray())

# f is now a file object you can do something with

result = somefunction(f)

response = 'I procsseed that and the result was %s' % (result,)

context.bot.send_message(chat_id=update.message.chat_id, text=response)

然后将处理程序添加到调度程序。请注意,使用 Filters.photo 只有照片消息才会到达此处理程序:

photo_handler = MessageHandler(Filters.photo, photo)
dispatcher.add_handler(photo_handler)

这支持最新版本 (v12) 的 API。

您可能还想看看我整理的脚本:tg_client.py .这是一个更大的 repo 的一部分,它通过 Yolov3 库进行图像处理。它还支持将机器人通信锁定到您自己的电报用户 ID(有关更多信息,请参阅我的 wiki page)。

您可以根据自己的需要修改它,方法是将 upload 函数换成调用您自己的处理脚本的东西。


编辑:我想我部分误解了你的问题,所以我会回答这部分:

by using cv2.imread(telegram_image.jpeg, 1) before doing any processing and running my model on it. Is there a way to do this without having to download the image file from the telegram bot?

感谢 this answer,我已经在我的代码中处理了这个问题这建议使用 cv2.imdecode 代替 cv2.imread

所以上面的 somefunction 可以这样处理:

def somefunction(input_stream):
image = cv2.imdecode(numpy.fromstring(input_stream, numpy.uint8), 1)

# image is now what cv2.imread('filename.jpg',1) would have returned.

# rest of your code.

return 'the result of the processing'

这避免了将文件写入磁盘,因为它全部在内存中处理。

关于python - 如何在不保存到文件的情况下处理来自电报机器人的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59876271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com