从 4 个通道的流中读取 PNG 图像

时间:2021-08-01 20:16:40

标签: python opencv discord.py opencv-python

我正在开发一个 Discord 机器人,它接受各种用于 OCR 的图像。当用户上传带有 4 个通道的 PNG 时,它会出错。我的意思是它将图像读取为几乎 100% 的白色,而实际图像则充满了色彩。

我尝试用 cv2.COLOR_BGRA2BGR 转换它,但这不起作用。但是在我的 pytest 中它确实有效。这可能是因为我在 pytest 中使用了 cv2.imread,这与我的实际代码有点不同。

代码(损坏)

<块引用>
for a in supported_attachments:
  async with aiohttp.ClientSession() as session:
    async with session.get(a) as res:
      if res.status == 200:
        buffer = io.BytesIO(await res.read())
        arr = np.asarray(bytearray(buffer.read()), dtype=np.uint8)
        img = cv2.imdecode(arr, -1)
        if len(img.shape) > 2 and img.shape[2] == 4:
          print('convert')
          img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
          plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
          plt.show() 
        images.append(img)

pytest(有效)

<块引用>

image = cv2.imread('../tests/images/stats/english/kills_png.png', cv2.COLOR_BGRA2BGR)

有什么建议或想法吗?

1 个答案:

答案 0 :(得分:1)

标志 cv2.COLOR_BGRA2BGR 用于 cv2.cvtColor() 而不是 cv2.imread()

cv2.imread() 的所有清单常量都以 cv2.IMREADxxx 开头并定义为 concat_ws