6

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

2
  • How an image represented in stdin? Commented Mar 14, 2013 at 16:43
  • @Igonato: as JPEG data, e.g. my_program < example.jpeg. Actually, I'm getting the data from a webcam with another program and I want to avoid creating temporary files. Commented Mar 14, 2013 at 16:59

2 Answers 2

12

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

2 Comments

Thank you. I did not encounter issues with stdin buffering. It is working without -u.
I've been trying to figure this out for a long time. Thanks for posting this. Didn't know of the frombuffer function.
2

I've tried the above solution but could not make it work. Replacing sys.stdin.read() by sys.stdin.buffer.read() did the job:

import numpy as np
import sys
import cv2

data = sys.stdin.buffer.read()
image = np.frombuffer(data, dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
cv2.imshow('stdin Image',image)
cv2.waitKey()

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.