Configuring a convolution layer in caffe cpp windows

I have this network 'RGB2GRAY.prototxt':

name: "RGB2GRAY"
layer {
  name: "data"
  type: "Input"
  top: "data"
  input_param { shape: { dim: 1 dim: 3 dim: 512 dim: 512 } }
}

layer {
    name: "conv1"
    bottom: "data"
    top: "conv1"
    type: "Convolution"
    convolution_param {
        num_output: 1
        kernel_size: 1
        pad: 0
        stride: 1
        bias_term: false
        weight_filler {
        type: "constant"
        value: 1
        }
    }
}

I am trying to use my own network that converts RGB to gray using this formula

x = 0.299r + 0.587g + 0.114b.

so basically, I can do a convolution with a kernel size of 1 with configured weights (0.299, 0.587, 0.114). but I don’t understand how to change the convolution level. I set the weight and offset, but could not change the filter value. I tried the approach below, but it does not update the convolution filter.

shared_ptr<Net<float> > net_;
net_.reset(new Net<float>("path of model file", TEST));

const shared_ptr<Blob<float> >& conv_blob = net_->blob_by_name("conv1");
float* conv_weight = conv_blob->mutable_cpu_data();
conv_weight[0] =  0.299;
conv_weight[1] =  0.587;
conv_weight[2] =  0.114;

net_->Forward();

//for dumping the output
const shared_ptr<Blob<float> >& probs = net_->blob_by_name("conv1");
const float* probs_out = probs->cpu_data();

cv::Mat matout(height, width, CV_32F);

for (size_t i = 0; i < height; i++)
{
    for (size_t j = 0; j < width; j++)
    {
        matout.at<float>(i, j) = probs_out[i* width + j];
    }

}
matout.convertTo(matout, CV_8UC1);
cv::imwrite("gray.bmp", matout);

In python, it was easier for me to set up a convolution filter, but I need a solution in C ++.

+4
source share
1 answer

Just make a small change in your C ++ code:

// access the convolution layer by its name
const shared_ptr<Layer<float> >& conv_layer = net_->layer_by_name("conv1");
// access the layer blob that stores weights
shared_ptr<Blob<float> >& weight = conv_layer->blobs()[0];
float* conv_weight = weight->mutable_cpu_data();
conv_weight[0] =  0.299;
conv_weight[1] =  0.587;
conv_weight[2] =  0.114;

, "conv1" blob , blob, Net<Dtype>::blob_by_name(const string& blob_name), blob, .

+2

Source: https://habr.com/ru/post/1663833/


All Articles