1

Is there any function in C++ or opencv that can do the same operation as numpy flatten() function does ??

I think my question was vague. I am trying to use K-means segmentation in C++ opencv environment, there is an example given in python here http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_ml/py_kmeans/py_kmeans_opencv/py_kmeans_opencv.html

center = np.uint8(center) res = center[label.flatten()]

I have been able to do most of the operation until this flatten thing in C++ The dimension of label is 921600 X 1 which I also get in C++ as well. Center dimension is 4X3 matrix. I guess the trick here is to get all the label value specific to center value. so at the end "res" becomes 921600 X 3 .

So my question is How do i do this in C++ with opencv ?

Thanks

  • 3
    Isn't 921600 X 1 matrix already a flat array? – user7860670 May 01 '17 at 21:18
  • `np.flatten` just returns a new array with the same data buffer, but a new 1d shape. Well, technically, `ravel()` returns a `view`, `flatten` a copy. So the details of how it works depends on the structure of numpy arrays and their shape. Without knowing more about the `C++` matrix/array structure, we can't give a similar answer. – hpaulj May 01 '17 at 21:20
  • @hpaulj I guess my question was very vague, I have updated my question now – Hemang Purohit May 02 '17 at 16:23
  • So it's really more of an `opencv` question, working with the C++ code rather than the Python interface. – hpaulj May 02 '17 at 16:32
  • yeah do you have any idea?? – Hemang Purohit May 02 '17 at 19:01

2 Answers2

1

So I have figured this out, there is no straight or 1 line solution of this ( if there is let me know haha)

res = center[label.flatten()] 

can be performed with following in C++ opencv

for(int i = 0; i<labels.rows ; i++)
{
  if(labels.at<int>(i) == 0) { 
    res.push_back(centers.row(0));
  } else if(labels.at<int>(i) == 1) {
      res.push_back(centers.row(1)); 
  } else if(labels.at<int>(i) == 2) {
      res.push_back(centers.row(2)); 
  } else{
      res.push_back(centers.row(3));
  } 
}

Thank you .

1

Old question but just in case someone ends up here, the correct answer is reshape method of the Mat class. Check OpenCV docs for more: https://docs.opencv.org/4.3.0/d3/d63/classcv_1_1Mat.html#a4eb96e3251417fa88b78e2abd6cfd7d8

Here is an example function that performs flattening:

cv::Mat Flatten(const cv::Mat& mat)
{
    return mat.reshape(1, 1);
}
Amin
  • 11
  • 4