I use python3 with numpy, scipy and opencv.
I'm trying to convert a image read through OpenCV and connected camera interface into a binary string, to send it within a json object through some network connection.
I have tried enconding the array as jpg and the decode the UTF-16 string, but I get no usable results. as example, with
img = get_image()
converted = cv2.imencode('.jpg', img)[1].tostring()
print(converted)
I get a byte-string as result:
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x02\x01\x01\x01\x01\x01\x02\x01....
But this data cannot be used as content of a json object, because it contains invalid characters. Is there a way I can display the real bytes behind this string? I believe that \xff represents byte value FF, so I need as String like FFD8FFE0... and so on, instead of \xff\xd8\xff\xe0. What am I doing wrong?
I tried to encode it as UTF-8 and UTF16 after the code above, but I get several errors on that:
utf_string = converted.decode('utf-16-le')
UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 0-1: illegal UTF-16 surrogate
text = strrrrrr.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
I can't figure out a way to get this right.
I also tried to convert it into a base64 encoded string, like explained in http://www.programcreek.com/2013/09/convert-image-to-string-in-python/ But that doesn't work either. ( This solution is not preferred, as it requires the image being written temporarly to disk, which is not exactly what I need. Preferrably the image should only be hold in memory, never on disk.)
The solution should contain a way to encode the image as json-conform string and also a way to decode it back to numpy-array, so it can be used again with cv2.imshow().
Thanks for any help.