% scale the intensities of the cells by looking at all cells in one
% image
load cells;

% train data:
I = cell2mat(x(:,3));
for i=1:length(Itrain)  % over all train images
   R=[]; G=[]; B=[];
   J = find(I==Itrain(i));
   for j=1:length(J)
      msk = x{J(j),2};
      % red:
      im = x{J(j),1}(:,:,1);
      pixs = im(msk);
      R = [R; pixs(:)];
      % green:
      im = x{J(j),1}(:,:,2);
      pixs = im(msk);
      G = [G; pixs(:)];
      % blue:
      im = x{J(j),1}(:,:,3);
      pixs = im(msk);
      B = [B; pixs(:)];
   end
   % now find min and max:
   % red:
   mR = quantile(double(R),[0.001 0.999]);
   mG = quantile(double(G),[0.001 0.999]);
   mB = quantile(double(B),[0.001 0.999]);
   for j=1:length(J)
      im = double(x{J(j),1});
      msk = double(x{J(j),2});
      % red:
      imR = im(:,:,1).*msk-mR(1);
      if mR(2)>mR(1), imR = imR/(mR(2)-mR(1)); end
      mR(mR<0) = 0; mR(mR>1) = 1;
      % green:
      imG = im(:,:,2).*msk-mG(1);
      if mG(2)>mG(1), imG = imG/(mG(2)-mG(1)); end
      mG(mG<0) = 0; mG(mG>1) = 1;
      % blue:
      imB = im(:,:,3).*msk-mB(1);
      if mB(2)>mB(1), imB = imB/(mB(2)-mB(1)); end
      mB(mB<0) = 0; mB(mB>1) = 1;
      x{J(j),1} = cat(3,imR,imG,imB);
   end
end

% test data:
I = cell2mat(z(:,3));
for i=1:length(Itest)  % over all train images
   R=[]; G=[]; B=[];
   J = find(I==Itest(i));
   for j=1:length(J)
      msk = z{J(j),2};
      % red:
      im = z{J(j),1}(:,:,1);
      pixs = im(msk);
      R = [R; pixs(:)];
      % green:
      im = z{J(j),1}(:,:,2);
      pixs = im(msk);
      G = [G; pixs(:)];
      % blue:
      im = z{J(j),1}(:,:,3);
      pixs = im(msk);
      B = [B; pixs(:)];
   end
   % now find min and max:
   % red:
   mR = quantile(double(R),[0.001 0.999]);
   mG = quantile(double(G),[0.001 0.999]);
   mB = quantile(double(B),[0.001 0.999]);
   for j=1:length(J)
      im = double(z{J(j),1});
      msk = double(z{J(j),2});
      % red:
      imR = im(:,:,1).*msk-mR(1);
      if mR(2)>mR(1), imR = imR/(mR(2)-mR(1)); end
      mR(mR<0) = 0; mR(mR>1) = 1;
      % green:
      imG = im(:,:,2).*msk-mG(1);
      if mG(2)>mG(1), imG = imG/(mG(2)-mG(1)); end
      mG(mG<0) = 0; mG(mG>1) = 1;
      % blue:
      imB = im(:,:,3).*msk-mB(1);
      if mB(2)>mB(1), imB = imB/(mB(2)-mB(1)); end
      mB(mB<0) = 0; mB(mB>1) = 1;
      z{J(j),1} = cat(3,imR,imG,imB);
   end
end

save cellscaled x z Itrain Itest;

