简体   繁体   中英

How to set a single color to values bigger than 0 but smaller than 1?

I have a matrix of nxn, for example:

[ 0   1    1 ;
 0.2  1   0.1; 
  0  0.4   0] 

I want to visualize my matrix and I want:

  • All values = 1 to be black
  • All values between 0 and 1 (0 < value <1) to be white
  • All values = 0 to be a specific color (red for example).

As in the following image:

例子

How can I achieve this?

The following solution builds color map, and use ind2rgb to create RGB image:

  • Convert A to "indexed image" (expand by 256, and round) - indexed image elements must be integers.
  • Create color map meeting range conditions.
  • Use ind2rgb for converting X to RGB image with created color map.

Check the following code sample:

A = [  0    1    1;...
     0.2    1  0.1;...
       0  0.4    0];

%N - Number of elements in the color map (e.g 256) applies "quantization level".
N = 256;

%Convert A to "indexed image" in range [0, N].
X = round(A*N);

%Create color map with N elements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%R, G, B (Red, Green, Blue) applies three color components of color map.
R = zeros(N, 1);
G = zeros(N, 1);
B = zeros(N, 1);

%Create array of 100 values in range 0 to 1
V = linspace(0, 1, N);

%All values = 1 to be black
R(V == 1) = 0;
G(V == 1) = 0;
B(V == 1) = 0;

%All values between 0 and 1 (0 < value <1) to be white
R((V > 0) & (V < 1)) = 1;
G((V > 0) & (V < 1)) = 1;
B((V > 0) & (V < 1)) = 1;

%All values = 0 to be a specific color (red for example).
R(V == 0) = 1;
G(V == 0) = 0;
B(V == 0) = 0;

%Concatenate color components, and form Nx3 color map.
cmap = [R, G, B];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Convert A to RGB, using colormap cmap.
RGB = ind2rgb(X, cmap);

imshow(RGB);

The solution is not the most simple solution, but it can be used for solving more general visualization problems.

Result (enlarged):
在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM