java - gRPC——在 Protobuf 中将 .png 图像从 Java 客户端发送到 Python 服务器

标签 java python-2.7 protocol-buffers grpc

我正在尝试使用 gRPC 和 ProtoBuf 将图像从 Java 客户端发送到 Python 服务器。我将图像编码为 ByteString 并使用blockingStub 发送它。 Python 服务器接收 ProtoBuf,但 Java ByteString 现在是 Python str。我不知道如何从 str 恢复图像。

当我调用服务器时:

request.ParseFromString(request.png_encoded)  # Throws error

它引发:

Traceback (most recent call last):

File "/usr/local/lib/python2.7/dist-packages/grpc/_server.py", line 364, in _call_behavior

return behavior(argument, context), True

File "process_server.py", line 57, in Process request.ParseFromString(request.png_encoded)

File "/usr/local/lib/python2.7/dist-packages/google/protobuf/message.py", line 185, in ParseFromString self.MergeFromString(serialized)

File "/usr/local/lib/python2.7/dist-packages/google/protobuf/internal/python_message.py", line 1082, in MergeFromString if self._InternalParse(serialized, 0, length) != length:

File "/usr/local/lib/python2.7/dist-packages/google/protobuf/internal/python_message.py", line 1108, in InternalParse new_pos = local_SkipField(buffer, new_pos, end, tag_bytes)

File "/usr/local/lib/python2.7/dist-packages/google/protobuf/internal/decoder.py", line 850, in SkipField return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)

File "/usr/local/lib/python2.7/dist-packages/google/protobuf/internal/decoder.py", line 820, in _RaiseInvalidWireType

raise _DecodeError('Tag had invalid wire type.')

DecodeError: Tag had invalid wire type.

Java 客户端:

public void run_process(String imPath) {
    logger.info("Will try to retrieve boxes with image " + imPath + " ...");
    File path = new File(imPath);
    byte[] imageInByte = null;
    ByteString byteIm = null;
    try {
        BufferedImage bufferedIm = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bufferedIm = ImageIO.read(path);
        ImageIO.write(bufferedIm, "png", out);
        out.flush();
        imageInByte = out.toByteArray();
        out.close();
        ByteBuffer buf = ByteBuffer.wrap(imageInByte);
        byteIm = ByteString.copyFrom(buf);
    } catch (IOException e) {
        e.printStackTrace();
    }

    private final ManagedChannel channel;
    channel = ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext(true).build();
    private final ProcessServiceGrpc.ProcessServiceBlockingStub blockingStub;
    blockingStub = ProcessServiceGrpc.newBlockingStub(channel);

    ProcessRequest request = ProcessRequest.newBuilder().setPngEncoded(byteIm).build();
    ProcessResponse response;
    try {
        response = blockingStub.process(request);
    } catch (StatusRuntimeException e) {
        logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
        return;
    }
    logger.info("Boxes retrieved: " + response.toString());
}

Python 服务器:

def Process(self, request, context):
    print(type(request.png_encoded))  # prints <type 'str'>
    request.ParseFromString(request.png_encoded)  # Throws error

    # Return empty response for now
    process_response = inference_pb2.ProcessResponse()
    return process_response

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    inference_pb2.add_ProcessServiceServicer_to_server(
        ProcessServiceServicer(), server)
    print "Starting Process Server"
    server.add_insecure_port('localhost:50051')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()

我尝试用谷歌搜索“Decode Java Protobuf in Python”和“decode java protobuf Bytestring in python”,但没有成功。提前致谢!

最佳答案

Java 中的

ByteString 只是一个不可变的 byte[]。 Python 2 中的等效项是 str。它是一个二进制表示形式。如果您想将图像保存到磁盘,您可以:

with open('out.png', 'wb') as file:
    file.write(request.png_encoded)

关于java - gRPC——在 Protobuf 中将 .png 图像从 Java 客户端发送到 Python 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39238838/

相关文章:

java - Jacob - 检索系统恢复信息 (Java)

arrays - Numpy.count_nonzero 在 64 位 Windows 平台上崩溃

python - 匹配 HTML 中的特定表格,BeautifulSoup

go - Go 中的 grpc header /cookie

Golang 类型在指向一种类型 slice 的指针 slice 与另一种类型 slice 之间的类型转换

python - 没有名为 google.protobuf 的模块

java菜单程序切换大小写避免退出如果从菜单中选择了数字

java - Apache POI,改变文件 MIME 类型。有可能修复它吗?

java - 如何使用正则表达式通过类名构建 HTML DOM 元素的选择器

python - 使用计算 GCD - Python 函数返回