【问题标题】:sort whole Mat image and store indices in OpenCV?对整个 Mat 图像进行排序并在 OpenCV 中存储索引?
【发布时间】:2014-03-01 15:40:02
【问题描述】:

这道题不是this question的重复题

我想对整个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

【问题讨论】:

    标签: c++ matlab opencv image-processing


    【解决方案1】:

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

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

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

    【讨论】:

    • @Micheal:谢谢,排序工作正常,我能够为上述输入获得`0 1 2 4`,但对于索引,我得到1 0 0 0...怎么样?跨度>
    【解决方案2】:

    基于“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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多