【问题标题】:'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte“utf-8”编解码器无法解码位置 0 的字节 0x89:无效的起始字节
【发布时间】:2021-07-29 20:44:49
【问题描述】:

我正在尝试使用 OpenCV2 在图像上绘制边界框。 我使用aiohttp.ClientSession() 向图像发出请求,我使用cv2.imdecode 读取图像。

我的代码最终是这样的:

async with aiohttp.ClientSession() as session:
    async with session.get(attachment.proxy_url, headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.55'
        }) as resp:

        image = await resp.content.read()
        nparr = np.fromstring(image, dtype=np.uint8)
        cvimg = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        # *hopefully* get to this point without erroring

通常当它到达 imdecode 部分时,会出现'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte 错误。

opencv 试图加载的图片是https://media.discordapp.net/attachments/831327584364920862/870406065257336852/photo-1571577275698-54f36820ee9b.png

【问题讨论】:

  • 当您尝试阅读 np.fromstring 的文档和示例时发生了什么?他们在示例中使用的数据是否看起来像 PNG 中的原始字节?不,它看起来像包含人类可读的数字表示的文本。相反,您有原始字节,所以...查看相关文档,看看您是否无法弄清楚应该使用什么。

标签: python numpy opencv numpy-ndarray aiohttp


【解决方案1】:

试试这个,看看它是否有效:

import base64
import json
import cv2
import numpy as np

async with aiohttp.ClientSession() as session:
    async with session.get(attachment.proxy_url, headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.55'
        }) as resp:

        image = await resp.content.read()
        jpg_original = base64.b64decode(image)
        jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
        img = cv2.imdecode(jpg_as_np, flags=1)

【讨论】:

  • 现在我得到“错误:(-215:断言失败)!buf.empty() in function 'cv::imdecode_'”
  • @ryanarex 让您的网络服务器以 base64 编码形式发送,而不是以字节形式发送
【解决方案2】:

我也搞定了。 原来是另一段代码引发了这个错误,与我发送的 sn-ps 无关。

【讨论】:

    猜你喜欢
    • 2022-11-06
    • 2020-09-22
    • 2021-12-01
    • 2016-05-13
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2016-06-27
    相关资源
    最近更新 更多