我需要将图像(numpy数组)、有关图像的附加元信息(如高度、宽度等)从 pythongrpc客户端传递到 pythongrpc服务器。
我需要运行这个方法。
import numpy as np
def predict(img, w, h):
# some operations
return img.shape[2], np.mean(img)
Run Code Online (Sandbox Code Playgroud)
我查看了文档,但 protobuf 中没有兼容的numpy数组数据类型。
https://developers.google.com/protocol-buffers/docs/proto3
image_procedure.proto
syntax = "proto3";
// input image, width, height
message Image {
image_type image = 1;
int32 width = 2;
int32 height = 3;
}
// output prediction
message Prediction {
int32 channel = 4;
float mean = 5;
}
// service
service ImageProcedure {
rpc ImageMeanWH(Image) returns (Prediction) {}
}
Run Code Online (Sandbox Code Playgroud)
如何将图像和其他相关数据发送到服务器并获得响应?
您始终可以将 numpy 数组编码为 base64 字符串并将其传递到服务器。
你的.proto文件应该看起来像这样:
syntax = "proto3";
// input image, width, height
message B64Image {
string b64image = 1;
int32 width = 2;
int32 height = 3;
}
// output prediction
message Prediction {
int32 channel = 4;
float mean = 5;
}
// service
service ImageProcedure {
rpc ImageMeanWH(B64Image) returns (Prediction) {}
}
Run Code Online (Sandbox Code Playgroud)
一旦你编译你的.proto文件
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. image_procedure.proto
将为.py您生成两个文件:
image_procedure_pb2.py
image_procedure_pb2_grpc.py
在客户端代码中,通过对图像进行编码来生成请求消息base64。
frame = np.random.randint(0,255, (416,416,3), dtype=np.uint8) # dummy rgb image
data = base64.b64encode(frame)
# create a valid request message
image_req = image_procedure_pb2.B64Image(b64image = data, width = 416, height = 416)
Run Code Online (Sandbox Code Playgroud)
在您的过程中,只需解码 Base64 并运行您想要的任何操作。
import numpy as np
import base64
def predict(b64img, w, h):
b64decoded = base64.b64decode(b64img)
imgarr = np.frombuffer(b64decoded, dtype=np.uint8).reshape(w, h, -1)
return imgarr.shape[2], np.mean(imgarr)
Run Code Online (Sandbox Code Playgroud)
我将代码扩展为教程,您可以在这里查看: https: //github.com/zabir-nabil/simple-gRPC