5

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

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

6
  • What do you get if you print out print(type(image_stream)) ? Commented Jan 12, 2019 at 13:59
  • <class '_io.BytesIO'> Commented Jan 12, 2019 at 14:03
  • Possible duplicate of stackoverflow.com/questions/46624449/… Commented Jan 12, 2019 at 14:10
  • 1
    Read the docs. imread takes a filename as the first parameter, not a stream. It's meant to read from files only. If you want to decode data from memory, you need to use imdecode. Commented Jan 12, 2019 at 14:58
  • Are your image_bytes even encoded? Commented Jan 12, 2019 at 15:46

1 Answer 1

30

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)
Sign up to request clarification or add additional context in comments.

2 Comments

This is awesome thanks - what if I want to do the opposite? go from cv2 to io stream?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.