I would like to know if there is a faster way than what I did below to calculate the adjacency matrix of the area from the watershed image.
Input: image of the watershed with N areas marked from 1 to N.
Output: The adjacency matrix of these N regions.
1. For each area, calculate the corresponding mask and put all the masks in the vector:
vector<Mat> masks; for(int i = 0; i < N; i++ ) {
2. Define a function to check if two areas are adjacent:
bool areAdjacent(const Mat& mask1, const Mat& mask2) {
3. Calculate the adjacency matrix M: if the ith region and the jth region are adjacent, then M [i] [j] = M [j] [i] = 1, otherwise they are 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;
source share