How to apply colours of my choosing to labels in a binary image based on their individual areas
7 views (last 30 days)
Show older comments
Callum Moore
on 17 Dec 2020
Commented: Image Analyst
on 22 Nov 2023
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!
9 Comments
Accepted Answer
Image Analyst
on 17 Dec 2020
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.
6 Comments
imaggeprocessor01
on 22 Nov 2023
@Image Analyst Thank you! this is really useful. Do you know how we can compare and get the dice score of the output image of this and a given "ground truth" image (basically a grayscale image correspond to images in the input dataset with only 2 labelling values. The washers are labelled with 1, small screws value 2 and background value 0).
Image Analyst
on 22 Nov 2023
Just split them up into two classes
testWashers = ismember(labeledImage, 1);
diceWashers = dice(testWashers, groundTruthWashers);
testScrews = ismember(labeledImage, 2);
diceScrews = dice(testScrews, groundTruthScrews);
More Answers (0)
See Also
Categories
Find more on Data Distribution Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!