当前位置:主页 > 软件编程 > Python代码 >

caffe binaryproto 与 npy相互转换的实例讲解

时间:2021-11-07 09:48:08 | 栏目:Python代码 | 点击:

在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()

您可能感兴趣的文章:

相关文章