0

I have been trying my heart out to figure what is wrong with my code. I am trying to sort a matrix, and then copy the last row of the sorted matrix. I cant view the contents in debugger (vs2015/vc++) so I need to save the contents to the disk, but I keep getting the error "No element name has been given" which I suspect is the result of an incorrect copy operation for the last row of the sorted matrix.

            cv::Mat sortedIndices;
            cv::sortIdx(Matrix, sortedIndices, CV_SORT_EVERY_COLUMN + CV_SORT_ASCENDING);
            cv::sort(Matrix, Matrix, CV_SORT_EVERY_COLUMN + CV_SORT_ASCENDING);
            auto cols = Matrix.size().width-1;
            auto maximums = Mat::zeros(1,cols+1,Matrix.type());
            Mat onlyRow = maximums.row(0);
            Matrix.row(Matrix.size().height - 1).copyTo(onlyRow);
            cv::FileStorage file("G:/3.txt", cv::FileStorage::WRITE);
            file << maximums;

I hope this is simple! enter image description here

Wajih
  • 793
  • 3
  • 14
  • 31

1 Answers1

1
  • You can sort the matrix directly calling sort, no need for sortIdx before that.
  • You can conveniently take a submatrix (e.g. a single row) using Range.
  • You should specify a name when saving something with FileStorage.

The following example should clarify this:

#include <opencv2\opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;

int main()
{
    RNG rng(1234);

    // Create a small random matrix
    Mat1b mat(3,5);
    randu(mat, Scalar(0), Scalar(255));

    // Sort the columns in ascending order
    cv::sort(mat, mat, SORT_EVERY_COLUMN + SORT_ASCENDING);

    // Just creating the header to last row
    // No actual data copy
    Mat1b lastCol(mat, Range(mat.rows - 1, mat.rows), Range::all());    

    {
        // Write last row to file
        FileStorage fout("test.yml", FileStorage::WRITE);
        fout << "some_name" << lastCol;
    }

    Mat1b lastCol2;
    {
        // Read last row from file
        FileStorage fin("test.yml", FileStorage::READ);
        fin["some_name"] >> lastCol2;
    }

    // lastCol and lastCol2 contain the same values now.

    return 0;
}

Since you mentioned that you need to dump data for debugging, please refer to this question. In short, you'll find Image Watch Visual Studio extension very useful.

Community
  • 1
  • 1
Miki
  • 40,887
  • 13
  • 123
  • 202