OpenCV 即时解码 returns none

OpenCV imdecode returns none

我正在尝试从 url 中读取图像。

为此,我创建了以下函数。对于我输入的一些 url,它完全按照我的意愿工作,但对于其他人,它却没有。在这种情况下,cv2.imread(img, cv2.IMREAD_COLOR) 函数 returns none

我的代码:

import cv2     
from urllib.request import Request, urlopen
import numpy as np



def urlToImage(url):
    # download image,convert to a NumPy array,and read it into opencv
    req = Request(
        url,
        headers={'User-Agent': 'Mozilla5.0(Google spider)', 'Range': 'bytes=0-{}'.format(5000)})
    resp = urlopen(req)
    img = np.asarray(bytearray(resp.read()), dtype="uint8")
    img = cv2.imdecode(img, cv2.IMREAD_COLOR)
    # return the image
    return img

img = urlToImage('https://my_image.jpg')
print(img)

有效的 url 示例:

"https://image.freepik.com/fotos-gratis/paisagem-ambiente-bonito-de-campo-verde_29332-1855.jpg"

无效的 url 示例:

"https://veja.abril.com.br/wp-content/uploads/2019/03/tecnologia-samsung-s10-01.jpg"

我哪里做错了?

使用 urllib 读取文件似乎有一些问题,但我没有深入研究

我尝试使用 import urllib.request as ur 而不是 from urllib.request import Request, urlopen

这对我有用:

import cv2
import numpy as np
import urllib.request as ur
from matplotlib import pyplot as plt # for testing in Jupyter

def urlToImage(url):
    resp = ur.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return image

在 Jupyter 上测试:

url = "https://image.freepik.com/fotos-gratis/paisagem-ambiente-bonito-de-campo-verde_29332-1855.jpg"
im = urlToImage(url)
plt.imshow(im[:,:,::-1])