我试图使用ndarray传递一个包含3个图像的python字典(存储为ZeroMQ ),将其作为使用者传递给另一个程序,并将数据解析为原始表单。遵循三种方式,但在任何一种方式下都无法取得成功。
下面是示例最小复制代码:
import pickle
import zmq
# Adding ZMQ Context
def zmq_context():
# Creating ZMQ context starts
context = zmq.Context()
footage_socket = context.socket(zmq.PUB)
footage_socket.connect('tcp://localhost:5002')
return footage_socket
wagon_dtl, ctr1_dtl, ctr2_dtl = NdArrays of images
socket_ctx = zmq_context()
# Trying two different ways of formatting the image before creating the dict, the below approach works for all three ndarrays
# 1st way
wagon_dtl = image_np_save # image_np_save is the original image
# 2nd way (this I tried because an ndarray isn't JSON serializable)
encoded, buffer = cv2.imencode('.jpg', image_np_save)
wagon_dtl = base64.b64encode(buffer)
if cond == "fulfilled":
full_wgn_dict = {"wagon_dtl": wagon_dtl, "ctr1_dtl": ctr1_dtl, "ctr2_dtl": ctr2_dtl}
# 1st way
dict_as_b64text = base64.b64encode(full_wgn_dict)
socket_ctx.send(dict_as_b64text)
# 2nd way
myjson = json.dumps(full_wgn_dict)
socket_ctx.send(myjson)
# 3rd way
dict_as_text = pickle.dumps(full_wgn_dict).encode('base64', 'strict')
socket_ctx.send(dict_as_text)如何解决这个问题?
发布于 2020-10-13 19:35:46
Q:“如何使用ZeroMQ
PUB/SUB__发送由ndarray和None组成的None字典?”
很简单,你最好用现成的.send_pyobj()-method来做好这件事。
派遣方,
PUB将调用socket.send_pyobj( full_wgn_dict )-method,这基本上是在这边。
一个接收方,
每个潜在的SUB-s都应该重用.recv_pyobj()-method。
然而,所有的SUB-s也必须再做一个步骤,主动订阅来接收任何消息。
有关socket.setsockopt( zmq.SUBSCRIBE, "" )的详细信息,请参阅ZeroMQ文档中的API,或毫不犹豫地从许多示例here中啜饮。
一些额外的技巧(对于琐碎的dict-s不需要)可能有助于SER/DES阶段的pickle-phase。然而,这些都超出了这个问题的范围,可能会在受控环境中带来优势,但在开放、不受控制的环境中却会带来问题,在开放、不受控制的环境中,您没有机会满足所需的先决条件--在我的应用程序中,我更喜欢使用import dill as pickle来增强对象的pickle.dumps()-SER/DES处理的健壮性,以及更多的进步,比如存储完整会话快照。学分:@MikeMcKearns
请随意阅读__doc__字符串中所有与语法相关的详细信息的文档:
>>> print zmq.Socket.send_pyobj.__doc__
Send a Python object as a message using pickle to serialize.
Parameters
----------
obj : Python object
The Python object to send.
flags : int
Any valid flags for :func:`Socket.send`.
protocol : int
The pickle protocol number to use. The default is pickle.DEFAULT_PROTOCOL
where defined, and pickle.HIGHEST_PROTOCOL elsewhere.
>>> print zmq.Socket.recv_pyobj.__doc__
Receive a Python object as a message using pickle to serialize.
Parameters
----------
flags : int
Any valid flags for :func:`Socket.recv`.
Returns
-------
obj : Python object
The Python object that arrives as a message.
Raises
------
ZMQError
for any of the reasons :func:`~Socket.recv` might failhttps://stackoverflow.com/questions/64336031
复制相似问题