python - 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"
我在这里做错了什么?
解决方案
似乎在读取文件时存在一些问题,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])
推荐阅读
- swift - 如何使用 Swift 5 /SwiftUI 将 AVAudioRecorder 文件上传到 Firebase 存储?
- python - 如何在没有 sys 的情况下从并行目录导入 py 文件
- python - ProfileReport(df) 将计算的间隔显示为 MISSING、REJECTED、UNSUPPORTED
- python - 在 Opencv 中收到错误:(-215:Assertion failed) !_src.empty() in function 'cvtColor'
- sql - 选择不返回的jpa查询更新
- r - 对于参考和数据,级别的顺序不同。重构数据以匹配
- python - 当数字除以 11 时找到余数的递归函数
- r - R启动时出现“错误:C堆栈使用量太接近限制”
- python - 如何在不定义餐厅名称的情况下对字典列表进行排序并获取具有相同餐厅名称的所有订单?
- animation - 制作 SVG 图像的绘制动画