我正在尝试从url读取图像。
为此,我创建了下面的函数。对于我输入的一些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)
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
木星上的测试:
url = "https://image.freepik.com/fotos-gratis/paisagem-ambiente-bonito-de-campo-verde_29332-1855.jpg"
im = urlToImage(url)
plt.imshow(im[:,:,::-1])