Python-opencv: Read image data from stdin
Question: How can I read image data from stdin rather than from a file?

With the C++ interface, it seems to be possible:
<http://stackoverflow.com/a/5458035/908515>. The function `imdecode` is
available in Python as well. But it expects a `numpy array` as (first)
argument. I have no idea how to convert the stdin data.

This is what I tried:

    
    
    import cv
    import sys
    import numpy
    
    stdin = sys.stdin.read()
    im = cv.imdecode(numpy.asarray(stdin), 0)
    

Result: `TypeError: <unknown> data type = 18 is not supported`


Answer: Looks like python stdin buffer is too small for images. You can run your
program with `-u` flag in order to remove buffering. More details in
[this](http://stackoverflow.com/a/3670470/723891) answer.

Second is that `numpy.asarray` probably not right way to get numpy array from
the data, `numpy.frombuffer` works for me very well.

So here is working code (only I used `cv2` instead of `cv` hope it wont matter
too much):

    
    
    import sys
    import cv2
    import numpy
    
    stdin = sys.stdin.read()
    array = numpy.frombuffer(stdin, dtype='uint8')
    img = cv2.imdecode(array, 1)
    cv2.imshow("window", img)
    cv2.waitKey()
    

Can be executed this way:

    
    
    python -u test.py < cat.jpeg
    

