how do I calculate the area of the black pixels?
3 views (last 30 days)
Show older comments
I have a pixture and i want to calculate the surface of the black area in the middle. I know the size of the small square's (10x10mm). and the distance between them is 18cm.
I have a script that outputs the amount of black pixels and white pixels but i would like to to output the surface area in milimeters.
Is this possible to do? I dont have much experience with matlab so does anyone have any tips on how to do it if it is possible
black pixels: 873454
white pixels: 2640296
0 Comments
Accepted Answer
Walter Roberson
on 25 Jun 2021
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/665000/image.jpeg';
img = imread(filename);
BW = imbinarize(rgb2gray(img));
imshow(BW)
format long g
props = regionprops(~BW, 'Area');
sA = sort([props.Area])
mA = mean(sA(1:end-1))
relA = sA(end)/mA
small_area = 10*10;
absA = relA * small_area
The small black squares are not all the same area, so I took the mean() area as being representative.
The large square is 91.4 times larger than the (mean) smaller square
The smaller square is 10x10 = 100 mm^2 so the larger one is 9141.5 mm^2
3 Comments
Walter Roberson
on 25 Jun 2021
You read the file. It is a JPEG file, and like 99.9% of .jpeg files, it is RGB even if it does not look like RGB.
So the first thing you need to do is convert the RGB to binary. Then the code displays the binary image.
After that, regionprops() is called to find the blobs and extract statistics about the blobs -- in particular the Area statistic. But regionprops() works on blobs that are non-zero, and here we need it to work on the blobs that are 0 (black), so ask regionprops() to work on ~BW with the ~ part converting black to white and white to black.
Once the areas of all of the blobs are extracted, sort the areas. The big blob will have the highest area (by far). Average the ones other than the last to find out how big they are (on average)
You know the small ones are supposed to be 100 mm^2. You can calculate the area of the big one by taking the number of pixels in it divide by the (average) number of pixels in the smaller ones, multiply by the known mm^2 of the small ones, to get the mm^2 of the large one.
Whether you should use the mean() or min() or max() of the size of the smaller blobs is open to discussion. You say that they are all 100 mm^2 but they all occupy different number of pixels, with about 10% difference between the size of the largest and smallest.
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!