How can I read image data from stdin rather than from a file?
With the C++ interface, it seems to be possible: https://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
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 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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With