opencv 36.Samples

1.切边

//1.切边
Mat src_sample1;
void sampleTrackChange(int,void*);
void Sample1Affine(int, void*);
void StartOp3::Sample1()
{
	
	src_sample1 = imread("../../Images/25.jpg", 1);
	if (!src_sample1.data) {
		cout << "文件打开失败" << endl;
	}
	char title[] = "original";
	namedWindow(title);
	imshow(title, src_sample1);

	int thresholdVal = 60;
	int maxThresholdVal = 255;
	createTrackbar("thresh value", title, &thresholdVal, maxThresholdVal, Sample1Affine);
	Sample1Affine(thresholdVal, 0);
	/*createTrackbar("thresh value",title, &thresholdVal,maxThresholdVal,sampleTrackChange);
	sampleTrackChange(60,0);*/



}


void Sample1Affine(int value, void*) {
	Mat src_gray;
	cvtColor(src_sample1, src_gray, COLOR_BGR2GRAY);
	Mat src_canny;
	Canny(src_gray, src_canny, value, value * 2, 3, false);

	vector<vector<Point>> contours;
	vector<Vec4i> hierarchy;
	findContours(src_canny, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));

	float maxw = 0;
	float maxh = 0;
	double degree = 0;
	for (size_t t = 0; t < contours.size(); t++) {
		RotatedRect minRect = minAreaRect(contours[t]);
		degree = abs(minRect.angle);
		if (degree > 0) {
			maxw = max(maxw, minRect.size.width);
			maxh = max(maxh, minRect.size.height);
		}
	}

	Rect ROI;
	Mat drawImg = Mat::zeros(src_sample1.size(), CV_8UC3);
	RNG rng(12345);
	for (size_t t = 0; t < contours.size(); t++) {
		RotatedRect minRect = minAreaRect(contours[t]);
		if (maxw == minRect.size.width && maxh == minRect.size.height) {
			degree = minRect.angle;
			ROI = minRect.boundingRect();
			Point2f pts[4];
			minRect.points(pts);
			Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
			for (int i = 0; i < 4; i++) {
				line(drawImg, pts[i], pts[(i + 1) % 4], color, 2, 8, 0);
			}
		}
	}

	imshow("drawImg", drawImg);
	//if (ROI.width > 0 && ROI.height > 0) {
	//	Mat roiImg = src_sample1(ROI);
	//	imshow("ROIImg", roiImg);
	//}


	Point2f center(src_sample1.cols / 2, src_sample1.rows / 2);
	Mat rotm = getRotationMatrix2D(center, degree, 1.0);
	Mat dst;
	warpAffine(src_sample1, dst, rotm, src_sample1.size(), INTER_LINEAR, 0, Scalar(255, 255, 255));
	imshow("Correct Image", dst);


}


void sampleTrackChange(int value, void*) 
{
	Mat src_gray;
	cvtColor(src_sample1, src_gray, COLOR_BGR2GRAY);
	Mat src_canny;
	Canny(src_gray,src_canny, value, value*2, 3,false);

	vector<vector<Point>> contours;
	vector<Vec4i> hierarchy;
	findContours(src_canny,contours,hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0,0));

	//RNG g_rng(12345);
	//Mat drawImg = Mat::zeros(src_canny.size(), CV_8UC3);
	//for (int i = 0; i < contours.size(); i++)
	//{
	//	Scalar color = Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255));//任意值
	//	drawContours(drawImg, contours, i, color, 2, 8, hierarchy, 0, Point());
	//}



	int minwidth = src_sample1.cols*0.75;
	int minheight = src_sample1.rows*0.75;
	RNG rng(1234);
	Mat drawImg = Mat::zeros(src_sample1.size(),CV_8UC3);
	Rect ROI;
	for (size_t t=0; t<contours.size(); t++)
	{
		RotatedRect minRect = minAreaRect(contours[t]);
		float degree = abs(minRect.angle);
		if (minRect.size.width>minwidth && minRect.size.height>minheight && minRect.size.height<(src_sample1.rows-5))
		{

			Point2f pts[4];
			minRect.points(pts);
			ROI = minRect.boundingRect();
			Scalar color = Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255));

			for (int i = 0; i < 4; i++) {
				line(drawImg,pts[i],pts[(i+1) % 4],color, 2, 8, 0);
			}

		}
	}

	imshow("drawImg",drawImg);

	if (ROI.width >0 && ROI.height >0) {
		Mat roiImg = src_sample1(ROI);
		imshow("ROIImg", roiImg);
	}


}

