Mat类编写矩阵乘法和加法操作

#include <iostream>
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;

Mat Inputmatrix(void)
{
	int row, column;
	float element;
	cout << "please input the first matrix(size):";
	cin >> row >> column;
	Mat matrix1(row, column, CV_32FC1);	//类型问题我没搞懂
	cout << "please input the matrix(elements):";
	for (int i = 0; i < matrix1.rows; ++i)
		for (int j = 0; j < matrix1.cols; ++j)
		{
			cin >> element;
			matrix1.at<float>(i, j) = element;
		}
	return matrix1;
}
Mat operate_function(Mat matrix1, Mat matrix2)
{
	char ch;
	cout << "please input the operation:";
	cin >> ch;
	cout << "output matrix is:" << endl;
	if (ch == '+')
	{
		if (matrix1.rows!= matrix2.rows || matrix1.cols != matrix2.cols)
		{
			cout << "error!";
			exit(0);
		}
		Mat matrixx = matrix1 + matrix2;
		return matrixx;
	}
	else if (ch == '*')
	{
		if (matrix1.cols != matrix2.rows)
		{
			cout << "error!";
			exit(0);
		}
		Mat matrixx = matrix1*matrix2;
		return matrixx;
	}
}

int main(int argc, char* argv[])
{
	Mat matrix1, matrix2;
	matrix1 = Inputmatrix();
	matrix2 = Inputmatrix();
	Mat matrix3 = operate_function(matrix1, matrix2);
	cout << matrix3;
	waitKey(0);
	return 0;
}

用Mat类不用自己考虑动态内存分配和释放,

*(矩阵相乘参与点乘的两个Mat矩阵的数据类型(type)只能是 CV_32F、 CV_64FC1、 CV_32FC2、 CV_64FC2 这4种类型中的一种。若选用其他类型,比如CV_8UC1,编译器会报错

版权声明:本文为qq_16968451原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。