Python-opencv: reading image data from stdin

How can I read image data from stdin and not from a file?

With the C ++ interface, this seems to be possible: https://stackoverflow.com/a/464829/ The imdecode function is also available in Python. But it expects a numpy array as the (first) argument. I do not know how to convert 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

+4
source share
1 answer

It looks like the python stdin buffer is too small for images. You can run your program using the -u flag to remove buffering. See more in this answer.

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

So, here is the working code (only I used cv2 instead of cv hope this is not too important):

 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() 

It can be performed as follows:

 python -u test.py < cat.jpeg 
+8
source

Source: https://habr.com/ru/post/1469286/


All Articles