sapienz
sapienz

Reputation: 152

Color discrimination of matrix connected components

In Matlab, I have a matrix M, say:

M=[0 0 2 2 0 0
   0 0 2 2 0 3
   1 1 2 2 3 3
   1 1 0 0 0 0
   1 1 0 0 0 0];

with some connected components labeled 1,2 and 3. I need to discriminate the components (1, 2 and 3) by using different colors (red, green and blue for example). Any help to do this. Thanks in advance

Upvotes: 0

Views: 147

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112679

You can use image and colormap. From the documentation of the former,

image(C) displays the data in array C as an image. Each element of C specifies the color for 1 pixel of the image.

When C is a 2-dimensional m-by-n matrix, the elements of C are used as indices into the current colormap to determine the color. For 'direct' CDataMapping (the default), values in C are treated as colormap indices (1-based if double, 0-based if uint8 or uint16).

Thererfore, you only need to call image(M+1), so that the values start at 1; and then define a suitable colormap. The colormap is a 3-column matrix, where each row defines a color in terms of its R, G, B components.

M = [0 0 2 2 0 0;0 0 2 2 0 3;1 1 2 2 3 3;1 1 0 0 0 0;1 1 0 0 0 0];
imagesc(M+1)       % add 1 so that values start at 1, not 0
cmap = [1 1 1;     % white
        .7 0 0;    % dark red
        0 .7 0;    % dark green
        0 0 .7];   % dark blue
colormap(cmap)     % set colormap
axis tight         % avoid white space around the values
axis equal         % aspect ratio 1:1

enter image description here

Upvotes: 1

Related Questions