通过套接字发送多维numpy数组

goqiplq2  于 2023-05-07  发布在  其他
关注(0)|答案(4)|浏览(137)

日安
我搜索过这个,但没有得到任何回应。我希望通过套接字发送一个多维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]

有没有办法把它转换成字符串,以某种方式,保存它的维数?

fnx2tebb

fnx2tebb1#

试试这个例子:

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

在这个模型中,客户端向服务器发送多维ndarray。有两个函数startServer()和startClient()。startServer不接受任何参数,但startClient需要服务器地址和ndarray作为参数。首先启动服务器,然后启动客户端。服务器仅在收到客户端发出的关机消息后才开始从缓冲区阅读。

hk8txs48

hk8txs482#

实际上,.tostring只返回原始数据。这意味着如果另一端不知道数组的形状和dtype,则还需要发送它们。
也许使用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]]

但对于非常小的阵列,大小开销可能很大:

print len(x.tostring()), len(dumps(x))
# 4 171

有关使用Pickle的更多信息,请访问see here.

q1qsirdb

q1qsirdb3#

这是一个使用XML-RPC的ajsp答案的临时答案。
在服务器端转换数据时,使用**'. tostring()'方法将numpy数据转换为字符串。这将numpy ndarray编码为bytes字符串。在客户端,当你接收到数据时,使用'. fromstring()'**方法对其进行解码。我为此写了两个简单的函数。希望这对你有帮助。

  1. ndarray 2str--将numpy ndarray转换为bytes字符串。
  2. str 2ndarray--将binary str转换回numpy ndarray。
def ndarray2str(a):
        # Convert the numpy array to string 
        a = a.tostring()

        return a

在接收端,数据作为**'xmlrpc.client. Binary'对象接收。您需要使用'.data**'访问数据。

def str2ndarray(a):
        # Specify your data type, mine is numpy float64 type, so I am specifying it as np.float64
        a = np.fromstring(a.data, dtype=np.float64)
        a = np.reshape(a, new_shape)

        return a

**注意:**这种方法的唯一问题是XML-RPC在发送大型numpy数组时非常慢。我花了大约4秒来发送和接收一个(10,500,500,3)大小的numpy数组。

我用的是Python 3.7.4。

9njqaruj

9njqaruj4#

我最近想做一件类似的事情,并试图自己做每件事,这占用了大量的时间和精力。事实证明,python中已经存在一个库,它可以为您做所有的事情(维护形状并抽象冗长的套接字代码)!
退房-https://pypi.org/project/mlsocket/

相关问题