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

使用Azure OCR读取摄像头帧报错:'bytes'对象无'read'属性

解决Azure OCR Read接口报错:'bytes' object has no attribute 'read' 及最佳实践

问题原因

Azure Computer Vision Python SDK的read_in_stream方法要求传入类文件对象(即实现了read()方法的对象,比如io.BytesIO),而你直接传入了bytes类型的图像数据,因此触发该错误。

修复方案

将bytes数据用io.BytesIO包装成类文件对象后再传入接口,同时替换已废弃的tostring()方法为tobytes():

import io
import cv2

def detect_text(image, highest_prob):
    # 将OpenCV帧编码为JPG格式的字节数据
    _, img_encoded = cv2.imencode(".jpg", image)
    img_bytes = img_encoded.tobytes()
    # 包装为类文件对象
    img_stream = io.BytesIO(img_bytes)
    
    # 调用Azure OCR Read接口
    recognize_printed_results = computervision_client.read_in_stream(img_stream, raw=True)
    # 后续处理识别结果的逻辑...

向Azure OCR发送摄像头帧的最佳方式

  • 使用类文件对象传递数据:这是官方推荐的标准方式,既避免直接传bytes的类型问题,也兼容本地文件和内存流等多种场景。
  • 裁剪目标区域后再识别:结合自定义视觉的预测结果,裁剪出车牌、公交编号等目标区域,缩小OCR识别范围,显著提升准确率和响应速度:
    def detect_text(image, highest_prob):
        # 从自定义视觉预测结果中提取边界框(相对比例转实际像素)
        bbox = highest_prob.bounding_box
        h, w = image.shape[:2]
        x1, y1 = int(bbox.left * w), int(bbox.top * h)
        x2, y2 = int((bbox.left + bbox.width) * w), int((bbox.top + bbox.height) * h)
        # 裁剪目标区域
        cropped_img = image[y1:y2, x1:x2]
        
        # 编码并包装为流
        _, img_encoded = cv2.imencode(".jpg", cropped_img)
        img_bytes = img_encoded.tobytes()
        img_stream = io.BytesIO(img_bytes)
        
        recognize_printed_results = computervision_client.read_in_stream(img_stream, raw=True)
        # 处理识别结果...
    
  • 优化图像编码:选择JPG等压缩格式,在保证识别清晰度的前提下减少数据传输量,降低API调用延迟。
  • 添加异常处理:针对网络超时、API调用失败等情况添加try-except块,提升Demo的稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:20:30