下载url图片,url中含有中文也不报错的方法

import cv2
import requests
import time
import numpy as np
def download_image_as_buffer(img_url):
    retries = 0
    while retries < 3:
        try:
            # 发送 HTTP 请求下载图片
            response = requests.get(img_url, timeout=10)
            response.raise_for_status()  # 检查请求是否成功
            image_buffer = response.content #字节流图片
            return image_buffer

        except Exception as e:
            retries += 1
            if retries >= 3:
                return None  # 如果重试了3次还是失败,则返回None
            time.sleep(retries * 0.1)  # 重试之间暂停0.1
            #print(f"Error downloading image: {e}")

img_url = "https://*****.com/*****/中文.jpg"
image_buffer = download_image_as_buffer(img_url)

# 3. 将二进制数据转换为 NumPy 数组
image_array = np.frombuffer(image_buffer, dtype=np.uint8)
# 4. 使用 OpenCV 解码图片
image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)

你可能感兴趣的:(python,opencv)