python - 如何使用 opencv (python) 从 url 读取 gif

标签 python opencv

我可以使用 cv2 as 读取 jpg 文件

import cv2
import numpy as np
import urllib
url = r'http://www.mywebsite.com/abc.jpg'
req = urllib.request.urlopen(url)
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr,-1)
cv2.imshow('abc',img)

但是,当我使用 gif 文件执行此操作时,它会返回一个错误:

error: (-215) size.width>0 && size.height>0 in function cv::imshow

如何解决这个问题?

最佳答案

步骤:

  1. 使用urllib从网络读取gif,
  2. 使用imageio.mimread 将gif 加载到nump.ndarray(s)。
  3. 通过 numpyOpenCV 更改 channel 顺序。
  4. 使用 OpenCV 进行其他图像处理

代码示例:

import imageio
import urllib.request

url = "/image/lui1A.gif"
fname = "tmp.gif"

## Read the gif from the web, save to the disk
imdata = urllib.request.urlopen(url).read()
imbytes = bytearray(imdata)
open(fname,"wb+").write(imdata)

## Read the gif from disk to `RGB`s using `imageio.miread` 
gif = imageio.mimread(fname)
nums = len(gif)
print("Total {} frames in the gif!".format(nums))

# convert form RGB to BGR 
imgs = [cv2.cvtColor(img, cv2.COLOR_RGB2BGR) for img in gif]

## Display the gif
i = 0

while True:
    cv2.imshow("gif", imgs[i])
    if cv2.waitKey(100)&0xFF == 27:
        break
    i = (i+1)%nums
cv2.destroyAllWindows()

注意。 我在另一个答案中使用了 gif。 Video Stabilization with OpenCV

结果:

>>> Total 76 frames!

显示的 gif 帧之一:

enter image description here

关于python - 如何使用 opencv (python) 从 url 读取 gif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48163539/

相关文章:

c++ - 将 opencv::Mat 复制到 Mat*

python - win32com导入错误python 3.4

python - Tkinter 窗口不显示任何内容

python - google-cloud 使用 python api 获取实例 ID 和区域

python - 如何校正和识别图像中的短文本

python - 使用openCV python查找骨架与边界之间的距离

python - 如何将 Countvectorized 数据转换回 Python 中的文本数据?

python - 尝试使用 astropy 将 FITS 文件转换为 ndarray 时获取 NaN 值

algorithm - 论文 "An Image Signature for any kind of Image"中的算法背后的推理是什么?

opencv:如何使用 kmeans() 按角度进行聚类