rcnn_features.m 1.72 KB
Newer Older
Ross Girshick's avatar
Ross Girshick committed
1
function feat = rcnn_features(im, boxes, rcnn_model)
2
3
4
5
6
7
8
% feat = rcnn_features(im, boxes, rcnn_model)
%   Compute CNN features on a set of boxes.
%
%   im is an image in RGB order as returned by imread
%   boxes are in [x1 y1 x2 y2] format with one box per row
%   rcnn_model specifies the CNN Caffe net file to use.

Ross Girshick's avatar
Ross Girshick committed
9
10
11
12
13
14
15
16
17
% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
% 
% This file is part of the R-CNN code and is available 
% under the terms of the Simplified BSD License provided in 
% LICENSE. Please retain this notice and LICENSE if you use 
% this file (or any portion of it) in your project.
% ---------------------------------------------------------
Ross Girshick's avatar
Ross Girshick committed
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

% make sure that caffe has been initialized for this model
if rcnn_model.cnn.init_key ~= caffe('get_init_key')
  error('You probably need to call rcnn_load_model');
end

% Each batch contains 256 (default) image regions.
% Processing more than this many at once takes too much memory
% for a typical high-end GPU.
[batches, batch_padding] = rcnn_extract_regions(im, boxes, rcnn_model);
batch_size = rcnn_model.cnn.batch_size;

% compute features for each batch of region images
feat_dim = -1;
feat = [];
curr = 1;
for j = 1:length(batches)
  % forward propagate batch of region images 
  f = caffe('forward', batches(j));
  f = f{1};
38
  f = f(:);
Ross Girshick's avatar
Ross Girshick committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  
  % first batch, init feat_dim and feat
  if j == 1
    feat_dim = length(f)/batch_size;
    feat = zeros(size(boxes, 1), feat_dim, 'single');
  end

  f = reshape(f, [feat_dim batch_size]);

  % last batch, trim f to size
  if j == length(batches)
    if batch_padding > 0
      f = f(:, 1:end-batch_padding);
    end
  end

  feat(curr:curr+size(f,2)-1,:) = f';
  curr = curr + batch_size;
end