MATLAB: How to apply colours of the choosing to labels in a binary image based on their individual areas

homeworkImage Processing Toolboximage segmentationlabels

Hi, I'm trying to create a program that can pick out screws and bolts in an image but the screws and bolts will be a different colour each. I've segmented the image successfuly and used the 'bwlabel' function to apply labels to the images. I know the 'label2rgb' function can apply colours to all labels but I can only make it so all labels are a random colour. I'm a little stumped and any help would be greatly appreciated!

Best Answer

Add this to your segmentaiton code:
% Get the aspect ratio of each blob.
props = regionprops(mask, grayImage, 'MajorAxisLength', 'MinorAxisLength', 'Area');
aMajor = [props.MajorAxisLength]
aMinor = [props.MinorAxisLength]
allAreas = sort([props.Area])
aspectRatios = aMajor ./ aMinor
numBlobs = length(props)
cmap = zeros(numBlobs+1, 3);
for k = 1 : numBlobs
if aspectRatios(k) > 2 % Whatever value you want.
cmap(k+1, :) = [1, 0, 0]; % Red.
else
cmap(k+1, :) = [0, 1, 0]; % Green.
end
end
cmap
h3 = subplot(2, 2, 3);
labeledImage = bwlabel(mask);
imshow(labeledImage, []);
colormap(h3, cmap);
Note: my segmentation is not good because it didn't find the lower right washer nice and the screw and the washer are touching and I didn't try to separate them. But the colormap code works well.