Advertisement
Guest User

Untitled

a guest
Jul 1st, 2019
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.17 KB | None | 0 0
  1. //input matrix must be of type CV_8UC1
  2. void MatrixSort(Mat matrix)
  3. {
  4.     //matrix that stores the indices from sortIdx    
  5.     Mat matrixRowIndices(matrix.rows, matrix.cols, CV_8UC1);
  6.     sortIdx(matrix, matrixRowIndices, SORT_EVERY_ROW + SORT_ASCENDING);
  7.  
  8.     //reconstruate the sorted matrix from the row indices
  9.     Mat sortedRowmatrix(matrix.rows, matrix.cols, CV_8UC1);
  10.     for (int row = 0; row < matrixRowIndices.rows; row++)
  11.     {
  12.         for (int col = 0; col < matrixRowIndices.cols; col++)
  13.         {
  14.             int pukIDIndex = matrixRowIndices.at<int>(row, col);
  15.             int distance = matrix.at<uchar>(row, pukIDIndex);
  16.             sortedRowmatrix.at<uchar>(row, col) = distance;
  17.         }
  18.     }
  19.     cout << "sorted row indices = " << endl << matrixRowIndices << endl << endl;
  20.     cout << "sorted row matrix = " << endl << sortedRowmatrix << endl << endl;
  21.  
  22.     //sortIdx on the columns
  23.     Mat matrixColIndices(matrix.rows, matrix.cols, CV_8UC1);
  24.     sortIdx(sortedRowmatrix, matrixColIndices, SORT_EVERY_COLUMN + SORT_ASCENDING);
  25.     cout << "sorted col indices= " << endl << matrixColIndices << endl << endl;
  26.  
  27.     //reconstruate the rows and columns sorted matrix
  28.     Mat sortedColmatrix(matrix.rows, matrix.cols, CV_8UC1);
  29.     for (int row = 0; row < sortedColmatrix.rows; row++)
  30.     {
  31.         for (int col = 0; col < sortedColmatrix.cols; col++)
  32.         {
  33.             //sort rows gives back the indexes of columns in the matrix before sorting.
  34.             int pukIDIndex = matrixColIndices.at<int>(row, col);
  35.  
  36.             //sort columns gives back the indexes of rows in the matrix before sorting.
  37.             int pukIDIndex2 = matrixRowIndices.at<int>(row, col);
  38.  
  39.             int distance = matrix.at<uchar>(pukIDIndex, pukIDIndex2);
  40.             sortedColmatrix.at<uchar>(row, col) = distance;
  41.         }
  42.     }
  43.  
  44.     cout << "sorted matrix indices = " << endl << sortedColmatrix << endl << endl;
  45.  
  46.     //Below is the correctly sorted matrix with the normal sort algorithm. This works (but does not gives the indices I require.)
  47.     Mat sortedDistanceMat(matrix.rows, matrix.cols, CV_8UC1);
  48.     cv::sort(matrix, sortedDistanceMat, SORT_EVERY_ROW + SORT_ASCENDING);
  49.     cv::sort(sortedDistanceMat, sortedDistanceMat, SORT_EVERY_COLUMN + SORT_ASCENDING);
  50.  
  51.     cout << "correctly sorted matrix = " << endl << sortedDistanceMat << endl << endl;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement