在套接字上发送多维numpy数组

ovf*_*ack 11 python arrays numpy multidimensional-array

美好的一天,

我已经搜索过这个但没有提出任何回复.我希望在套接字上发送一个多维的numpy数组.因此,我决定将其转换为字符串:

但是,它会破坏数组的表示形式:

>>> import numpy as np
>>> x = np.array([[0, 1], [2, 3]])
>>> xstring = x.tostring()
>>> print xstring

>>> print x
[[0 1]
 [2 3]]
>>> print xstring

>>> nparr = np.fromstring(xstring, dtype=np.uint8)
>>> print nparr
[0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0]
Run Code Online (Sandbox Code Playgroud)

无论如何,我可以以某种方式转换为字符串,保存它的维度?

Ras*_* Mv 8

试试这个例子: -

import socket
import numpy as np
from cStringIO import StringIO

class numpysocket():
    def __init__(self):
        pass

    @staticmethod
    def startServer():
        port=7555
        server_socket=socket.socket() 
        server_socket.bind(('',port))
        server_socket.listen(1)
        print 'waiting for a connection...'
        client_connection,client_address=server_socket.accept()
        print 'connected to ',client_address[0]
        ultimate_buffer=''
        while True:
            receiving_buffer = client_connection.recv(1024)
            if not receiving_buffer: break
            ultimate_buffer+= receiving_buffer
            print '-',
        final_image=np.load(StringIO(ultimate_buffer))['frame']
        client_connection.close()
        server_socket.close()
        print '\nframe received'
        return final_image

    @staticmethod
    def startClient(server_address,image):
        if not isinstance(image,np.ndarray):
            print 'not a valid numpy image'
            return
        client_socket=socket.socket()
        port=7555
        try:
            client_socket.connect((server_address, port))
            print 'Connected to %s on port %s' % (server_address, port)
        except socket.error,e:
            print 'Connection to %s on port %s failed: %s' % (server_address, port, e)
            return
        f = StringIO()
        np.savez_compressed(f,frame=image)
        f.seek(0)
        out = f.read()
        client_socket.sendall(out)
        client_socket.shutdown(1)
        client_socket.close()
        print 'image sent'
        pass
Run Code Online (Sandbox Code Playgroud)

在此模型中,客户端将多维ndarray发送到服务器.startServer()和startClient()有两个函数.startServer不带参数,但startClient需要服务器地址以及ndarray作为参数.首先启动Server,然后启动客户端.服务器仅在收到客户端的关闭消息后才开始从缓冲区读取.


小智 4

事实上,.tostring只返回原始数据。这意味着如果对方不知道数组的形状和数据类型,您还需要发送这些信息。

也许使用 Pickle 序列化数组更容易:

import numpy as np
from cPickle import dumps, loads

x = np.array([[1, 2],[3, 4]], np.uint8)
print loads(dumps(x))
# [[1 2]
#  [3 4]]
Run Code Online (Sandbox Code Playgroud)

尽管对于非常小的数组,大小开销可能会很大:

print len(x.tostring()), len(dumps(x))
# 4 171
Run Code Online (Sandbox Code Playgroud)

有关使用 Pickle 的更多信息,请参阅此处。