原文链接: https://blog.csdn.net/hyman_yx/article/details/51732656
https://blog.csdn.net/ZhikangFu/article/details/53260329
使用Caffe的C++接口进行操作时,需要的图像均值文件是pb格式,例如常见的均值文件名为mean.binaryproto;但在使用python接口进行操作时,需要的图像均值文件是numpy格式,例如mean.npy。
所以在跨语言进行操作时,需要将mean.binaryproto转换成mean.npy,转换代码如下:
# -*- coding:UTF-8 -*-
import caffe
import numpy as np
mean_path = 'mean.binaryproto' # 待转换的pb格式图像均值文件路径
mean_np_path = 'mean.npy' # 转换后的numpy格式图像均值文件路径
blob = caffe.proto.caffe_pb2.BlobProto() # 创建protobuf blob
data = open(mean_path, 'rb' ).read() # 读入mean.binaryproto文件内容
blob.ParseFromString(data) # 解析文件内容到blob
array = np.array(caffe.io.blobproto_to_array(blob))# 将blob中的均值转换成numpy格式,array的shape (mean_number,channel, hight, width)
mean_npy = array[0] # 一个array中可以有多组均值存在,故需要通过下标选择其中一组均值
np.save(mean_np_path ,mean_npy)
mean = mean_npy.mean(1).mean(1)
print(mean)
已知图像均值,构造mean.npy
如果已知图像中每个通道的均值,例如3通道图像每个通道的均值分别为104,117,123,我们也可以通过其构造mean.npy。代码如下:
import numpy as np
MEAN_NPY_PATH = 'mean.npy'
mean = np.ones([3,256, 256], dtype=np.float)
mean[0,:,:] = 104
mean[1,:,:] = 117
mean[2,:,:] = 123
np.save(MEAN_NPY, mean)
载入mean.npy
上面我们用两种方式构造了均值文件mean.npy,在使用时载入mean.npy的代码如下:
import numpy as np
mean_npy = np.load(MEAN_NPY_PATH)
mean = mean_npy.mean(1).mean(1)
mean.npy转mean.binaryproto
均值文件类型为:1*H*W
import numpy as np
import caffe
import sys
blob = caffe.proto.caffe_pb2.BlobProto()
with open('mean.npy','rb') as f:
data_mean = numpy.load(f)
blob.channels=1
blob.height = data_mean.shape[0]
blob.width = data_mean.shape[1]
blob.data.extend(data_mean.astype(float).flat)
binaryproto_file = open('mean.binaryproto', 'wb' )
binaryproto_file.write(blob.SerializeToString())
binaryproto_file.close()