对整个垫子图像进行排序并在 OpenCV 中存储索引

sort whole Mat image and store indices in OpenCV?

本文关键字:OpenCV 索引 存储 排序 图像      更新时间:2023-10-16

这个问题不是这个问题的重复

我想对整个Mat image进行排序并存储类似于MatLab's [B , Ix] = sort(A);的索引

但是在 openCV 中,sort() 和 sortIdx() 仅适用于 EACH_ROWEACH_COLUMN

问题:那么,如何对整个Mat进行排序并将Indices也存储在 openCV 中?

PS:我想得到以下内容:

输入 =

2 0

4 1

dst_index =

1

1

2

2

dst_sorted =

0 1

2 4

有一个解决方案,但只有当图像在内存中连续时,它才有效。通常情况下,除非您的图像只是较大图像的投资回报率。您可以使用函数 isContinuous 来检查这一点。诀窍是创建使用与原始图像相同的内存缓冲区的 Mat,但不是将其视为 N 行和 M 列,而是将其视为 1 行和 M*N 列。这可以通过整形功能来完成。

Mat sameMemoryNewShape = image.reshape(1, 1);

现在你可以在sameMemoryNewShape上使用sort()或sortIdx()。

基于"Michael Burdinov"的解决方案,以下内容应该有效。

Mat A = (Mat_<uchar>(3, 4) << 0, 5, 2, 5, 2, 4, 9, 12, 3, 12, 11, 1); // example matrix
Mat B; //storing the 1D index result
Mat C = A.reshape(1, 1); //as mentioned by Michael Burdinov
sortIdx(C, B, SORT_EVERY_ROW + SORT_ASCENDING);
for (int i = 0; i < B.cols; i++) //from index 0 to index rows * cols of the original image
{
    int val =  B.at<int>(0, i); //access B, which is in format CV_32SC1
    int y = val / A.cols; //convert 1D index into 2D index
    int x = val % A.cols;
    std::cout << "idx " << val << " at (x/y) " << x << "/" << y
              << " is " << (int) A.at<uchar>(y, x) << endl;
}

请注意,结果B以 CV_32SC1(32 位整数)为单位。不考虑这可能会导致"奇怪"的行为,并可能导致1 0 0 0