如何在Python3中使用OpenCV从文件缓冲区读取文件

4
我正在尝试使用这个库。特别是以下三行代码:
    image_stream = io.BytesIO(image_bytes)
    frame = cv2.imread(image_stream)

我遇到了一个异常:

Traceback (most recent call last):
  File "/home/a/Pictures/pycharm-community-2018.3.2/helpers/pydev/pydevd.py", line 1741, in <module>
    main()
  File "/home/a/Pictures/pycharm-community-2018.3.2/helpers/pydev/pydevd.py", line 1735, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/home/a/Pictures/pycharm-community-2018.3.2/helpers/pydev/pydevd.py", line 1135, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/home/a/Pictures/pycharm-community-2018.3.2/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/a/Documents/wiker/main.py", line 13, in <module>
    if __name__ == '__main__': main()
  File "/home/a/Documents/wiker/main.py", line 10, in main
    article['video'] = video.make_video_from_article(article)
  File "/home/a/Documents/wiker/video.py", line 15, in make_video_from_article
    frame = cv2.imread(image_stream)
TypeError: bad argument type for built-in operation

但它可以在真实文件上运行。这里有什么需要修复的地方。

如果您打印出 print(type(image_stream)),您会得到什么? - Employee
<class '_io.BytesIO'> - user10886181
可能是 https://dev59.com/_1YN5IYBdhLWcg3w9MRJ 的重复问题。 - Employee
1
阅读文档。imread 的第一个参数需要是文件名,而不是流。它只能从文件中读取。如果你想要从内存中解码数据,你需要使用 imdecode - Dan Mašek
你的 image_bytes 是否已经编码? - Ulrich Stern
我这样获取图像数据 image_content = get("https://" + image_url).content,需要引入模块 from requests import get - user10886181
1个回答

28

这里有一个解决方案:

import io, requests, cv2, numpy as np

url = "https://images.pexels.com/photos/236047/pexels-photo-236047.jpeg"
img_stream = io.BytesIO(requests.get(url).content)
img = cv2.imdecode(np.frombuffer(img_stream.read(), np.uint8), 1)

cv2.imshow("img", img)
cv2.waitKey(0)

1
太棒了,谢谢!如果我想做相反的事情怎么办?从cv2转到io流? - Rami.K
@Rami.K https://dev59.com/OmMl5IYBdhLWcg3w_bHj#64849668 - ch4rl1e97

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接