简体   繁体   中英

'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

I'm trying to draw a bounding box on an image using OpenCV2. I'm using aiohttp.ClientSession() to make a request to an image and I'm using cv2.imdecode to read the image.

My code ends up something like:

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

Usually when it gets to the imdecode part, it errors with 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte .

The image that opencv is trying to load is https://media.discordapp.net/attachments/831327584364920862/870406065257336852/photo-1571577275698-54f36820ee9b.png

Try this and see if it works:

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)

I got it too work. Turns out it was a different section of code that threw this error, and was unrelated to the snippets I sent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM