MATLAB: Finding length of scale bar from matrix form of image

imageimage processingmatriciesmatrixpixelpixel sizescale bar

I have a grey image which I have converted into matrix form, but below the image there is a scale bar. The scale bar is surrounded by white background and scale bar is black. I am wondering if there is a way to code something to go through my matrix of the whole image until it detects the first black pixel (the first black pixel on the scale bar)

Best Answer

As said before, not too difficult if you know what you need. Here is the code
% Read the image
imageWithScaleBar = imread('/Users/ccr22/Desktop/1.png');
%display to visualise
imagesc(imageWithScaleBar(:,:,1))
% select the low intensity pixels notice that you only need one
% channel of the RGB as it is a gray scale image
% You need to close as there may be small gaps in the scale bar
blackPart = imclose(imageWithScaleBar(:,:,1)<20,ones(1,3));
% find the major axis length to know which is the scale bar and
% the bounding box for the position
blackPartLabelled = bwlabel(blackPart);
imagesc(blackPartLabelled)
darkParts.jpg
You can see that each dark section of your image has a different colour, i.e. a label, now you need to know which is the one you want, i.e. the long thin one, so look for the major axis length
blackPartProperties = regionprops(blackPartLabelled,'MajoraxisLength','boundingbox');
[a,b]=(max([blackPartProperties.MajorAxisLength]));
When you run this you will have the output of a and b as there is no echo inhibitor in the last line:
a =
173.2051
b =
85
Now you know that the object you want is number 85, so select it
% so the object in question is label 85
scaleBar = (blackPartLabelled==b);
imagesc(scaleBar)
scaleBar.jpg
So now you have the scale bar, I have used the data tips to show where it starts manually but you can get this directly by retrieving the bounding box previously calculated:
>> blackPartProperties(b).BoundingBox
ans =
96.5000 188.5000 150.0000 1.0000
that gives you the coordinates where your scale bar is located and that solves the problem. Do let me know if you have questions and if this solves your problem, please accept the answer.
Related Question