Find the perimeter of the shaded region-- the logical "1."

3 views (last 30 days)
In a binomial array of some random, consecutive shape. I have to create script that will determine the perimeter of each "line."
Example:
random sahpe=
[ 0 1 0 0 0
1 1 1 0 0
0 1 0 0 0
1 1 0 0 0
0 1 0 0 0 ]
ans= 18
I currently have this in a script looking like this:
box=[0 0 0 0 0; 0 0,1,0 0; 0 0,1,0 0; 0 0,0,0 0; 0 0 0 0 0] %in a 3 by 3 with a perimeter of zeros
for row= 2:4 %row number of shape box
for col= 2:4 %col number of shape box
if box(row,col)==1 %if element(1,1)=1 look at row and col of it
row;
col;
end
Sides= box(row, col-1)+ box(row, col+1)+ box(row+1, col)+ box(row-1, col)
eachSides= 4 -Sides
sub= eachSides*(Sides+1)
end
end
It works for only two conjoined logical arrays. Can anyone help?

Answers (2)

DGM
DGM on 18 Nov 2022
See bwperim() or regionprops() to get the perimeter. If you want to come up with a different way to define the perimeter, that'll be up to you to define.

Image Analyst
Image Analyst on 18 Nov 2022
You can use bwboundaries to get perimeter points. But if it's the length of the perimeter that is wanted regionprops is the way to go
sahpe = [ 0 1 0 0 0
1 1 1 0 0
0 1 0 0 0
1 1 0 0 0
0 1 0 0 0 ]
sahpe = 5×5
0 1 0 0 0 1 1 1 0 0 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0
props = regionprops(sahpe, 'Perimeter');
perim = props.Perimeter
perim = 10.2140
% or you could count the number of perimeter pixels.
perim = nnz(bwperim(sahpe))
perim = 7
% Or you could run along the border computing the distance to the last
% pixel.
boundaries = bwboundaries(sahpe);
b = boundaries{1};
x = b(:, 2);
y = b(:, 1);
% Tack on end
x = [x; x(1)];
y = [y; y(1)];
perim = sum(sqrt(diff(x) .^ 2 + diff(y) .^ 2))
perim = 10.4853

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by