如何在aiogram中将message.photo直接作为文件传入函数(无需存库)
解决Telegram机器人人脸识别:无需存储直接传入照片的方法
当然可以不用保存到数据库,直接把照片以内存数据的形式传入函数。你之前的问题在于传入的message.photo是PhotoSize对象列表、file_id是字符串,都不符合模型要求的文件路径或numpy数组格式。以下是具体实现方案:
核心思路
通过Telegram Bot API将照片下载到内存(而非本地文件或数据库),转换成模型能识别的格式(PIL Image或numpy数组),再传入分析函数。
具体代码实现
1. 处理Telegram消息中的照片
假设你使用python-telegram-bot库,先在消息处理函数中把照片下载到内存:
from io import BytesIO from PIL import Image import numpy as np def handle_photo(update, context): # 取分辨率最高的照片(message.photo按分辨率从小到大排序,最后一个是最高清的) highest_res_photo = update.message.photo[-1] # 获取文件对象 file_obj = context.bot.get_file(highest_res_photo.file_id) # 下载照片内容到内存BytesIO对象 photo_bytes = BytesIO(file_obj.download_as_bytearray()) # 调用分析方法 recognition_result = PhotoAnalyser.analyse_photo(photo_bytes) update.message.reply_text(f"识别到的类别:{recognition_result}")
2. 修改PhotoAnalyser类
调整analyse_photo方法,支持处理内存中的照片数据:
class PhotoAnalyser: @staticmethod def analyse_photo(photo_bytes): # 将BytesIO转换为PIL Image,再转成numpy数组(适配模型输入要求) img = Image.open(photo_bytes) img_np = np.array(img) temp = [] # 用numpy数组执行预测 prediction_result = model.predict(img_np, confidence=30, overlap=30) for prediction in prediction_result.json()['predictions']: temp.append(prediction['class']) # 保存预测后的图片(可选,若要发给用户可存到内存) output_buffer = BytesIO() prediction_result.save(output_buffer, format='JPEG') output_buffer.seek(0) # 若需发送给用户:context.bot.send_photo(chat_id=xxx, photo=output_buffer) return temp
关键说明
- 为什么之前的尝试失败?
message.photo是Telegram封装的PhotoSize对象集合,file_id只是照片的唯一标识字符串,都不是模型能直接解析的文件内容或数组。 - 若你的模型支持直接读取BytesIO对象(比如Ultralytics YOLO),可以省略PIL和numpy转换步骤,直接把
photo_bytes传入model.predict。 - 保存预测图时,避免用
f'{file}_prediction.jpg'这种写法(BytesIO对象无法转成字符串),改用内存缓冲区或固定文件名。
内容的提问来源于stack exchange,提问作者Elizaveta Borisyonok
相关产品推荐
相关产品推荐

