OpenCV 获取图片的最大的五个轮廓并将其摆正

int main()
{
    std::cout << "Hello World!\n"; 
	
	Mat srcImage = imread("11.jpg");
	if (srcImage.empty())
	{
		cout << "load image failed,please connect administrator";
		return -1;
	}
	

	Mat grayImage;
	cvtColor(srcImage, grayImage, COLOR_RGB2GRAY);
	//imwrite("1_gray.jpg", grayImage);
	//namedWindow("灰度图", CV_WINDOW_AUTOSIZE);
	//imshow("灰度图", grayImage);

	Mat binaryImage;
	threshold(grayImage, binaryImage, 0, 255, THRESH_OTSU);
	//imwrite("1_binary.jpg", binaryImage);
	//namedWindow("二值化图", CV_WINDOW_AUTOSIZE);
	//imshow("二值化图", binaryImage);

	Mat cannyImage;
	Canny(binaryImage, cannyImage, 3, 9, 3);

	vector > contours;
	vector hierarchy;
	findContours(cannyImage, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

	for (int i = 0; i < contours.size(); i++)
	{
		for (int j = i + 1; j < contours.size(); j++)
		{
			if (contourArea(contours[j]) > contourArea(contours[i]))
			{
				swap(contours[i], contours[j]);
			}
		}
	}

	Mat rectImage = Mat::zeros(srcImage.rows, srcImage.cols, srcImage.type());
	int drawCount = 5;
	if (contours.size() < 5) drawCount = contours.size();
	for (int i = 0; i < drawCount; i++)
	{
		drawContours(srcImage, contours, i, Scalar(0, 255, 0), 1, 8);
	}
	namedWindow("轮廓图", CV_WINDOW_AUTOSIZE);
	imshow("轮廓图", srcImage);
	
	for (int i = 0; i < drawCount; i++)
	{
		//cout < vertex[j].y)
				{
					swap(vertex[i], vertex[j]);
				}
			}
		}
		if (vertex[0].x > vertex[1].x)
		{
			swap(vertex[0], vertex[1]);
		}

		if (vertex[2].x < vertex[3].x)
		{
			swap(vertex[2], vertex[3]);
		}

		double Height = getDistance(vertex[1], vertex[2]);
		double width = getDistance(vertex[0], vertex[1]);

		Point2f dstVertex[4];
		dstVertex[0] = Point2f(0, 0);
		dstVertex[1] = Point2f(width, 0);
		dstVertex[2] = Point2f(width, Height);
		dstVertex[3] = Point2f(0, Height);
		Mat perspective_Tran = getPerspectiveTransform(vertex, dstVertex);

		Mat perspectiveImage = Mat::zeros(Height, width, srcImage.type());
		warpPerspective(srcImage, perspectiveImage, perspective_Tran, perspectiveImage.size());

		String strWindowName = "outTranMat" + to_string(i);
		namedWindow(strWindowName);
		imshow(strWindowName, perspectiveImage);
	}

	waitKey(0);
}

 

你可能感兴趣的:(OpenCV)