You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不保存文件从Telegram获取图片字节并传入OpenCV处理?

问题:Telegram机器人直接处理字节流图片识别条形码失败

我开发了一款接收带条形码图片的Telegram机器人,通过Telebot模块对接Telegram API,需要完成图片处理、条形码识别并将结果存入数据库。目前遇到的问题:从Telegram下载的图片为字节格式,保存为PNG后可被OpenCV正常识别条码,但希望跳过保存步骤,直接将字节数据传入OpenCV处理。尝试将字节码转为numpy数组后,OpenCV无法识别条形码;保存图片后再打开则可正常识别,现寻求无需保存文件的解决方案。

解决方案

核心问题出在字节流转OpenCV矩阵的细节处理,以及条形码识别接口的返回值解析上,调整如下:

  • 替换已弃用的np.fromstring为np.frombuffer,更安全地处理字节数据
  • 使用cv2.IMREAD_COLOR替代cv2.IMREAD_UNCHANGED,确保图片转为BarcodeDetector所需的BGR颜色空间
  • 正确解析detectAndDecode的返回结果,该接口返回包含解码内容、条码格式等信息的元组,需提取有效数据

修改后的完整代码

import telebot as tb
from config import token
import cv2
import numpy as np


bot = tb.TeleBot(token)
bot.set_my_commands([
    tb.types.BotCommand("/start", "Start")
])


@bot.message_handler(commands=['start'])
def start_bot(message):
    bot.send_message(message.chat.id, 'Start Bot')

@bot.message_handler(func=lambda m: True, content_types=['photo'])
def get_broadcast_picture(message):
    # 取最高清的图片(message.photo按分辨率从小到大排列,[-1]对应最高清版本)
    file_info = bot.get_file(message.photo[-1].file_id)
    file_bytes = bot.download_file(file_info.file_path)
    result_code = scanner_bar_cv2(file_bytes)
    bot.send_message(message.chat.id, result_code if result_code else "未识别到条形码")

def scanner_bar_cv2(file_bytes: bytes):
    # 将字节数据转为numpy数组
    nparr = np.frombuffer(file_bytes, np.uint8)
    # 解码为OpenCV兼容的BGR格式图片
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    
    bd = cv2.barcode.BarcodeDetector()
    # detectAndDecode返回元组:(解码结果列表, 条码格式列表, 检测区域, 置信度)
    decoded_data, _, _, _ = bd.detectAndDecode(img)
    
    # 返回第一个有效解码结果,无结果则返回空字符串
    return decoded_data[0] if len(decoded_data) > 0 else ""


if __name__ == "__main__":
    bot.polling(non_stop=True, timeout=123)

额外优化说明

  • 选择最高清的图片输入,提升条形码识别成功率
  • 增加识别失败时的友好提示,优化用户体验
  • 移除未使用的冗余模块,精简代码结构

内容的提问来源于stack exchange,提问作者Jun_Pegas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 04:26:15