Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在不保存到文件的情况下处理来自电报机器人的图像_Python_Heroku_Flask_Computer Vision_Telegram Bot - Fatal编程技术网

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

Python 如何在不保存到文件的情况下处理来自电报机器人的图像,python,heroku,flask,computer-vision,telegram-bot,Python,Heroku,Flask,Computer Vision,Telegram Bot,我的telegram bot设计用于进行图像分类,因此我需要首先从用户处读取图像,例如,在进行任何处理和运行我的模型之前,使用cv2.imread(telegrame\u image.jpeg,1)。有没有一种方法可以做到这一点,而不必从电报机器人下载图像文件 这是我目前掌握的代码: bot = telegram.Bot(token=TOKEN) @app.route('/{}'.format(TOKEN), methods=['POST']) def start(): # retrie

我的telegram bot设计用于进行图像分类,因此我需要首先从用户处读取图像,例如,在进行任何处理和运行我的模型之前,使用
cv2.imread(telegrame\u 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()
下载文件时遇到问题。代码运行时没有错误,但我在任何地方都找不到图像文件

很抱歉,我是新手,非常感谢您的帮助或建议,谢谢

如果您还没有准备好,我建议您使用。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)
然后将处理程序添加到调度程序。请使用
过滤器注意。照片
只有照片邮件才会到达此处理程序:

photo_handler = MessageHandler(Filters.photo, photo)
dispatcher.add_handler(photo_handler)
这支持API的最新版本(v12)

您可能还希望查看我编写的脚本:。这是大型回购协议的一部分,该协议通过
Yolov3
库进行图像处理。它还支持将bot通信锁定为您自己的电报用户ID(有关更多信息,请参阅my)

您可以根据自己的需要修改它,将
upload
函数替换为调用您自己的处理脚本的函数


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

在进行任何处理和运行我的模型之前,使用
cv2.imread(telegrame\u image.jpeg,1)
。有没有一种方法可以做到这一点,而不必从电报机器人下载图像文件

我在我的代码中处理了这个问题,这表明使用
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'
这避免了将文件写入磁盘,因为所有文件都在内存中处理