Python error sending image over socket with pickleCommon use-cases for pickle in PythonPyAudio Over Network crashesPython multiprocessing PicklingError: Can't pickle <type 'function'>Pickle incompatibility of numpy arrays between Python 2 and 3Repeated transient-socket connections - memory leak risk?Server response on socket being truncated at 2KCan't pickle an RSA key to send over a socketPython 3 sockets app stops sending dataclient-server python and file opening errorP5js and Python communication via socket

Why do money exchangers give different rates to different bills?

How to change lightning-radio-group selected value programmatically?

Getting a W on your transcript for grad school applications

Do Maps have an Reliable Relationship between keySet() order and values() order?

Out of scope work duties and resignation

Why is "Vayechulu" said 3 times on Leil Shabbat?

How to model the curly cable part of the phone

Is latino sine flexione dead?

Can there be a single technologically advanced nation, in a continent full of non-technologically advanced nations?

Verb "geeitet" in an old scientific text

Why was the battle set up *outside* Winterfell?

I'm in your subnets, golfing your code

Can hackers enable the camera after the user disabled it?

What was the design of the Macintosh II's MMU replacement?

how to ban all connection to .se and .ru in the hosts.deny-file

How important is people skills in academic career and applications?

Why is the relative clause in the following sentence not directly after the noun and why is the verb not in the end of the sentence?

Expressing 'our' for objects belonging to our apartment

Why is Arya visibly scared in the library in S8E3?

String won't reverse using reverse_copy

Multi-channel audio upsampling interpolation

If your medical expenses exceed your income does the IRS pay you?

Lie super algebra presentation of the Kähler identities

As matter approaches a black hole, does it speed up?



Python error sending image over socket with pickle


Common use-cases for pickle in PythonPyAudio Over Network crashesPython multiprocessing PicklingError: Can't pickle <type 'function'>Pickle incompatibility of numpy arrays between Python 2 and 3Repeated transient-socket connections - memory leak risk?Server response on socket being truncated at 2KCan't pickle an RSA key to send over a socketPython 3 sockets app stops sending dataclient-server python and file opening errorP5js and Python communication via socket






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I am creating a program that sends a video stream over a socket, and I am using pickle to load/dump my image numpy array. I am sending pictures fast so I can receive frames fast and make a live video from it. When I try this, I get the error _pickle.UnpicklingError: invalid load key, '<'.



I've tried to constantly load the array in pickle (pickle.loads) and use cv2 to open the frame, but after a few frames it gives the error _pickle.UnpicklingError: invalid load key, '<'.



Server.py (The main focus is send_commands())



import os
import time
import socket
import sys
import threading
import cv2
import numpy as np
import pickle

loggedin = 1

all_addresses = []
all_connections = []
def socket_create():
if loggedin == 0:
return


try:
global host
global port
global s
host = ''
port = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as e:
print("Socket error > " + str(e))
return


def socket_bind():
try:
global host
global port
global s
host = ''
print("Socket binding - Port > " + str(port))
print(host + str(port))
s.bind((host, int(port)))
s.listen(1)
except socket.error as e:
print("Socket binding - Error > " + str(e))
time.sleep(3)
socket_bind()
def accept_connections():
for c in all_connections:
c.close()
del all_connections[:]
del all_addresses[:]
while True:
try:
conn, address = s.accept()
conn.setblocking(1)
all_connections.append(conn)
all_addresses.append(address)
print("nC - IP > " + str(address[0]))
except socket.error as e:
print("Error: " + str(e))
time.sleep(3)
time.sleep(1)
def send_commands():
print("send")
time.sleep(2)
conn = all_connections[0]
conn.send(str.encode("#Video"))

while True:
p = conn.recv(40960000)
data_arr = pickle.loads(p, fix_imports=True, encoding="bytes")
frame = cv2.cvtColor(data_arr, cv2.COLOR_RGB2BGR)
cv2.imshow("frame", frame)
print("go")
cv2.waitKey(10)

def go():
socket_create()
socket_bind()
a = threading.Thread(name='background', target=accept_connections)
a.start()
send_commands()

go()


Client.py (Main focus is img())



import threading
import time
import os
import sys
import socket
import pyscreenshot
import pickle
import numpy as np
from PIL import ImageGrab

host = "192.168.1.27"
port = 9999





def go():
global s
while True:

try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, int(port)))
while True:
data = s.recv(40960000)
if data.decode("utf-8") != "#Video":
return
while True:
img()
print("img")

except:
print("Error")
time.sleep(2)

