【问题标题】:How to use opencv in Python3 to read file from file buffer如何在 Python3 中使用 opencv 从文件缓冲区读取文件
【发布时间】:2019-06-07 04:24:29
【问题描述】:

我正在尝试使用this 库。特别是这 3 行:

    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))会得到什么?
  • 阅读文档。 imread 将文件名作为第一个参数,而不是流。它仅用于从文件中读取。如果要从内存中解码数据,需要使用imdecode
  • 您的image_bytes 是否已编码?

标签: python python-3.x opencv


【解决方案1】:

这里有一个解决方案:

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)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多