1

Im working on an Application were I get an image in Opencv Mat format from a Webcam in a Java Client and have to process this image on a python server.

Therefore I`m sending a bytearray to the python server. I´m encoding the Image in Java like this:

private VideoCapture capture = new VideoCapture();

...

this.capture.read(frame);
    if (!frame.empty()) {
      byte[] return_buff = new byte[(int) (frame.total() *
                frame.channels())];
      frame.get(0, 0, return_buff);
...

After that I send it through a Socket using a DataOutputStream. When I echo it back to the Java Client the bytedata seems to have been transferred correctly and entirely. In Python I then tried to decode it with PIL

img = Image.open(BytesIO(data))

And yes I already import PIL like suggested here: PIL: Convert Bytearray to Image

But Im still getting this Error:

img = Image.open(BytesIO(data))
File "/root/.local/lib/python2.7/site-packages/PIL/Image.py", line 2590, in 
open % (filename if filename else fp))
IOError: cannot identify image file

Do I have to change the way I assembled my bytearra or do I have to encode it in a different way?

Hellcaraxe
  • 65
  • 1
  • 1
  • 5

1 Answers1

0

Solved it! The thing is that Image.open(BytesIO(data)) apparently expects the data to have some kind of header to describe the image type and was therefore unfitting for a mat converted to bytes because a Mat appears to have no kind of header integrated, just the plain image data. In python an Image from a Mat bytearray can be derived using the following:

img = cv2.imdecode(bytearray, flag)

with flag being a number representing the cvtype of the image.

Hellcaraxe
  • 65
  • 1
  • 1
  • 5