def img():
img = ImageGrab.grab()
img_np = np.array(img)
data_string = pickle.dumps(img_np)
s.sendall(data_string)


if __name__ == '__main__':
go()









share|improve this question




























    1















    I am creating a program that sends a video stream over a socket, and I am using pickle to load/dump my image numpy array. I am sending pictures fast so I can receive frames fast and make a live video from it. When I try this, I get the error _pickle.UnpicklingError: invalid load key, '<'.



    I've tried to constantly load the array in pickle (pickle.loads) and use cv2 to open the frame, but after a few frames it gives the error _pickle.UnpicklingError: invalid load key, '<'.



    Server.py (The main focus is send_commands())



    import os
    import time
    import socket
    import sys
    import threading
    import cv2
    import numpy as np
    import pickle

    loggedin = 1

    all_addresses = []
    all_connections = []
    def socket_create():
    if loggedin == 0:
    return


    try:
    global host
    global port
    global s
    host = ''
    port = 9999
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error as e:
    print("Socket error > " + str(e))
    return


    def socket_bind():
    try:
    global host
    global port
    global s
    host = ''
    print("Socket binding - Port > " + str(port))
    print(host + str(port))
    s.bind((host, int(port)))
    s.listen(1)
    except socket.error as e:
    print("Socket binding - Error > " + str(e))
    time.sleep(3)
    socket_bind()
    def accept_connections():
    for c in all_connections:
    c.close()
    del all_connections[:]
    del all_addresses[:]
    while True:
    try:
    conn, address = s.accept()
    conn.setblocking(1)
    all_connections.append(conn)
    all_addresses.append(address)
    print("nC - IP > " + str(address[0]))
    except socket.error as e:
    print("Error: " + str(e))
    time.sleep(3)
    time.sleep(1)
    def send_commands():
    print("send")
    time.sleep(2)
    conn = all_connections[0]
    conn.send(str.encode("#Video"))

    while True:
    p = conn.recv(40960000)
    data_arr = pickle.loads(p, fix_imports=True, encoding="bytes")
    frame = cv2.cvtColor(data_arr, cv2.COLOR_RGB2BGR)
    cv2.imshow("frame", frame)
    print("go")
    cv2.waitKey(10)

    def go():
    socket_create()
    socket_bind()
    a = threading.Thread(name='background', target=accept_connections)
    a.start()
    send_commands()

    go()


    Client.py (Main focus is img())



    import threading
    import time
    import os
    import sys
    import socket
    import pyscreenshot
    import pickle
    import numpy as np
    from PIL import ImageGrab

    host = "192.168.1.27"
    port = 9999





    def go():
    global s
    while True:

    try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, int(port)))
    while True:
    data = s.recv(40960000)
    if data.decode("utf-8") != "#Video":
    return
    while True:
    img()
    print("img")

    except:
    print("Error")
    time.sleep(2)

    def img():
    img = ImageGrab.grab()
    img_np = np.array(img)
    data_string = pickle.dumps(img_np)
    s.sendall(data_string)


    if __name__ == '__main__':
    go()









    share|improve this question
























      1












      1








      1








      I am creating a program that sends a video stream over a socket, and I am using pickle to load/dump my image numpy array. I am sending pictures fast so I can receive frames fast and make a live video from it. When I try this, I get the error _pickle.UnpicklingError: invalid load key, '<'.



      I've tried to constantly load the array in pickle (pickle.loads) and use cv2 to open the frame, but after a few frames it gives the error _pickle.UnpicklingError: invalid load key, '<'.



      Server.py (The main focus is send_commands())



      import os
      import time
      import socket
      import sys
      import threading
      import cv2
      import numpy as np
      import pickle

      loggedin = 1

      all_addresses = []
      all_connections = []
      def socket_create():
      if loggedin == 0:
      return


      try:
      global host
      global port
      global s
      host = ''
      port = 9999
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      except socket.error as e:
      print("Socket error > " + str(e))
      return


      def socket_bind():
      try:
      global host
      global port
      global s
      host = ''
      print("Socket binding - Port > " + str(port))
      print(host + str(port))
      s.bind((host, int(port)))
      s.listen(1)
      except socket.error as e:
      print("Socket binding - Error > " + str(e))
      time.sleep(3)
      socket_bind()
      def accept_connections():
      for c in all_connections:
      c.close()
      del all_connections[:]
      del all_addresses[:]
      while True:
      try:
      conn, address = s.accept()
      conn.setblocking(1)
      all_connections.append(conn)
      all_addresses.append(address)
      print("nC - IP > " + str(address[0]))
      except socket.error as e:
      print("Error: " + str(e))
      time.sleep(3)
      time.sleep(1)
      def send_commands():
      print("send")
      time.sleep(2)
      conn = all_connections[0]
      conn.send(str.encode("#Video"))

      while True:
      p = conn.recv(40960000)
      data_arr = pickle.loads(p, fix_imports=True, encoding="bytes")
      frame = cv2.cvtColor(data_arr, cv2.COLOR_RGB2BGR)
      cv2.imshow("frame", frame)
      print("go")
      cv2.waitKey(10)

      def go():
      socket_create()
      socket_bind()
      a = threading.Thread(name='background', target=accept_connections)
      a.start()
      send_commands()

      go()


      Client.py (Main focus is img())



      import threading
      import time
      import os
      import sys
      import socket
      import pyscreenshot
      import pickle
      import numpy as np
      from PIL import ImageGrab

      host = "192.168.1.27"
      port = 9999





      def go():
      global s
      while True:

      try:
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      s.connect((host, int(port)))
      while True:
      data = s.recv(40960000)
      if data.decode("utf-8") != "#Video":
      return
      while True:
      img()
      print("img")

      except:
      print("Error")
      time.sleep(2)

      def img():
      img = ImageGrab.grab()
      img_np = np.array(img)
      data_string = pickle.dumps(img_np)
      s.sendall(data_string)


      if __name__ == '__main__':
      go()









      share|improve this question














      I am creating a program that sends a video stream over a socket, and I am using pickle to load/dump my image numpy array. I am sending pictures fast so I can receive frames fast and make a live video from it. When I try this, I get the error _pickle.UnpicklingError: invalid load key, '<'.



      I've tried to constantly load the array in pickle (pickle.loads) and use cv2 to open the frame, but after a few frames it gives the error _pickle.UnpicklingError: invalid load key, '<'.



      Server.py (The main focus is send_commands())



      import os
      import time
      import socket
      import sys
      import threading
      import cv2
      import numpy as np
      import pickle

      loggedin = 1

      all_addresses = []
      all_connections = []
      def socket_create():
      if loggedin == 0:
      return


      try:
      global host
      global port
      global s
      host = ''
      port = 9999
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      except socket.error as e:
      print("Socket error > " + str(e))
      return


      def socket_bind():
      try:
      global host
      global port
      global s
      host = ''
      print("Socket binding - Port > " + str(port))
      print(host + str(port))
      s.bind((host, int(port)))
      s.listen(1)
      except socket.error as e:
      print("Socket binding - Error > " + str(e))
      time.sleep(3)
      socket_bind()
      def accept_connections():
      for c in all_connections:
      c.close()
      del all_connections[:]
      del all_addresses[:]
      while True:
      try:
      conn, address = s.accept()
      conn.setblocking(1)
      all_connections.append(conn)
      all_addresses.append(address)
      print("nC - IP > " + str(address[0]))
      except socket.error as e:
      print("Error: " + str(e))
      time.sleep(3)
      time.sleep(1)
      def send_commands():
      print("send")
      time.sleep(2)
      conn = all_connections[0]
      conn.send(str.encode("#Video"))

      while True:
      p = conn.recv(40960000)
      data_arr = pickle.loads(p, fix_imports=True, encoding="bytes")
      frame = cv2.cvtColor(data_arr, cv2.COLOR_RGB2BGR)
      cv2.imshow("frame", frame)
      print("go")
      cv2.waitKey(10)

      def go():
      socket_create()
      socket_bind()
      a = threading.Thread(name='background', target=accept_connections)
      a.start()
      send_commands()

      go()


      Client.py (Main focus is img())



      import threading
      import time
      import os
      import sys
      import socket
      import pyscreenshot
      import pickle
      import numpy as np
      from PIL import ImageGrab

      host = "192.168.1.27"
      port = 9999





      def go():
      global s
      while True:

      try:
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      s.connect((host, int(port)))
      while True:
      data = s.recv(40960000)
      if data.decode("utf-8") != "#Video":
      return
      while True:
      img()
      print("img")

      except:
      print("Error")
      time.sleep(2)

      def img():
      img = ImageGrab.grab()
      img_np = np.array(img)
      data_string = pickle.dumps(img_np)
      s.sendall(data_string)


      if __name__ == '__main__':
      go()






      python-3.x sockets pickle python-sockets






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 22 at 22:08









      yakoyako

      11418




      11418






















          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55308414%2fpython-error-sending-image-over-socket-with-pickle%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid …


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55308414%2fpython-error-sending-image-over-socket-with-pickle%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

          Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?