首页 > 解决方案 > OpenCV imdecode 不返回

问题描述

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

为此,我创建了下面的函数。对于我输入的某些 url,它完全按照我的意愿工作,但对于其他人,它没有。在这种情况下,cv2.imread(img, cv2.IMREAD_COLOR)函数返回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)

有效的网址示例:

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

无效的网址示例:

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

我在这里做错了什么?

标签: pythonopencvurllibcv2

解决方案


似乎在读取文件时存在一些问题,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])

推荐阅读