- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的电报机器人设计用于图像分类,因此我需要先读取用户的图像,例如,在执行任何操作之前使用 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/
我是一名优秀的程序员,十分优秀!