在caffe中,如果使用的是c++接口,均值文件默认为.binaryproto格式,而如果使用的是Python接口,均值文件默认的是numpy的.npy格式,在工作中有时需要将两者进行互相转换,具体方式如下:
binaryproto -> npy
import numpy as np
import caffe
import sys
blob = caffe.proto.caffe_pb2.BlobProto()
data = open( 'mean.binaryproto' , 'rb' ).read()
blob.ParseFromString(data)
arr = np.array( caffe.io.blobproto_to_array(blob) )
out = arr[0]
np.save( 'mean.npy' , out )
npy -> binaryproto
data_mean is 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()