OpenCV利用透视变换将斜体校正

	cv::Mat src = cv::imread("D:\\sxl\\处理图片\\斜体分割\\测试图\\正2.png");
	if (!src.data)
		return;
	//--------------旋转------------------------------------------------------
	double angle = 19;
	Point2f center(src.cols / 2, src.rows / 2);
	Mat rot = getRotationMatrix2D(center, angle, 1);
	Rect bbox = RotatedRect(center, src.size(), angle).boundingRect();

	rot.at(0, 2) += bbox.width / 2.0 - center.x;
	rot.at(1, 2) += bbox.height / 2.0 - center.y;

	//设置选择背景边界颜色:绿色 
	Scalar borderColor = Scalar(255, 255, 255);
	Mat dst;
	warpAffine(src, dst, rot, bbox.size(), INTER_LINEAR, BORDER_CONSTANT, borderColor);

	Mat gray, BinImg;
	if (dst.channels() == 3)
	{
		cvtColor(dst, gray, CV_BGR2GRAY);   //转换成灰度图
	}
	else
	{
		gray = dst;
	}
	//--------------旋转------------------------------------------------------


	vector not_a_rect_shape;
	not_a_rect_shape.push_back(Point(3, 82));
	not_a_rect_shape.push_back(Point(2, 276));
	not_a_rect_shape.push_back(Point(234, 191));
	not_a_rect_shape.push_back(Point(239, 1));
	// For debugging purposes, draw green lines connecting those points
	// and save it on disk
	const Point* point = ¬_a_rect_shape[0];
	int n = (int)not_a_rect_shape.size();
	Mat draw = gray.clone();
	polylines(draw, &point, &n, 1, true, Scalar(0, 255, 0), 3, CV_AA);
	imwrite("draw.jpg", draw);
	//  topLeft, topRight, bottomRight, bottomLeft
	cv::Point2f src_vertices[4];
	src_vertices[0] = not_a_rect_shape[0];
	src_vertices[1] = not_a_rect_shape[1];
	src_vertices[2] = not_a_rect_shape[2];
	src_vertices[3] = not_a_rect_shape[3];

	Point2f dst_vertices[4];
	dst_vertices[0] = Point(2, 2);
	dst_vertices[1] = Point(0, 194);
	dst_vertices[2] = Point(235, 190);
	dst_vertices[3] = Point(239, 1);
	Mat warpMatrix = getPerspectiveTransform(src_vertices, dst_vertices);
	cv::Mat rotated;
	warpPerspective(gray, rotated, warpMatrix, rotated.size(), INTER_LINEAR, BORDER_CONSTANT);
	// Display the image
	cv::namedWindow("Original Image");
	cv::imshow("Original Image", src);
	cv::namedWindow("warp perspective");
	cv::imshow("warp perspective", rotated);
	imwrite("result.jpg", src);
	cv::waitKey();
	return ;

效果图:
OpenCV利用透视变换将斜体校正_第1张图片
OpenCV利用透视变换将斜体校正_第2张图片
OpenCV利用透视变换将斜体校正_第3张图片

欢迎扫码关注我的微信公众号

在这里插入图片描述

你可能感兴趣的:(#,OpenCV其他)