python生成caffe binary proto文件

来源:互联网 发布:淘宝运营 策划能力 编辑:程序博客网 时间:2024/05/24 01:15

使用python 生成 caffe .binaryproto文件,使用起来比caffe提供的二进制工具灵活一些,可以在生成的时候自由添加一些对数据的处理。

python 代码:

def ComputeMean(img_file_list,mean_file_write_to):    #resize 尺寸    protosize=(224,224)    #可以限定生成均值图像使用的图像数量    mean_count=20000    images=open(img_file_list.decode('utf-8')).read().strip().split('\n')    totalMean=np.zeros(protosize[0],protosize[1],3)    accedImage=np.zeros(protosize[0],protosize[1],3)    for index,img in enumerate(images):        img_path=img.decode('gbk').split(' ')[0].replace('G:/','/Volumes/xxx/')        print img_path        img_data=cv2.imread(img_path.encode('gbk'))        img_resized=cv2.resize(img_data,protosize,interpolation=cv2.INTER_LINEAR)        cv2.accumulate(img_resized,accedImage)        #累计1000次计算一次均值速度会快一些,如果图像太多汇总起来再计算可能会溢出。        if(index%1000 ==0 and index>0):             accedImage=accedImage/float(mean_count)             cv2.accumulate(accedImage,totalMean)             accedImage=np.zeros(protosize[0],protosize[1],3)        print "processed: "+str(index)        if index==mean_count:            break    accedImage=accedImage/float(mean_count)    cv2.accumulate(accedImage,totalMean)    #均值文件保存成图像便于查看    cv2.imwrite(mean_to_file+"proto.jpg",totalMean)    cv2.imshow("test",totalMean)    cv2.waitKey(1000)     #for RGB image    # totalMean=totalMean.transpose((2, 0, 1))    # 存储为binaryproto    blob = caffe.BlobProto()    blob.channels=3    blob.height = protosize[0]    blob.width = protosize[1]    blob.num=1    blob.data.extend(totalMean.astype(float).flat)    binaryproto_file = open(mean_file_write_to, 'wb' )    binaryproto_file.write(blob.SerializeToString())    binaryproto_file.close()

对于单通道图像生成的方式大同小异,channel改为1即可。

原创粉丝点击