void computeFeatures(Net<Dtype>& caffe_test_net,
    const vector<Mat>& imgs,
    string LAYER,
    int BATCH_SIZE,
    vector<vector<Dtype>>& output) {
  int nImgs = imgs.size();
  int nBatches = ceil(nImgs * 1.0f / BATCH_SIZE);
  for (int batch = 0; batch < nBatches; batch++) {
    int actBatchSize = min(nImgs - batch * BATCH_SIZE, BATCH_SIZE);
    vector<Mat> imgs_b;
    if (actBatchSize >= BATCH_SIZE) {
      imgs_b.insert(imgs_b.end(), imgs.begin() + batch * BATCH_SIZE, 
          imgs.begin() + (batch + 1) * BATCH_SIZE);
    } else {
      imgs_b.insert(imgs_b.end(), imgs.begin() + batch * BATCH_SIZE, imgs.end());
      for (int j = actBatchSize; j < BATCH_SIZE; j++)
        imgs_b.push_back(imgs[0]);
    }
    vector<int> dvl(BATCH_SIZE, 0);
    boost::dynamic_pointer_cast<caffe::MemoryDataLayer<Dtype>>(
        caffe_test_net.layers()[0])->AddMatVector(imgs_b, dvl);
    vector<Blob<Dtype>*> dummy_bottom_vec;
    Dtype loss = 0.0f;
    caffe_test_net.ForwardPrefilled(&loss);
    const boost::shared_ptr<Blob<Dtype>> feat = caffe_test_net.blob_by_name(LAYER);
    for (int i = 0; i < actBatchSize; i++) {
      Dtype* feat_data = feat->mutable_cpu_data() + feat->offset(i);
      output.push_back(vector<Dtype>(feat_data, feat_data + feat->count() / feat->num()));
    }
    LOG(INFO) << "Batch " << batch << "/" << nBatches << " (" << actBatchSize << " images) done";
  }
}
Exemple #2
0
// function blob_get_data_byname_multigpu
// input:  blob_name 
// output: response
static void blob_get_data_byname_multigpu(MEX_ARGS) {
	if (nrhs != 1) {
		LOG(ERROR) << "Only given " << nrhs << " arguments";
		mexErrMsgTxt("caffe_mex : Wrong number of arguments");
	}

	if (solvers_.empty())
	{
		mexPrintf("No solver inited!\n");
		plhs[0] = mxCreateDoubleScalar(-1);
		return;
	}

	mxCHECK(sync_ptr != NULL, "blob_set_data_multigpu only work on multi-GPU solver");

	vector<shared_ptr<P2PSync<float>>>* sync_vec = sync_ptr->get_syncs(); 

	char* blob_name = mxArrayToString(prhs[0]);

	mxArray* top;
	top = mxCreateCellMatrix(int(sync_vec->size()), 1);
	for (int i = 0; i < sync_vec->size(); i++)
	{
		Solver<float> *solver;
		if (i == 0)
		{
			solver = sync_ptr->solver().get();
		}
		else
		{
			solver = (*sync_vec)[i]->solver().get();
		}

		Net<float> *net = solver->net().get();
		Blob<float> *blob = net->blob_by_name(blob_name).get();

		mxArray* response = blob_to_mx_mat(blob, DATA);
		mxSetCell(top, i, response);
	}

	plhs[0] = top;
	mxFree(blob_name);
}