OpenCV中的reshape

OpenCV中关于reshape的定义如下:


reshape有两个参数:

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

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

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

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

#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
int main()
{
	cv::Mat testMat = cv::Mat::zeros ( 5, 3, CV_8UC3 );
	std::cout << "size of testMat: " << testMat.rows << " x " << testMat.cols << std::endl;
	std::cout<<"testMat = "<<testMat<<std::endl;
	cv::Mat result = testMat.reshape ( 0, 3 );
	std::cout << " size of original testMat: " << testMat.rows << " x " << testMat.cols << std::endl;
	std::cout << " size of reshaped testMat: " << result.rows << " x " << result.cols << std::endl;
	std::cout << "result = " << result << std::endl;
	cv::waitKey(0);
	system("pause");
	return 0;
}
结果如下:



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

#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
int main()
{
	cv::Mat testMat = cv::Mat::ones ( 5, 3, CV_8UC3 );
	std::cout << "size of testMat: " << testMat.rows << " x " << testMat.cols << std::endl;
	std::cout<<"testMat = "<<testMat<<std::endl;
	cv::Mat result = testMat.reshape ( 0, 6 );
	std::cout << " size of original testMat: " << testMat.rows << " x " << testMat.cols << std::endl;
	std::cout << " size of reshaped testMat: " << result.rows << " x " << result.cols << std::endl;
	std::cout << "result = " << result << std::endl;
	cv::waitKey(0);
	system("pause");
	return 0;
}
因为行和列的乘积不相等

结果如下:



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

可以这样:

unsigned char v11[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; 
cv::Mat A = cv::Mat(3, 4, CV_8U, v11); 
cv::Mat B = A.reshape(1, 12);  
但不能这样:

cv::Mat testMat = cv::Mat::zeros ( 5, 3, CV_8UC3 );
std::cout << "size of testMat: " << testMat.rows << " x " << testMat.cols << std::endl;

testMat.reshape ( 0, 1 );
std::cout << " size of reshaped testMat: " << testMat.rows << " x " << testMat.cols << std::endl;









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值