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

本文展示了如何使用OpenCV的Mat类来输入矩阵并执行加法和乘法操作。通过Inputmatrix()函数获取用户输入的矩阵,然后在operate_function()函数中根据用户选择执行相应的矩阵运算。程序检查了矩阵尺寸是否适合进行加法或乘法,并返回运算结果。
#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,编译器会报错
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值