MATLAB: 3D matrix with various chain!!

3d plotsconnected componentsImage Processing Toolbox

If I have U3 matrix as:
U3(:,:,1) = [
0 , 0 , 0 , 0 , 0;
0 , 0 , 0 , 0 , 0;
0 , 1 , 0 , 0 , 1;
0 , 0 , 0 , 0 , 0;
0 , 0 , 0 , 0 , 0
]
U3(:,:,2) = [
0 , 0 , 0 , 0 , 0;
0 , 0 , 0 , 0 , 0;
0 , 1 , 0 , 0 , 1;
0 , 1 , 0 , 0 , 0;
0 , 1 , 0 , 0 , 0
]
U3(:,:,3) = [
0 , 0 , 0 , 0 , 0;
0 , 0 , 0 , 0 , 0;
0 , 1 , 0 , 0 , 1;
0 , 0 , 0 , 0 , 0;
0 , 0 , 0 , 0 , 0
]
I assumed that these coordinates can be represented as an individual chain U3(3,2,1) and U3(3,2,2)and U3(4,2,2) and U3(5,2,2)and U3(3,2,3). and the other coordinates as another individual chain U3(3,4,1) and U3(3,4,2) and U3(3,4,3).
How can I give each chain a similar individual number? EX.
U3(3,2,1) and U3(3,2,2)and U3(4,2,2) and U3(5,2,2)and U3(3,2,3)=2
U3(3,4,1) and U3(3,4,2) and U3(3,4,3)=3

Best Answer

You can use bwconncomp. See this demo I wrote for you:
U3(:,:,1) = [
0 , 0 , 0 , 0 , 0;
0 , 0 , 0 , 0 , 0;
0 , 1 , 0 , 0 , 1;
0 , 0 , 0 , 0 , 0;
0 , 0 , 0 , 0 , 0
]
U3(:,:,2) = [
0 , 0 , 0 , 0 , 0;
0 , 0 , 0 , 0 , 0;
0 , 1 , 0 , 0 , 1;
0 , 1 , 0 , 0 , 0;
0 , 1 , 0 , 0 , 0
]
U3(:,:,3) = [
0 , 0 , 0 , 0 , 0;
0 , 0 , 0 , 0 , 0;
0 , 1 , 0 , 0 , 1;
0 , 0 , 0 , 0 , 0;
0 , 0 , 0 , 0 , 0
]
% Method 1
% Make the list for how you want the objects labeled:

desiredNumberList = [2 3 4 42 69 123 73]; % Whatever you want.

% Make an object for the output
labeledImage = zeros(size(U3), 'int16')
% Do connected components labeling.
connectivityObject = bwconncomp(U3)
% Get the number of object it found (optional).
numberOfObjects = connectivityObject.NumObjects
% Now go through the blobs, reassiging them with the labels Hisham wants.
for blob = 1 : numberOfObjects
% Get the linear indices of the pixels that
% identify this particular blob.
pixelIndexes = connectivityObject.PixelIdxList{blob}
% Make those pixels have the desired number.
labeledImage(pixelIndexes) = desiredNumberList(blob);
end
% Print out the output image to the command window.
labeledImage
% Method 2
% Use labelmatrix but cast to uint16 if you ever expect to have more than 255 blobs.
labeledImage = uint16(labelmatrix(connectivityObject))
% But you didn't want 1,2,3, etc. You wanted custom numbers.
% For that we need to remap the default label numbers using intlut().
% Right now the blobs are labeled 1,2,3, etc.
% Make those pixels have the desired number with intlut().
% Make the list for how you want the objects labeled:
% But first one has to be zero because zero must remain as zero.
desiredNumberList = zeros(1, int32(intmax('uint16'))+1, 'uint16');
desiredNumberList(1:8) = [0 2 3 4 42 69 123 73]; % Whatever you want.
labeledImage = intlut(labeledImage, desiredNumberList)