matlabnormalizationbsxfunmatconvnet

Matlab: error using bsxfun Non-singleton dimensions of the two input arrays must match each other


I'm trying to run https://www.vlfeat.org/matconvnet/quick/,

I wrote the following codes (network is Alexnet):

im = imread('/home/levi/Codes/MM_space//n01443537_22563.JPEG');
im_ = single(im);
im_ = imresize(im_, net.meta.normalization.imageSize(1:2));

Until this part is fine, _im becomes a

227*227*3 single

However, after running this:

im_ = bsxfun(@minus, im_, net.meta.normalization.averageImage);

I receive the error:

Error using bsxfun Non-singleton dimensions of the two input arrays must match each other

According to the webpage it should work, but is not working... I also did a little search but still struggling with solving it.

net.meta.normalization.averageImage is

3×1 single column vector

  122.7395
  114.8967
  101.5919

Thank you for your help in advance


Solution

  • You are trying to apply an operation between a 227*227*3 matrix and a 3*1 (or 3*1*1) array. bsxfun tries to expand the singleton dimensions (i.e. dimensions of size 1 in the array) to match the size of the other array, but to do that the other dimensions must already match. They don't because your non-singleton dimension in the array is dimension 1, where the matching dimension of size 3 in the matrix is dimension 3.

    You can reshape the array so that the matching sizes are aligned

    % Make the average array a 1*1*3
    avg = reshape( net.meta.normalization.averageImage, 1, 1, [] );
    % Now do subtraction
    im_ = bsxfun(@minus, im_, avg);
    

    Note that since MATLAB 2016b, you can use implicit expansion without requiring bsxfun. The same condition applies with the input dimensions, so you still need the reshape above, but then you can just do

    im_ = im_ - avg;