title: Video Streaming: Could not deserialize image after using pickle
body: <p>I'm trying to create a video streaming application, which has 3 components:</p>
  
  <ol>
  <li>An streaming application which streams via UDP the image received from camera </li>
  <li>The UDP server which reads for data, puts it in a local file</li>
  <li>HTTP Server, with a /cam.mjpg API, whose handler reads every 0.05 seconds from that pickle file, and transmits it (content type multipart)</li>
  </ol>
  
  <p>I'm getting the following error:</p>
  
  <pre><code>----------------------------------------
  Exception happened during processing of request from ('192.168.43.251', 54236)
  Traceback (most recent call last):
    File "/usr/lib/python3.4/socketserver.py", line 613, in process_request_thread
      self.finish_request(request, client_address)
    File "/usr/lib/python3.4/socketserver.py", line 344, in finish_request
      self.RequestHandlerClass(request, client_address, self)
    File "/usr/lib/python3.4/socketserver.py", line 669, in __init__
      self.handle()
    File "/usr/lib/python3.4/http/server.py", line 398, in handle
      self.handle_one_request()
    File "/usr/lib/python3.4/http/server.py", line 386, in handle_one_request
      method()
    File "streaming_video_server2.py", line 25, in do_GET
      img = cv2.imdecode(img, x)
  TypeError: only size-1 arrays can be converted to Python scalars
  ----------------------------------------
  </code></pre>
  
  <p>Here are my files, one by one (1, 2, 3)</p>
  
  <pre><code>#!/usr/bin/python
  import cv2
  from PIL import Image
  import time
  import datetime
  import numpy as np
  import socket
  import sys
  import _pickle as cPickle
  import struct
  
  
  def StartStreamSending():
      UDP_IP = "127.0.0.1"
      UDP_PORT = 8012
      capture=cv2.VideoCapture(0)
      capture.set(cv2.CAP_PROP_FRAME_WIDTH, 320);
      capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 240);
      clientsocket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
      fourcc = cv2.VideoWriter_fourcc(*'MPEG')
      out = cv2.VideoWriter('output.avi',fourcc, 20.0, (320,240))
  
  
      while True:
          ret,img=capture.read()
          timestamp = datetime.datetime.now()
          ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p")
          cv2.putText(img, ts, (10, img.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
          #Store the frame into the output file
          out.write(img)
          #Some processing before sending the frame to webserver
          imgRGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
          jpg = Image.fromarray(imgRGB)
          size = sys.getsizeof(imgRGB)
          print(size)
  
          result, img_str = cv2.imencode('.jpeg', img)
          #data = np.array(img_str)
          data = img_str
  
          dataToSend = cPickle.dumps(data)
          size = sys.getsizeof(dataToSend)
          print(size)
          print(type(dataToSend));
  
          clientsocket.sendto(dataToSend, (UDP_IP, UDP_PORT))
  
  StartStreamSending()
  </code></pre>
  
  <p>File 2 : The UDP server which reads for data, puts it in a local file</p>
  
  <pre><code>import socket
  import sys
  import cv2
  import _pickle as cPickle
  import numpy as np
  import struct
  
  HOST='localhost'
  PORT=8012
  
  def WaitAndReceiveVideoStream(_strHOST, _iPORT):
      s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
      print('Socket created')
  
      s.bind((_strHOST,_iPORT))
      print('Socket bind complete')
  
  
  
      data = ""
      #payload_size = struct.calcsize("L")
  
      i = 0
      while True:
          data, addr = s.recvfrom(66512)
          print(data)
          frame=cPickle.loads(data)
          i = i + 1
          print('coming frame' + str(i))
  
          with open('cam0.pickle', 'wb') as handle:
              cPickle.dump(frame, handle)
  
  WaitAndReceiveVideoStream(HOST, PORT)
  </code></pre>
  
  <p>And the HTTP Server (File 3):</p>
  
  <pre><code>#!/usr/bin/python
  import cv2
  from PIL import Image
  import numpy as np
  import threading
  from http.server import BaseHTTPRequestHandler,HTTPServer
  import _pickle as cPickle
  from socketserver import ThreadingMixIn
  from io import StringIO,BytesIO
  import time
  import datetime
  
  class CamHandler(BaseHTTPRequestHandler):
      def do_GET(self):
          if self.path.endswith('.mjpg'):
              self.send_response(200)
              self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')
              self.end_headers()
              while True:
                  try:
                      with open('cam0.pickle', 'rb') as handle:
                          img = cPickle.load(handle)
                          #use numpy to construct an array from the bytes
                          x = np.fromstring(img, dtype='uint8')
                          img = cv2.imdecode(img, x)
                      #Some processing before sending the frame to webserver
                      ##imgRGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                      ##jpg = Image.fromarray(imgRGB)
                      jpg = Image.fromarray(img)
                      tmpFile = BytesIO()
                      jpg.save(tmpFile,'JPEG')
                      self.wfile.write("--jpgboundary".encode())
                      self.send_header('Content-type','image/jpeg')
                      self.send_header('Content-length',str(tmpFile.getbuffer().nbytes))
                      print(str(tmpFile.getbuffer().nbytes))
                      self.end_headers()
                      jpg.save(self.wfile,'JPEG')
                      time.sleep(0.05)
                      print("Still inside mjpg")
                  except KeyboardInterrupt:
                      break
                  except ConnectionResetError:
                      break
              return
          if self.path.endswith('.html'):
              self.send_response(200)
              self.send_header('Content-type','text/html')
              self.end_headers()
              self.wfile.write('&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;'.encode())
              self.wfile.write('&lt;img src="http://127.0.0.1:8080/cam.mjpg"/&gt;'.encode())
              self.wfile.write('&lt;/body&gt;&lt;/html&gt;'.encode())
              return
  
  
  class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
      """Handle requests in a separate thread."""
  
  def main():
      try:
          server = ThreadedHTTPServer(('0.0.0.0', 8080), CamHandler)
          print( "server started")
          server.serve_forever()
      except KeyboardInterrupt:
          server.socket.close()
  
  if __name__ == '__main__':
      main()
  </code></pre>
  
  <p>I believe the data I'm sending could be sent as a numpy array, not too sure, please suggest.</p>