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

时间:2022-02-27 08:37:56

caffe中,如果使用的是c++接口,均值文件默认为.binaryproto格式,而如果使用的是python接口,均值文件默认的是numpy的.npy格式,在工作中有时需要将两者进行互相转换,具体方式如下:

binaryproto -> npy

?
1
2
3
4
5
6
7
8
9
10
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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()

以上这篇caffe binaryproto 与 npy相互转换的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/may0324/article/details/52316967