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

Community
  • 1
  • 1
undur_gongor
  • 15,657
  • 5
  • 63
  • 75

2 Answers2

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
Community
  • 1
  • 1
Igonato
  • 10,175
  • 3
  • 35
  • 64
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()
Felipe Cunha
  • 166
  • 1
  • 5