Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

python - How to use opencv in Python3 to read file from file buffer

I am trying to use this library. In particular these 3 lines:

    image_stream = io.BytesIO(image_bytes)
    frame = cv2.imread(image_stream)

and I am having an exception:

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+"
", 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

But it works on real files. what can be fixed here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here a solution:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...