

function Out = GrayMtx2ToyotaMtx(In,origres)
nExmpl = size(In,2);
for i = 1:nExmpl
  if(mod(i,25) == 0)
    fprintf('%d of %d\n',i,nExmpl);
  end
  im = reshape(In(:,i),origres);
  imL = im2LayerIm(im,[16,16]);
  Out(:,i) = imL(:);
end

function im_layers = im2LayerIm(im,resolution)
crop = imresize(im, resolution*4,'bilinear');
im_layers = ApplySobelFilts(crop);
im_layers = maxfilter(im_layers,5);
im_layers = imresize(im_layers,resolution,'bilinear');

function im_layers = ApplySobelFilts(crop)
filts{1} = [1,1,1;0,0,0;-1,-1,-1];
filts{2} = [-1,0,1;-1,0,1;-1,0,1];
filts{3} = [0,1,1;-1,0,1;-1,-1,0];
filts{4} = [1,1,0;1,0,-1;0,-1,-1];
filts{5} = [-1,-1,-1;-1,8,-1;-1,-1,-1];
filts{6} = [0,0,0;0,1,0;0,0,0];
s = size(crop);
im_layers = zeros(s(1),s(2),length(filts));
crop = im2double(crop);
for i = 1:length(filts)
  im_layers(:,:,i) = imfilter(crop,filts{i},'symmetric');
  if(i ~= 6)
    im_layers(:,:,i) = abs(im_layers(:,:,i));
  end
end