caffe mean


原文链接: caffe mean

mean.binaryproto转mean.npy
使用Caffe的C++接口进行操作时,需要的图像均值文件是pb格式,例如常见的均值文件名为mean.binaryproto;但在使用python接口进行操作时,需要的图像均值文件是numpy格式,例如mean.npy。所以在跨语言进行操作时,需要将mean.binaryproto转换成mean.npy,转换代码如下:

import caffe
import numpy as np

MEAN_PROTO_PATH = 'mean.binaryproto'               # 待转换的pb格式图像均值文件路径
MEAN_NPY_PATH = 'mean.npy'                         # 转换后的numpy格式图像均值文件路径

blob = caffe.proto.caffe_pb2.BlobProto()           # 创建protobuf blob
data = open(MEAN_PROTO_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_NPY_PATH ,mean_npy)

已知图像均值,构造mean.npy
如果已知图像中每个通道的均值,例如3通道图像每个通道的均值分别为104,117,123,我们也可以通过其构造mean.npy。代码如下:

import numpy as np

MEAN_NPY_PATH = 'mean.npy'

mean = np.ones([3,256, 256], dtype=np.float)
mean[0,:,:] = 104
mean[1,:,:] = 117
mean[2,:,:] = 123

np.save(MEAN_NPY, mean)

载入mean.npy
上面我们用两种方式构造了均值文件mean.npy,在使用时载入mean.npy的代码如下:

import numpy as np

mean_npy = np.load(MEAN_NPY_PATH)
mean = mean_npy.mean(1).mean(1)

————————————————
版权声明:本文为CSDN博主「hyman_yx」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/hyman_yx/article/details/51732656

import sys
# sys.path.insert(0, caffe_root + 'python')
import caffe
import caffe.proto.caffe_pb2 as caffe_proto

import numpy as np

def binaryproto_2_npy(binaryproto_file, npy_file):
    '''
    '''
    blob = caffe.proto.caffe_pb2.BlobProto()
    data = open(binaryproto_file, 'rb').read()
    blob.ParseFromString(data)
    data = np.array(blob.data)
    arr = np.array( caffe.io.blobproto_to_array(blob) )
    #out = arr[0]
    print("[INFO] binaryproto shape {}".format(arr.shape))
    np.save( npy_file , arr)

def data_2_binaryproto(binaryproto_file, mean):
    """
    Create a binaryproto file with a single blob containing the given pixel-wise mean.
    Overwrites any existing file with the same name.
    :param filename: Filename to be used
    :type filename: str
    :param mean: Numpy array holding the mean
    :type mean: numpy.multiarray.ndarray
    """
    #if 4 != len(mean.shape):
    #    print("mean's shape should be 4-D, but is {}".format(mean.shape))
    blob = caffe.io.array_to_blobproto(mean)
    with open(binaryproto_file, "wb") as f:
        f.write(blob.SerializeToString())

if __name__ == "__main__":
    npy_file = "./imagenet_mean.npy"

    binaryproto_file = "./imagenet_mean.binaryproto"
    # generate_interpNet_mean_binaryproto((3,3), binaryproto_file)
    binaryproto_2_npy(binaryproto_file, npy_file)
`