【问题标题】:OpenCV imdecode returns noneOpenCV imdecode 不返回
【发布时间】:2023-04-06 00:36:01
【问题描述】:

我正在尝试从 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"

我在这里做错了什么?

【问题讨论】:

  • 尝试查看从 np.asarray 返回的 img。看它的形状。它看起来像彩色图像吗?
  • 此行返回一个不代表颜色的代码。老实说,我不知道它们的意思,这是一个示例: [255, 216, 255, 219, 0, 67, 0, 1, 1, 1, 1....] cv2.imdecode 应该获取每个数字并转换为一个 BGR 数组

标签: python opencv urllib cv2


【解决方案1】:

使用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])

【讨论】:

  • 现在我正在测试您的解决方案,它几乎可以工作。如果我通过 ur.urlopen(url) 中的 url 工作正常。但是请求需要通过反报废块,如果我使用ur.urlopen(req),问题仍然存在
  • 现在可以了,我只是更改了 Request 函数,删除了 Range': 'bytes=0-{}'.format(5000)} 部分。我不知道会发生什么,但它现在有效
猜你喜欢
  • 1970-01-01
  • 2018-06-08
  • 2018-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
相关资源
最近更新 更多