How can I transform a graded colored map into a percentage matrix (convert pixel color into a percentage based on a palette)?

Viewed 57

I'd like to convert this graded colored map into a matrix in which to each pixel a percentage of orange is assigned. In particular, taking the color palette of orange at the right of image.

I'd like to assign 100% to the brightest orange at the top and 0% to the black at the bottom. Hence, I'd like to assign to each pixel a percentage, based on the color of that single pixel in relation to the palette.

Finally, my goal consists of averaging these percentages in order to get a sort of mean percentage of orange. For the latter step, I shouldn't have any issue... but I've no idea how to face the former problem.

I am looking for a solution either in R, Matlab or Mathematica

1 Answers

Here's an idea that I had. Suppose you have an image with arbitrary colors; let's solve for a transformation that reduces your color from 3-dimensional space to a single dimension by running an optimizer. The cost function is derived from the error when the original colors are attempted to be recovered by the lossy color transformation.

See the image below for my result, scaled to 100% at the brightest pixel and 0% at the darkest.

img = imread('zpiaD.png');
opt = optimset('Display', 'Iter');

itf = fminsearch(@(itf) min_colormap(img, itf) , zeros(1,3), opt);
[~, rimg] = min_colormap(img, itf);

subplot(2,1,1), imshow(rimg), title 'single color dimension'
subplot(2,1,2)
rimg = double(rimg);
imagesc(100 * (rimg - min(min(rimg))) / (max(max(rimg)) - min(min(rimg)))),
colorbar, title 'scaled'

function [res, timg] = min_colormap(img, itf)
  pimg = double(reshape(img, size(img,1)*size(img,2), size(img,3)));
  timg = transpose(itf * pimg');
  res = sum(((timg * itf) - pimg).^2, 'all');
  timg = cast(reshape(timg, size(img,1), size(img,2)), 'uint8');
end

result

Related