Reputation: 11
I have an image such as the one below that I am trying to convert to grayscale. However, I do not want the standard conversion to grayscale.
Ideally I would like to define some custom color map that would convert the image to grayscale based on the values in the map.
For example: I would like to convert the image below to grayscale using the "jet" gradient in
Visit http://b.vimeocdn.com/ts/121/673/121673915_640.jpg
Upvotes: 1
Views: 1487
Reputation: 3037
Background
Here is the algorithm used by Matlab's built-in method rgb2gray():
rgb2gray() converts RGB values to grayscale values by forming a weighted sum of the R, G, and B components:
0.2989 * R + 0.5870 * G + 0.1140 * B
Note that these are the same weights used by the rgb2ntsc function to compute the Y component.
Note that we have a single multiplier for each of the color channels, which makes life easy.
Solution
The inverse mapping is a nonlinear problem- there is no single set of RGB weights that can take you from the colors back to the gray. You also have no guarantee that the jet
colormap contains all the colors used in the image.
Here is a best-effort workaround, which maps colors to the nearest color in the colormap:
%% Define the transformation as a non-uniform 3D interpolation
resolution = 512;
cmap = jet(resolution);
x = cmap(:,1);
y = cmap(:,2);
z = cmap(:,3);
intensity = gray(resolution);
intensity = intensity(:,1);
fx = TriScatteredInterp(x,y,z,intensity,'nearest');
%% Load our image, then interpolate from RGB to Grayscale intensity
img = double(imread('image.jpeg'))/255.0;
imgOut = fx(img(:,:,1),img(:,:,2),img(:,:,3));
imshow(imgOut)
Runtime is a function of colormap resolution, resolution=512 takes about a minute, resolution=64 takes about 5 seconds. This is slow for two reasons. First, we are doing a non-linear search for each pixel (rather than applying a linear transform). Second, the interpolation is scattered (rather than uniformly defined) which further slows things down.
Input
Output with colormap resolution = 64
Output with colormap resolution = 512
Upvotes: 2