在C中序列化原始图像缓冲区(rgb像素)并在Python中反序列化

时间:2017-01-06 20:28:57

标签: python c serialization zeromq msgpack

我想序列化原始图像数据,即uint16数组,并使用zmq将其发送到python。我被认为使用了msgPack-c,但我发现的唯一方法就是给定How do I unpack and extract data properly using msgpack-c?

如果我遵循这种方法,我必须分别在C数组中打包每个元素,这将使它非常慢。

请有人指出正确的方向。

1 个答案:

答案 0 :(得分:1)

您可以按原样从c侧发送uint16_t数组,并使用ctypes模块以python代码访问它。

发送c代码:

#include <stdint.h>
#include <stdio.h>
#include <zmq.h>

#define IMAGE_SIZE (256 * 256)

unsigned checksum(uint16_t* data, int len) {
    unsigned s = 0;
    for (int i = 0; i < len; ++i) {
        s += data[i];
    }
    return s;
}

int main() {
    uint16_t image[IMAGE_SIZE];
    printf("image checksum: %i\n", checksum(image, IMAGE_SIZE));

    void* context = zmq_ctx_new();
    void* push = zmq_socket(context, ZMQ_PUSH);
    zmq_connect(push, "tcp://127.0.0.1:5555");
    zmq_send(push, image, IMAGE_SIZE * sizeof(uint16_t), 0);
    zmq_close(push);
    zmq_ctx_destroy(context);
    return 0;
}

接收python代码:

from ctypes import c_uint16
import zmq

IMAGE_SIZE = 256 * 256
Image = c_uint16 * IMAGE_SIZE # corresponds to uint16_t[IMAGE_SIZE]

context = zmq.Context(1)
pull = zmq.Socket(context, zmq.PULL)
pull.bind("tcp://127.0.0.1:5555")
message = pull.recv()

image = Image.from_buffer_copy(message)

# This should print the same number as the sending code
# Note that it is different from sum(message)
print(sum(image))