opencv仿射变换和透视变换(二)实践篇

一、仿射变换

举例:基于离散点求最小外接轮廓

其主要思路是先把图像二值化,得到一系列离散的前景像素点集合,然后利用轮廓的最小外接矩形函数,得到偏斜的矩形大小与角度,通过仿射变换完成校正。代码实现如下:

int main()
{
	Mat src, gray,dst;
	src = imread("D:\\cv_study\\Exercise\\文字倾斜\\text.png");
	cvtColor(src, gray, CV_BGR2GRAY);
	threshold(gray, dst, 0, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU);
	vectorpoints;
	findNonZero(dst, points);
	RotatedRect box = minAreaRect(points);
	double angle = box.angle;
	if (angle < -45.)
		angle += 90.;
	printf("angle : %.2f\n", angle);
	Point2f vertices[4];
	box.points(vertices);
	for (int i = 0; i < 4; ++i)
		line(src, vertices[i], vertices[(i + 1) % 4], Scalar(0, 0, 255), 2);
	Mat rot_mat = getRotationMatrix2D(box.center, angle, 1);
	Mat rotated;
	warpAffine(src, rotated, rot_mat, src.size(), cv::INTER_CUBIC, 0, Scalar(255, 255, 255));
	waitKey();
    return 0;
}

opencv仿射变换和透视变换(二)实践篇_第1张图片

二、透视变换

透视变换的一般过程:读入图片,获取边界点,定义目标边界点,获取转换矩阵,执行转换。

int main()
{
	Mat src = imread("D:\\cv_study\\Exercise\\Perspective Transformation\\1.jpg");
	vectorsrc_coners(4);
	src_coners[0] = Point2f(13, 134);
	src_coners[1] = Point2f(271, 24);
	src_coners[2] = Point2f(180, 411);
	src_coners[3] = Point2f(398, 362);
	circle(src, src_coners[0], 3, Scalar(0, 0, 255), 3, 8);
	circle(src, src_coners[1], 3, Scalar(0, 0, 255), 3, 8);
	circle(src, src_coners[2], 3, Scalar(0, 0, 255), 3, 8);
	circle(src, src_coners[3], 3, Scalar(0, 0, 255), 3, 8);
	vectordst_coners(4);
	dst_coners[0] = Point2f(0, 300);
	dst_coners[1] = Point2f(0, 0);
	dst_coners[2] = Point2f(400, 300);
	dst_coners[3] = Point2f(400, 0);
	Mat warpMatrix = getPerspectiveTransform(src_coners, dst_coners);
	Mat dst;
	warpPerspective(src, dst, warpMatrix, dst.size(), INTER_LINEAR, BORDER_CONSTANT);
	waitKey();
    return 0;
}

opencv仿射变换和透视变换(二)实践篇_第2张图片

 

---

参考文献:

https://blog.csdn.net/zhangjunp3/article/details/80318533

https://blog.csdn.net/zhangjunp3/article/details/80036310

 

你可能感兴趣的:(OpenCV/Halcon)