caffe binaryproto 与 npy相互转换的实例讲解
在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()
以上这篇caffe binaryproto 与 npy相互转换的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。