2.直线检测

//2.直线检测
void StartOp3::Sample2()
{
	Mat src_sample2;
	src_sample2 = imread("../../Images/26.jpg", IMREAD_GRAYSCALE);
	if (!src_sample2.data) {
		cout << "文件打开失败" << endl;
	}
	//char title[] = "original";
	//namedWindow(title);
	//imshow(title, src_sample2);

	Rect roi = Rect(10,10,src_sample2.cols-16,src_sample2.rows-16);
	Mat roiImg = src_sample2(roi);
	imshow("roiImg",roiImg);

	//threshold
	Mat src_binary;
	threshold(roiImg, src_binary,0, 255, THRESH_BINARY_INV|THRESH_OTSU);
	imshow("src_binary", src_binary);

	//morphology
	Mat src_morphology;
	Mat kernel = getStructuringElement(MORPH_RECT, Size(25,1), Point(-1,-1));
	morphologyEx(src_binary, src_morphology, MORPH_OPEN, kernel, Point(-1,-1), 1, 0);
	/*imshow("src_morphology", src_morphology);*/

	//dilate
	kernel = getStructuringElement(MORPH_RECT, Size(3,3), Point(-1,-1));
	dilate(src_morphology, src_morphology, kernel, Point(-1,-1));
	imshow("src_morphology", src_morphology);

	//Hough lines
	vector<Vec4i> lines;
	HoughLinesP(src_morphology, lines, 1, CV_PI/180.0, 30, 20.0, 0);
	Mat src_resImg = roiImg.clone();
	cvtColor(src_resImg, src_resImg, COLOR_GRAY2BGR);
	for (size_t i=0; i<lines.size(); i++)
	{
		Vec4i eachline = lines[i];
		line(src_resImg, Point(eachline[0],eachline[1]), Point(eachline[2], eachline[3]), Scalar(0, 0, 255), 2, 8, 0);

	}
	imshow("src_resImg", src_resImg);
}

3.对象提取

//3.对象提取
void StartOp3::Sample3()
{
	Mat src_sample3;
	src_sample3 = imread("../../Images/27.jpg", IMREAD_GRAYSCALE);
	if (!src_sample3.data) {
		cout << "文件打开失败" << endl;
	}
	imshow("src_sample3", src_sample3);

	//threshold
	Mat src_threshold;
	threshold(src_sample3, src_threshold, 0, 255, THRESH_BINARY|THRESH_OTSU);
	imshow("src_threshold", src_threshold);

	//morphology
	Mat src_morphology;
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3,3), Point(-1,-1));
	morphologyEx(src_threshold, src_morphology, MORPH_CLOSE, kernel, Point(-1,-1), 2);
	imshow("src_morphology close", src_morphology);

	morphologyEx(src_morphology, src_morphology, MORPH_OPEN, kernel, Point(-1, -1), 2);
	imshow("src_morphology open", src_morphology);

	//contours operate
	vector<vector<Point>> contours;
	vector<Vec4i> hireachy;
	findContours(src_morphology, contours, hireachy, RETR_TREE, CHAIN_APPROX_NONE, Point());

	Mat resultImage = Mat::zeros(src_morphology.size(), CV_8UC3);
	Mat res_show = src_sample3.clone();
	cvtColor(res_show, res_show, COLOR_GRAY2BGR);
	for (size_t i = 0; i < contours.size(); i++) {
		//通过面积过滤部分干扰项
		double area = contourArea(contours[i]);
		if (area<100)continue;
		//通过横纵比过滤出圆
		Rect rect = boundingRect(contours[i]);
		float ratio = float(rect.width) / float(rect.height);
		if (ratio<1.1 && ratio>0.9) {
			//thickness写-1表示填充
			drawContours(resultImage, contours, i, Scalar(0,0,255), -1,8, Mat(), 0, Point());
			//printf("circle length : %f\n", arcLength(contours[t], true));
			int x = rect.x + rect.width / 2;
			int y = rect.y + rect.height / 2;
			//draw circle center
			circle(res_show, Point(x,y), 2, Scalar(0, 0, 255), 2, 8, 0);
			//draw circle
			circle(res_show, Point(x, y), rect.width / 2, Scalar(0, 0, 255), 2, 8, 0);
		}

	}
	imshow("src_morphology res", res_show);

}

