Clear Filters
Clear Filters

Apply 4 color 2d colormap to data

6 views (last 30 days)
Elin Jacobs
Elin Jacobs on 9 Dec 2022
Answered: Jaswanth on 9 Feb 2024
Hi,
I have two 1800x3600 matrices with values between 0-1, and have generated a four-color 2d colormap with the below code, where the x axis would correspond to the values in one matrix and y axis would correspond to the values in the other. I want to use the scheme to colorcode each element with the same index in the two matrices, simlar to the attached figure. Any pointers to accomplish this would be appreciated!
c{1} = [1 0 0]; % specify 4 colors
c{2} = [0 0 0];
c{3} = [1 0 1];
c{4} = [0 0 1];
C = reshape(vertcat(c{:}), 2, 2, []);
n = 700; % number of pixels
img = zeros(n, n, 3);
for i=1:3
img(:,:,i) = interp2([0 1], [0 1], C(:,:,i), linspace(0,1,n), linspace(0,1,n).');
end
imshow(img);

Answers (1)

Jaswanth
Jaswanth on 9 Feb 2024
Hi Elin Jacobs,
To color code each element with the same index in the two matrices using the colormap you have generated, you can map the values from each matrix to the corresponding x and y coordinates in the color map image.
Assuming you have matrix data available, following steps post defining the color and interpolating the colormap as per the code you have provided could be helpful:
  • Initialize the RGB Image: An empty RGB image ‘rgbImage’ is initialized with the same dimensions as ‘matrix1’ (and ‘matrix2’), with three layers to represent the red, green, and blue color channels.
rgbImage = zeros(size(matrix1, 1), size(matrix1, 2), 3);
  • Map Data to Colormap and Create RGB Image: Each element in ‘matrix1’ and ‘matrix2’ corresponds to a coordinate on the colormap image. The roundfunction calculates the nearest integer pixel coordinate on the colormap image based on the value from ‘matrix1’ (x-axis) and ‘matrix2’ (y-axis). The corresponding color from the colormap image is then assigned to the pixel at position (i, j) in 'rgbImage.'
for i = 1:size(matrix1, 1)
for j = 1:size(matrix1, 2)
x_coord = round(matrix1(i, j) * (n - 1)) + 1;
y_coord = round(matrix2(i, j) * (n - 1)) + 1;
rgbImage(i, j, :) = colormapImage(y_coord, x_coord, :);
end
end
imshow(rgbImage);
I hope above provided pointers will be helpful in accomplishing your task.

Categories

Find more on Colormaps in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!