Path: blob/master/modules/dnn/src/caffe/caffe_shrinker.cpp
16339 views
// This file is part of OpenCV project.1// It is subject to the license terms in the LICENSE file found in the top-level directory2// of this distribution and at http://opencv.org/license.html.3//4// Copyright (C) 2017, Intel Corporation, all rights reserved.5// Third party copyrights are property of their respective owners.67#include "../precomp.hpp"89#ifdef HAVE_PROTOBUF10#include <fstream>11#include "caffe_io.hpp"12#endif1314namespace cv { namespace dnn {15CV__DNN_INLINE_NS_BEGIN1617#ifdef HAVE_PROTOBUF1819void shrinkCaffeModel(const String& src, const String& dst, const std::vector<String>& layersTypes)20{21CV_TRACE_FUNCTION();2223std::vector<String> types(layersTypes);24if (types.empty())25{26types.push_back("Convolution");27types.push_back("InnerProduct");28}2930caffe::NetParameter net;31ReadNetParamsFromBinaryFileOrDie(src.c_str(), &net);3233for (int i = 0; i < net.layer_size(); ++i)34{35caffe::LayerParameter* lp = net.mutable_layer(i);36if (std::find(types.begin(), types.end(), lp->type()) == types.end())37{38continue;39}40for (int j = 0; j < lp->blobs_size(); ++j)41{42caffe::BlobProto* blob = lp->mutable_blobs(j);43CV_Assert(blob->data_size() != 0); // float32 array.4445Mat floats(1, blob->data_size(), CV_32FC1, (void*)blob->data().data());46Mat halfs(1, blob->data_size(), CV_16SC1);47convertFp16(floats, halfs); // Convert to float16.4849blob->clear_data(); // Clear float32 data.5051// Set float16 data.52blob->set_raw_data(halfs.data, halfs.total() * halfs.elemSize());53blob->set_raw_data_type(caffe::FLOAT16);54}55}56#if GOOGLE_PROTOBUF_VERSION < 300500057size_t msgSize = saturate_cast<size_t>(net.ByteSize());58#else59size_t msgSize = net.ByteSizeLong();60#endif61std::vector<uint8_t> output(msgSize);62net.SerializeWithCachedSizesToArray(&output[0]);6364std::ofstream ofs(dst.c_str(), std::ios::binary);65ofs.write((const char*)&output[0], msgSize);66ofs.close();67}6869#else7071void shrinkCaffeModel(const String& src, const String& dst, const std::vector<String>& types)72{73CV_Error(cv::Error::StsNotImplemented, "libprotobuf required to import data from Caffe models");74}7576#endif // HAVE_PROTOBUF7778CV__DNN_INLINE_NS_END79}} // namespace808182