一、介绍

    transform():Transposes a matrix.

    perspectiveTransform():Performs the perspective matrix transformation of vectors.

    warpAffine():Applies an affine transformation to an image.

    warpPerspective():Applies a perspective transformation to an image.

二、transform

	Mat m23 = Mat::zeros(2, 3, CV_32FC1);  // 2*2  2*3
	m23.at<float>(0, 0) = 1.0;
	m23.at<float>(0, 2) = 2.0;
	m23.at<float>(1, 1) = 3.0;
	m23.at<float>(1, 2) = 4.0;
	cout << "m23 = " << endl << m23 << endl;

	// src.channel = m.cols 或 m.cols - 1
	// 当src.channel=m.cols - 1时,src增加一通道,值为1
	Mat src = Mat::zeros(4, 4, CV_8UC3);
	for (int i = 0; i < src.rows; i++)
	{
		for (int j = 0; j < src.cols; j++)
		{
			for (int k = 0; k < src.channels(); k++)
			{
				src.at<Vec3b>(i, j)[k] = 2 * i + j + k;
			}
		}
	}
	cout << "src = " << endl << src << endl;

	Mat dst;
	cv::transform(src, dst, m23);  // dst.channel = m.rows
	cout << "dst = " << endl << dst << endl;

三、perspectiveTransform

	Mat m33 = Mat::zeros(3, 3, CV_32FC1);  // 3*3  4*4
	m33.at<float>(0, 0) = 1.0;
	m33.at<float>(0, 2) = 2.0;
	m33.at<float>(1, 1) = 3.0;
	m33.at<float>(1, 2) = 4.0;
	m33.at<float>(2, 2) = 2.0;
	cout << "m33 = " << endl << m33 << endl;

	// src.channel = m.cols - 1   src增加一个通道,值为1
	Mat src = Mat::zeros(2, 2, CV_32FC2);
	for (int i = 0; i < src.rows; i++)
	{
		for (int j = 0; j < src.cols; j++)
		{
			for (int k = 0; k < src.channels(); k++)
			{
				src.at<Vec2f>(i, j)[k] = 2.0f * i + j + k;
			}
		}
	}
	cout << "src = " << endl << src << endl;

	// dst.size = src.size   dst.channels = src.channels
	// 3*3 * 3*1 = 3*1   4*4 * 4*1 = 4*1    m * v1 = v2
	// m33 * [x,y,1] = [x',y',w], 使用[x'/w, y'/w]作为dst的结果
	Mat dst;
	cv::perspectiveTransform(src, dst, m33);
	cout << "dst = " << endl << dst << endl;

四、warpAffine

	// 仿射变换矩阵 M 2*3 --- 旋转、平移、缩放
	cv::Point2f center = Point2f(img.cols / 2.0f, img.rows / 2.0f);  // 旋转中心
	double angle = 10.0;  // 旋转角度,逆时针为正
	double scale = 1.2;   // 缩放尺寸
	Mat M = cv::getRotationMatrix2D(center, angle, scale);
	int bound_w = (img.rows * fabs(sin(angle * CV_PI / 180)) + img.cols * fabs(cos(angle * CV_PI / 180))) * scale;
	int bound_h = (img.rows * fabs(cos(angle * CV_PI / 180)) + img.cols * fabs(sin(angle * CV_PI / 180))) * scale;
	M.at<double>(0, 2) += (bound_w - img.cols) / 2.0;  // x平移
	M.at<double>(1, 2) += (bound_h - img.rows) / 2.0;  // y平移
	Mat dst;
	cv::warpAffine(img, dst, M, cv::Size(bound_w, bound_h));

 

 

五、warpPerspective

	// 透视变换矩阵 M 3*3 --- 投影
	Point2f ptsF[4], ptsT[4];
	ptsF[0] = Point2f(163, 191);
	ptsF[1] = Point2f(735, 160);
	ptsF[2] = Point2f(872, 936);
	ptsF[3] = Point2f(112, 980);
	ptsT[0] = Point2f(163, 191);
	ptsT[1] = Point2f(735, 191);
	ptsT[2] = Point2f(735, 936);
	ptsT[3] = Point2f(163, 936);
	Mat M = cv::getPerspectiveTransform(ptsF, ptsT);
	Mat dst;
	cv::warpPerspective(img, dst, M, img.size());

 

 

Logo

分享最新、最前沿的AI大模型技术,吸纳国内前几批AI大模型开发者

更多推荐