4.对象计数

//4.对象计数
void StartOp3::Sample4()
{
	Mat src_sample4;
	src_sample4 = imread("../../Images/28.jpg", 0);
	if (!src_sample4.data) {
		cout << "文件打开失败" << endl;
	}
	imshow("src_sample3", src_sample4);

	//threshold
	Mat dst_threshold;
	threshold(src_sample4, dst_threshold, 0,255, THRESH_BINARY| THRESH_TRIANGLE);
	imshow("dst_threshold", dst_threshold);

	//morphology
	Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5), Point(-1, -1));
	dilate(dst_threshold, dst_threshold, kernel, Point(-1,-1), 2);
	imshow("dilate image", dst_threshold);

	//distanceTransform
	Mat dst_distancetransform;
	dst_threshold = ~ dst_threshold;
	distanceTransform(dst_threshold, dst_distancetransform, DIST_L2, 5);
	normalize(dst_distancetransform, dst_distancetransform, 0, 1.0, NORM_MINMAX);
	imshow("dst_distancetransform", dst_distancetransform);

	//adaptiveThreshold
	Mat dst_8U;
	dst_distancetransform.convertTo(dst_8U, CV_8U);
	adaptiveThreshold(dst_8U, dst_8U, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 91, 0.0);
	//normalize(dst_8U, dst_8U, 0, 255, NORM_MINMAX);
	kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
	//erode(dst_8U, dst_8U, kernel, Point(-1, -1), 1);
	dilate(dst_8U, dst_8U, kernel, Point(-1, -1), 1);
	imshow("dst_8U", dst_8U);

	 //find contours
	vector<vector<Point>> contours;
	findContours(dst_8U, contours, CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);

	// draw result
	Mat markers = Mat::zeros(src_sample4.size(), CV_8UC3);
	RNG rng(12345);
	for (size_t t = 0; t < contours.size(); t++) {
		drawContours(markers, contours, static_cast<int>(t), Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)),
			-1, 8, Mat());
	}
	printf("number of corns : %d", contours.size());
	imshow("Final result", markers);

}

5.透视变换

