1

I have a 640 x 480 CV_8UC3 Mat image and want to perform the k-means segmentation. So I need to convert it to CV_32F (no problem here), reshape it, and run k-means.

The problem is reshape() does nothing:

cv::Mat colorMat;
image.convertTo (colorMat, CV_32FC3);
std::cout << colorMat.size () << "; ch: " << colorMat.channels () << std::endl; // [640 x 480]; ch: 3
colorMat.reshape (1, colorMat.rows * colorMat.cols); // Here I expect it to become [307200 x 3], 1 channel - each column representing a color component
std::cout << colorMat.size () << "; ch: " << colorMat.channels () << std::endl; // [640 x 480]; ch: 3

Am I doing something wrong?

Alex
  • 1,165
  • 2
  • 9
  • 27

1 Answers1

6

You need to assign the result of reshapeto a matrix:

colorMat = colorMat.reshape (1, colorMat.rows * colorMat.cols);

You can see here (second snippet) a complete example.

Community
  • 1
  • 1
Miki
  • 40,887
  • 13
  • 123
  • 202
  • Yes, I was just writing a similar answer having read [this question](http://stackoverflow.com/questions/13400239/reshaping-a-matrix-failed-in-opencv-2-4-3). They lack the return value descriptions in the documentation obviously... – Alex Feb 12 '17 at 10:46
  • Actually the [doc](http://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html#a4eb96e3251417fa88b78e2abd6cfd7d8) shows that the return value is a `Mat`, but probably it's not clear enough. – Miki Feb 12 '17 at 10:48