Fast adjacency matrix computation from watershed

asked 2013-06-18 10:16:02 -0600

Nesbit gravatar image

updated 2013-06-19 11:53:24 -0600

I would like to know if there is a faster way, than what I have done below, to compute the region adjacency matrix from a watershed image.

Input: watershed image with N regions labeled from 1 to N.

Output: adjacency matrix of these N regions.

1. For each region, compute the corresponding mask and put all masks into a vector:

vector<Mat> masks;    
for(int i = 0; i < N; i++ )
{    
// Create the corresponding mask
Mat mask;    
compare(wshed, i+1, mask, CMP_EQ);

// Dilate to overlap the watershed line (border)
dilate(mask, mask, Mat());

// Add to the list of masks
masks.push_back(mask);    
}

2. Define a function to check if two regions are adjacent:

bool areAdjacent(const Mat& mask1, const Mat& mask2)
{
    // Get the overlapping area of the two masks
    Mat m;
    bitwise_and(mask1, mask2, m);

    // Compute the size of the overlapping area
    int size = countNonZero(m);

    // If there are more than 10 (for example) overlapping pixels, then the two regions are adjacent
    return (size > 10);
}

3. Compute the adjacency matrix M: if the i-th region and the j-th region are adjacent, then M[i][j] = M[j][i] =1, otherwise they are equal to 0.

Mat M = Mat::zeros(N, N, CV_8U);
for(int i = 0; i < N-1; i++)
    {
        for(int j = i+1; j < N; j++)
        {
            if(areAdjacent(masks[i], masks[j]))
            {
                M.at<uchar>(i,j) = 1;
                M.at<uchar>(j,i) = 1;
            }
        }
    }
    return M;
edit retag flag offensive close merge delete

Comments

Hi , step 3,i think it's identity matrix,right?It true , then you can use: Mat::eye

wuling gravatar imagewuling ( 2013-06-19 11:49:19 -0600 )edit

Actually, M is the adjacency matrix and need to be computed.

Nesbit gravatar imageNesbit ( 2013-06-19 11:54:59 -0600 )edit
1

I've answered myself but have to wait 2 days to be able to post it.

Nesbit gravatar imageNesbit ( 2013-06-19 12:05:03 -0600 )edit
wuling gravatar imagewuling ( 2013-06-19 12:09:03 -0600 )edit