gpt4 book ai didi

opencv - (OpenCV) 从分水岭快速计算邻接矩阵

转载 作者:太空宇宙 更新时间:2023-11-03 20:50:04 25 4
gpt4 key购买 nike

我想知道是否有比我在下面所做的更快的方法从分水岭图像计算区域邻接矩阵。

输入:具有从 1 到 N 标记的 N 个区域的分水岭图像。

输出:这N个区域的邻接矩阵。

<强>1。对于每个区域,计算相应的掩码并将所有掩码放入一个向量中:

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。定义一个函数来检查两个区域是否相邻:

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。计算邻接矩阵M:如果第i个区域和第j个区域相邻,则M[i][j] = M[j][i] =1,否则等于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;

最佳答案

下面是简单但非常快的:

Mat getAdjacencyMatrix(const int* klabels, int width, int height, int K)
/////* Input:
//// - int* klabels: the labeled watershed image (the intensity of the watershed lines is -1)
//// - int K: the number of superpixels (= kmax + 1)
//// * Output:
//// - Mat M: the adjacency matrix (M[i][j] = M[i][j] = 1 if the superpixels i and j are adjacent, and = 0 otherwise)
////*/

{
/// Create a KxK matrix and initialize to 0
Mat M(K, K, CV_32S, Scalar(0));

/// Scan the labeled image
for(int y=1; y < height-1; y++)
{
for(int x=1; x < width-1; x++)
{
// Get the label of the current pixel and the ones of its neighbors
int k = klabels[y*width + x];
int kleft = klabels[y*width + x - 1];
int kright = klabels[y*width + x + 1];
int kup = klabels[(y-1)*width + x];
int kdown = klabels[(y+1)*width + x];
if(k != kleft)
{
M.at<int>(k,kleft) =1;
M.at<int>(kleft,k) =1;
}
if(k != kright)
{
M.at<int>(k,kright) =1;
M.at<int>(kright,k) =1;
}
if(k != kup)
{
M.at<int>(k,kup) =1;
M.at<int>(kup,k) =1;
}
if(k != kdown)
{
M.at<int>(k,kdown) =1;
M.at<int>(kdown,k) =1;
}
}
}

return M;
}

关于opencv - (OpenCV) 从分水岭快速计算邻接矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17186912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com