When using OpenCV reshape and gets this error:
OpenCV Error: Image step is wrong (The matrix is not continuous, thus its number of rows can not be changed) in unknown function,
Let’s look at the documentation of the reshape function, Wrong parameters can also cause this error
According to the documentation the signature is
Mat Mat::reshape(int cn, int rows=0) const
With the following meaning of the arguments:
- cn – New number of channels. If the parameter is 0, the number of channels remains the same.
- rows – New number of rows. If the parameter is 0, the number of rows remains the same.
Note that the number of columns is implicit — it’s calculated from the existing matrix properties and the two parameters.
According to this, the code
data = mu.reshape(5, 5);
creates a 5-channel matrix of 5 rows and 1 column.
In order to reshape you matrix to a single channel 5×5 matrix, you have to do the following:
data = mu.reshape(1, 5);
Alternately, since the input matrix is already single channel, you can also use
data = mu.reshape(0, 5);
Besides:
there are 3 cases, where you’d get non-continuous Mat’s.
- it’s a roi
- bmp images and the like sometimes come padded
- you made a mat from a pixel pointer ( i.e some non-opencv capture device ) and that might be padded, too
since you have to reorder the memory in all those cases, checking for continuity and a clone() acll will solve it.
if ( ! mat.isContinuous() ) { mat = mat.clone(); }
参考:
https://stackoverflow.com/questions/36191118/opencv-reshape-function-does-not-work-properly
https://answers.opencv.org/question/22742/create-a-memory-continuous-cvmat-any-api-could-do-that/