//5.透视校正
void StartOp3::Sample5()
{

	Mat src_sample5;
	src_sample5 = imread("../../Images/29.jpg", 1);
	if (!src_sample5.data) {
		cout << "文件打开失败" << endl;
	}
	imshow("src_sample3", src_sample5);


	//threshold
	Mat dst_gray,dst_threshold;
	cvtColor(src_sample5, dst_gray, COLOR_BGR2GRAY);
	threshold(dst_gray, dst_threshold, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
	imshow("dst_threshold", dst_threshold);

	//morphology
	Mat dst_morphology;
	Mat kernel = getStructuringElement(MORPH_RECT, Size(5,5), Point(-1,-1));
	morphologyEx(dst_threshold, dst_morphology, MORPH_CLOSE, kernel, Point(-1,-1),3);
	imshow("dst_morphology", dst_morphology);

	//find contours
	bitwise_not(dst_morphology, dst_morphology, Mat());
	vector<vector<Point>> contours;
	vector<Vec4i> hierarchy;
	findContours(dst_morphology, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());

	int width = src_sample5.cols;
	int height = src_sample5.rows;
	Mat drawImage = Mat::zeros(src_sample5.size(), CV_8UC3);
	for (size_t t = 0; t < contours.size(); t++) {
		Rect rect = boundingRect(contours[t]);
		if (rect.width > width / 2 && rect.width < width - 5) {
			drawContours(drawImage, contours, static_cast<int>(t), Scalar(0, 0, 255), 2, 8, hierarchy, 0, Point());
		}
	}
	imshow("contours", drawImage);


	//HoughlinesP
	Mat dst_gray_contours;
	vector<Vec4i> lines;
	int accu= min(width*0.5, height*0.5);
	cvtColor(drawImage, dst_gray_contours, COLOR_BGR2GRAY);
	HoughLinesP(dst_gray_contours, lines, 1, CV_PI/180.0, height*0.6, accu);
	Mat linesImage = Mat::zeros(src_sample5.size(), CV_8UC3);
	RNG rng(12345);
	for (size_t t = 0; t < lines.size(); t++) {
		Vec4i ln = lines[t];
		line(linesImage, Point(ln[0], ln[1]), Point(ln[2], ln[3]), Scalar(rng.uniform(0,255), rng.uniform(0, 255), rng.uniform(0, 255)), 2, 8, 0);
	}
	printf("number of lines : %d\n", lines.size());
	imshow("lines image", linesImage);

	//locate four lines
	int deltah = 0;
	int deltaw = 0;
	Vec4i topLine, bottomLine;
	Vec4i leftLine, rightLine;
	for (int i = 0; i < lines.size(); i++) {
		Vec4i ln = lines[i];
		deltah = abs(ln[3] - ln[1]);
		deltaw = abs(ln[2] - ln[0]);
		if (deltah > height / 2.0 && deltaw<width/2.0) {

			if (ln[2]<width/2.0) {
				leftLine = lines[i];
			}
			else {
				rightLine = lines[i];
			}

		}
		if (deltah < height / 2.0 && deltaw > width / 2.0) {

			if (ln[1]< height/2.0) {
				topLine = lines[i];
			}
			else {
				bottomLine = lines[i];
			}

		}

		/*if (ln[3] < height / 2.0 && ln[1] < height / 2.0 && deltah < accu - 1) {
			if (topLine[3] > ln[3] && topLine[3] > 0) {
				topLine = lines[i];
			}
			else {
				topLine = lines[i];
			}
		}
		if (ln[3] > height / 2.0 && ln[1] > height / 2.0 && deltah < accu - 1) {
			bottomLine = lines[i];
		}
		if (ln[0] < width / 2.0 && ln[2] < width / 2.0) {
			leftLine = lines[i];
		}
		if (ln[0] > width / 2.0 && ln[2] > width / 2.0) {
			rightLine = lines[i];
		}*/
	}
	cout << "top line : p1(x, y) = " << topLine[0] << "," << topLine[1] << " p2(x, y) = " << topLine[2] << "," << topLine[3] << endl;
	cout << "bottom line : p1(x, y) = " << bottomLine[0] << "," << bottomLine[1] << " p2(x, y) = " << bottomLine[2] << "," << bottomLine[3] << endl;
	cout << "left line : p1(x, y) = " << leftLine[0] << "," << leftLine[1] << " p2(x, y) = " << leftLine[2] << "," << leftLine[3] << endl;
	cout << "right line : p1(x, y) = " << rightLine[0] << "," << rightLine[1] << " p2(x, y) = " << rightLine[2] << "," << rightLine[3] << endl;




	//fiting linear equation
	float k1, c1;
	k1 = float(topLine[3] - topLine[1]) / float(topLine[2] - topLine[0]);
	c1 = topLine[1] - k1 * topLine[0];
	float k2, c2;
	k2 = float(bottomLine[3] - bottomLine[1]) / float(bottomLine[2] - bottomLine[0]);
	c2 = bottomLine[1] - k2 * bottomLine[0];
	float k3, c3;
	k3 = float(leftLine[3] - leftLine[1]) / float(leftLine[2] - leftLine[0]);
	c3 = leftLine[1] - k3 * leftLine[0];
	float k4, c4;
	k4 = float(rightLine[3] - rightLine[1]) / float(rightLine[2] - rightLine[0]);
	c4 = rightLine[1] - k4 * rightLine[0];



	//intersection point
	Point p1; // 左上角
	p1.x = static_cast<int>((c1 - c3) / (k3 - k1));
	p1.y = static_cast<int>(k1*p1.x + c1);
	Point p2; // 右上角
	p2.x = static_cast<int>((c1 - c4) / (k4 - k1));
	p2.y = static_cast<int>(k1*p2.x + c1);
	Point p3; // 左下角
	p3.x = static_cast<int>((c2 - c3) / (k3 - k2));
	p3.y = static_cast<int>(k2*p3.x + c2);
	Point p4; // 右下角
	p4.x = static_cast<int>((c2 - c4) / (k4 - k2));
	p4.y = static_cast<int>(k2*p4.x + c2);

	cout << "p1(x, y)=" << p1.x << "," << p1.y << endl;
	cout << "p2(x, y)=" << p2.x << "," << p2.y << endl;
	cout << "p3(x, y)=" << p3.x << "," << p3.y << endl;
	cout << "p4(x, y)=" << p4.x << "," << p4.y << endl;

	circle(linesImage, p1, 2, Scalar(255, 0, 0), 2, 8, 0);
	circle(linesImage, p2, 2, Scalar(255, 0, 0), 2, 8, 0);
	circle(linesImage, p3, 2, Scalar(255, 0, 0), 2, 8, 0);
	circle(linesImage, p4, 2, Scalar(255, 0, 0), 2, 8, 0);

	imshow("four corners", linesImage);

	// Perspective transformation
	vector<Point2f> src_corners(4);
	src_corners[0] = p1;
	src_corners[1] = p2;
	src_corners[2] = p3;
	src_corners[3] = p4;

	vector<Point2f> dst_corners(4);
	dst_corners[0] = Point(0, 0);
	dst_corners[1] = Point(width, 0);
	dst_corners[2] = Point(0, height);
	dst_corners[3] = Point(width, height);

	// getPerspectiveTransform
	Mat resultImage;
	Mat warpmatrix = getPerspectiveTransform(src_corners, dst_corners);
	warpPerspective(src_sample5, resultImage, warpmatrix, resultImage.size(), INTER_LINEAR);
	namedWindow("Final Result", CV_WINDOW_AUTOSIZE);
	imshow("Final Result", resultImage);

}

6.对象提取与量测

//6.对象提取与测量
void StartOp3::Sample6()
{

	Mat src_sample6;
	src_sample6 = imread("../../Images/30.jpg", 1);
	if (!src_sample6.data) {
		cout << "文件打开失败" << endl;
	}
	imshow("src_sample3", src_sample6);

	//blur
	Mat dst_blur;
	GaussianBlur(src_sample6, dst_blur, Size(15,15), 0,0);
	imshow("dst_blur", dst_blur);

	//threshold
	Mat dst_gray, dst_threshold;
	cvtColor(dst_blur, dst_gray, COLOR_BGR2GRAY);
	threshold(dst_gray, dst_threshold, 0, 255, THRESH_BINARY|THRESH_TRIANGLE);
	imshow("dst_threshold", dst_threshold);

	//morphology
	Mat dst_morph;
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3,3), Point(-1,-1));
	morphologyEx(dst_threshold, dst_morph, MORPH_CLOSE, kernel, Point(-1, -1), 2);
	imshow("dst_morph", dst_morph);

	//find contours
	vector<vector<Point>> contours;
	vector<Vec4i> hierarchy;
	findContours(dst_morph, contours, hierarchy,RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
	Mat dst_drawImg=Mat::zeros(src_sample6.size(), CV_8UC3);
	for (size_t t = 0; t < contours.size(); t++) {
		Rect rect = boundingRect(contours[t]);
		if (rect.width < src_sample6.cols / 2) continue;
		if (rect.width > (src_sample6.cols - 20)) continue;
		double area = contourArea(contours[t]);
		double len = arcLength(contours[t], true);
		drawContours(dst_drawImg, contours, static_cast<int>(t), Scalar(0, 0, 255), 1, 8, hierarchy);
		printf("area  of star could : %f\n", area);
		printf("length  of star could : %f\n", len);
	}
	imshow("result", dst_drawImg);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值