基于C++的opencv中Mat矩阵运算方法总结


文章目录

  • 前言
  • 一、Mat运算种类
    • 1.1 代数运算
    • 1.2 类型转换


前言

Mat类是目前opencv最为常用的图像数据格式,其优点在于无需手动开辟内存空间和实时释放,针对此类的各种运算方法有很多,本文按照各种运算方法的种类进行简单的总结和示例。


一、Mat运算种类

将Mat的运算简单的分为以下几种:

1.1 代数运算

    Mat imageadd = image1 + image2;
	//imshow("加法", imageadd);

	Mat imageadd1;
	Mat imageadd2;
	add(image1, image2, imageadd1);
	add(image1, 2, imageadd2);//函数重载
	//imshow("加法", imageadd);

	Mat imagesub = image1 - image2;//运算符重载
	//imshow("减法", imagesub);

	Mat imageAbsdiff;
	absdiff(image1, image2, imageAbsdiff);
	//imshow("减法绝对值", imageAbsdiff);

	Mat imagesub1;
	subtract(image1, image2, imagesub1);
	//imshow("减法", imagesub);

	Mat imageweighted;
	addWeighted(image1, 0.5, image2, 0.2, 50, imageweighted);
	//imshow("加权", imageweighted);

	Mat imagemultiply;
	multiply(image1, image2, imagemultiply, 1.0, CV_32FC1);
	//imshow("点乘", imagemultiply);

	Mat imagedivide;
	divide(image1, image2, imagedivide, 1.0, -1);
	//imshow("点除", imagedivide);

	//非
	Mat image2not;
	Mat mask = Mat::zeros(image2.size(), CV_8UC1);

	mask(Rect(200, 100, 200, 200)) = 255;

	bitwise_not(image2, image2not, mask);
	//imshow("非", image2not);

	//或
	Mat image2or;
	bitwise_or(image2, imagesub, image2or, mask);
	//imshow("或", image2or);
	
    //异或
	Mat image2xor;
	bitwise_xor(image2, imageadd2, image2xor, mask);
	imshow("异或", image2xor);

	//与
	Mat image2and;
	bitwise_and(image2, imagesub, image2and, mask);
	//imshow("与", image2and);

1.2 类型转换

    //---------------------数组和Mat------------------------
	int height = image.rows;
	int width = image.cols;

	//转16位一维数组
	uint8_t* array1 = new uint8_t[height * width * 3];
	for (int i = 0; i < height; i++)
	{
		for (int j = 0; j < width; j++)
		{
			for (int k = 0; k < 3; k++)
			{
				array1[i * width * 3 + j * 3 + k] = image.at(i, j)[k];
			}		
		}
	}

	Mat image3(height, width, CV_8UC3, array1);

你可能感兴趣的:(opencv,opencv,c++,矩阵)