1 | initial version |
you could iterate over the white pixels only using findNonZero() , but this has the downside, that you have to check boundaries for each and every pixel, so imho, Brute Force does as well:
// let's collect "interesting points",
// if there's only one neighbour, it's an endpoint,
// if it has 3, it's a bifurcation(or T-junction),
// 4 neighbours denote an X-like crossing.
vector<Point> one, three, four;
// let's use Mat_<T> for easy (y,x) access (also, [0..1] range):
Mat_<uchar> bin = your_binary_img / 255;
// since we're checking 1 pixel neighbourhood,
// we need to spare 1 pixel border on each side:
for (int r=1; r<bin.rows-1; r++) {
for (int c=1; c<bin.cols-1; c++) {
uchar cen = bin(r,c);
if (cen==0) continue; // background
// now we just walk in a circle around the center pixel,
// and collect neighbours(starting top-left):
int neighbours = bin(r-1,c-1) + bin(r-1,c) + bin(r-1,c+1)
+ bin(r, c-1) + bin(r, c+1)
+ bin(r+1,c-1) + bin(r+1,c) + bin(r+1,c+1);
if (neighbours==1) one.push_back(Point(c,r));
if (neighbours==3) three.push_back(Point(c,r));
if (neighbours==4) four.push_back(Point(c,r));
}
}