I´m trying to compute the perimeter of a region in binary images. When a region is simply connected, i.e. it has no “holes”, everything is quite simple: I just check for every pixel if it belongs to the region and has at least a neighbor which is not belonging to the region… I have a variable that counts the number of pixels satisfying this condition.
In the case of region with holes I use a different way. I start from a pixel in the border and “jump” to a neighbor (increasing a counter) if it is itself a border pixel. The procedure, with some more quirks, ends when I go back to the initial pixels. Something like this:
int iPosCol = iStartCol, int iPosRow = iStartRow;
do
{
//check neighbors, pick point on the perimeter
//condition: value == label, pixel at the border.
check8Neighbors(iPosCol, iPosRow);
updatePixPosition(iPosCol, iPosRow);
}
while ( iPosC != iStartC || iPosR != iStartR );
The problem is that this method won´t work if the holes in the region are close to the border (1-pixel distance).
Are there standard ways of computing perimeter of non simply connected regions, or am I approaching the problem in the wrong way?
So here is my proposition:
Let’s assume you want to find the border of a black region(for simplicity).
First add one extra white column and one extra white row on all sides of the image. This is done to simplify corner cases and I will try to explain where it helps.
Next do a breadth first search from any pixel in your region. The edges in the graph are defined as connecting neighbouring cells in black color. By doing this BFS you will find all the pixels in your region. Now select the bottom-most(you can find it linerly) and if there are many bottom-most just select any of them. Select the pixel that is below it – this pixel is white for sure because: we selected the bottom-most of the pixels in our region and if the pixel was black the BFS would have visited it. Also there is a pixel below our bottom-most pixel because of the extra rows and columns we added.
Now do another BFS this time passing through white nighbouring pixels(again the fact that we added additional rows and columns helps here). This way we find a white region that surrounds the black region we are interested in from everywhere. Now all the pixels from the original black region that are neighbouring any of the pixels in the newly found white region are part of the border and only they are part of it. So you count those pixels and there you go – you have the perimeter.
The solution is complicated by the fact that we do not want to count borders of the holes as part of the perimeter – had this condition not be present we could just count all the pixels in the initial black region that are neighbouring any white pixel or the border of the image(here we do not need to add rows and colums).
Hope this answer helps.