opencv reshape函数说明

转自http://blog.csdn.net/yang6464158/article/details/20129991

reshape有两个参数:

其中,参数:cn为新的通道数,如果cn = 0,表示通道数不会改变。

参数rows为新的行数,如果rows = 0,表示行数不会改变。

注意:新的行*列必须与原来的行*列相等。就是说,如果原来是5行3列,新的行和列可以是1行15列,3行5列,5行3列,15行1列。仅此几种,否则会报错。

具体调用也很简单,代码如下所示:

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include <opencv/cv.h>  
  3. #include <opencv/highgui.h>  
  4. int main()  
  5. {  
  6.     cv::Mat testMat = cv::Mat::zeros ( 5, 3, CV_8UC3 );  
  7.     std::cout << "size of testMat: " << testMat.rows << " x " << testMat.cols << std::endl;  
  8.     std::cout<<"testMat = "<<testMat<<std::endl;  
  9.     cv::Mat result = testMat.reshape ( 0, 3 );  
  10.     std::cout << " size of original testMat: " << testMat.rows << " x " << testMat.cols << std::endl;  
  11.     std::cout << " size of reshaped testMat: " << result.rows << " x " << result.cols << std::endl;  
  12.     std::cout << "result = " << result << std::endl;  
  13.     cv::waitKey(0);  
  14.     system("pause");  
  15.     return 0;  
  16. }  

结果如下:

比如说:下面的情况就会报错:

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include <opencv/cv.h>  
  3. #include <opencv/highgui.h>  
  4. int main()  
  5. {  
  6.     cv::Mat testMat = cv::Mat::ones ( 5, 3, CV_8UC3 );  
  7.     std::cout << "size of testMat: " << testMat.rows << " x " << testMat.cols << std::endl;  
  8.     std::cout<<"testMat = "<<testMat<<std::endl;  
  9.     cv::Mat result = testMat.reshape ( 0, 6 );  
  10.     std::cout << " size of original testMat: " << testMat.rows << " x " << testMat.cols << std::endl;  
  11.     std::cout << " size of reshaped testMat: " << result.rows << " x " << result.cols << std::endl;  
  12.     std::cout << "result = " << result << std::endl;  
  13.     cv::waitKey(0);  
  14.     system("pause");  
  15.     return 0;  
  16. }  

因为行和列的乘积不相等

结果如下:



我们在使用reshape的时候一定不能用定义的Mat类型赋给原来的类型,必须重新定义一个新类。

可以这样:

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. unsigned char v11[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };   
  2. cv::Mat A = cv::Mat(3, 4, CV_8U, v11);   
  3. cv::Mat B = A.reshape(1, 12);    

但不能这样:

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
    1. cv::Mat testMat = cv::Mat::zeros ( 5, 3, CV_8UC3 );  
    2. std::cout << "size of testMat: " << testMat.rows << " x " << testMat.cols << std::endl;  
    3.   
    4. testMat.reshape ( 0, 1 );  
    5. std::cout << " size of reshaped testMat: " << testMat.rows << " x " << testMat.cols << std::endl;  
原文地址:https://www.cnblogs.com/fdd566/p/6410342.html