简体   繁体   English

OpenCV imdecode 返回无

[英]OpenCV imdecode returns none

I'm trying to read an image from url.我正在尝试从 url 读取图像。

For this, I created the funcion below.为此,我创建了下面的函数。 For some url I input, it works exactly how I wish, but for others, it doesn't.对于我输入的一些 url,它完全按照我的意愿工作,但对于其他人,它没有。 In this cases the cv2.imread(img, cv2.IMREAD_COLOR) function returns none .在这种情况下, cv2.imread(img, cv2.IMREAD_COLOR) function 返回none

My code:我的代码:

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)

Example of url that works:有效的 url 示例:

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

Example of url that doesn't work:不起作用的 url 示例:

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

What i'm doing wrong here?我在这里做错了什么?

Seems there is some issue reading the file with urllib but I didn't dig into .似乎使用urllib读取文件存在一些问题,但我没有深入研究 .

I tried with import urllib.request as ur instead of from urllib.request import Request, urlopen .我尝试使用import urllib.request as ur而不是from urllib.request import Request, urlopen

This works for me:这对我有用:

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

Test on Jupyter:在 Jupyter 上测试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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