Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-opencv: Read image data from stdin

Tags:

python

opencv

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

like image 565
undur_gongor Avatar asked Mar 14 '13 16:03

undur_gongor


1 Answers

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
like image 52
Igonato Avatar answered Sep 21 '22 17:09

Igonato