title: Python OpenCV Image to byte string for json transfer
body: <p>I use <strong>python3</strong> with <strong>numpy, scipy and opencv</strong>. </p>
  
  <p>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.</p>
  
  <p>I have tried enconding the array as jpg and the decode the UTF-16 string, but I get no usable results. as example, with</p>
  
  <pre><code>img = get_image()
  converted = cv2.imencode('.jpg', img)[1].tostring()
  print(converted)
  </code></pre>
  
  <p>I get a byte-string as result:</p>
  
  <blockquote>
    <p>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....</p>
  </blockquote>
  
  <p>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?</p>
  
  <p>I tried to encode it as UTF-8 and UTF16 after the code above, but I get several errors on that:</p>
  
  <pre><code>utf_string = converted.decode('utf-16-le')
  </code></pre>
  
  <blockquote>
    <p>UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 0-1: illegal UTF-16 surrogate</p>
  </blockquote>
  
  <pre><code>text = strrrrrr.decode('utf-8')
  </code></pre>
  
  <blockquote>
    <p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte</p>
  </blockquote>
  
  <p>I can't figure out a way to get this right.</p>
  
  <p>I also tried to convert it into a base64 encoded string, like explained in 
  <a href="http://www.programcreek.com/2013/09/convert-image-to-string-in-python/" rel="noreferrer">http://www.programcreek.com/2013/09/convert-image-to-string-in-python/</a>
  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.)</p>
  
  <p>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().</p>
  
  <p>Thanks for any help.</p>