mean.npy 转换为mean.protxt
import caffe
import numpy as np
#
# mean.npy to mean.binaryproto
# 使用mean.npy 生成 mean.binaryproto 用于caffe的模型转换
MEAN_NPY_PATH = 'mean.npy'
# 构造损失值得数据, 将npy进行数据保存
mean = np.ones([1, 3, 160, 160], dtype=np.float)
mean[0, 0, :, :] = 102.02040364583333 # 将各个维度的均值进行添加
mean[0, 1, :, :] = 102.02040364583333
mean[0 ,2, :, :] = 102.02040364583333
np.save(MEAN_NPY_PATH, mean) # 将均值保存在路径下
import numpy as np
mean_npy = np.load(MEAN_NPY_PATH) # 加载均值的路径
mean = mean_npy.mean(1).mean(1) # 获得均值
import numpy as np
import caffe
import sys
blob = caffe.proto.caffe_pb2.BlobProto()
with open('mean.npy', 'rb') as f:
data_mean = np.load(f)
# 构造blob的尺寸
blob.num = 1
blob.channels = 3
blob.height = data_mean.shape[2]
blob.width = data_mean.shape[3]
blob.data.extend(data_mean.astype(float).flat)
binaryproto_file = open('mean.binaryproto', 'wb')
binaryproto_file.write(blob.SerializeToString())
binaryproto_file.close()
将mean.protxt 转换为mean.npy
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)