1
votes

Each pixel in an image has an rgb value that looks like [r g b], where r,g,b are integer values from 0 to 255.

Now, let us define 8 rgb color extremes:

[0 0 0] black

[0 0 255] blue

[0 255 0] green

[0 255 255] cyan

[255 0 0] red

[255 0 255] magenta

[255 255 0] yellow

[255 255 255] white.

Is there an efficient way in Matlab or a function in Matlab that can convert an image into another image that has these 8 extreme colors, with threshold?

2
Could you please tell a rule for conversion? i.e. I have [120, 80, 200] pixel, to which extreme it should be mapped?Gryphon
@Gryphon Simple subtraction should do - the one with the smallest difference will be pickedfrslm
Have you tried rgb2ind?rahnema1
@Gryphon, it depends on the threshold, if r_threshold = g_threshold = b_threshold = 128, then it would be [0 0 255]Faceb Faceb
Why not write it in the question? rgb2ind or LUT can do the thing, but you should prepare map or table for lookup yourselfGryphon

2 Answers

0
votes

If you actually want is to assign each pixel color to what a human would say are the closest of those 8 colors to the current pixel, you should compute a L2 distance between the color in each pixel and each of the eight colors in a perceptually uniform color space like Lab*. The smallest distance would then be the assigned color. Computing distances in RGB space does not correspond to what a human would say is the "closest color".

https://en.wikipedia.org/wiki/Lab_color_space

You could implement this using the MATLAB function pdist2.

https://www.mathworks.com/help/stats/pdist2.html

0
votes

A quick way is to threshold each channel, converting it to 0 or 1, then multiplying by 255:

r_threshold = 128;
g_threshold = 117;
b_threshold = 192;
% im is original image
im2(:,:,1) = (im(:,:,1) - r_threshold) > 0;   % threshold red channel...
im2(:,:,2) = (im(:,:,2) - g_threshold) > 0;   % ... green channel
im2(:,:,3) = (im(:,:,3) - b_threshold) > 0;   % ... and blue channel
im2 = im2 .* 255;   % change range from [0,1] to [0,255]

An equivalent but slightly less obvious way to do the thresholding (for newer versions of MATLAB) would be to permute the vector of thresholds into a 1x1x3 vector and performing elementwise subtraction:

im2 = (im .- permute([r_threshold, g_threshold, b_threshold], [1 3 2])) > 0;
im2 = im2 .* 255;