【opencv机器视觉识别钢板层数备忘录】

原图:

首先想到的是基于边缘检测或者阈值分割的方法进行检测:


#include<opencv2\opencv.hpp>
#include<iostream>


using namespace std;
using namespace cv;



Mat org, dst, img, tmp;


void on_mouse(int event, int x, int y, int flags, void *)
{


	static Point pre_pt = (-1, -1);
	static Point cur_pt = (-1, -1);

	if (event == CV_EVENT_LBUTTONDOWN){
		pre_pt = Point(x, y);
	}

	else if (event == CV_EVENT_MOUSEMOVE && flags)//摁下左键,flags为1 
	{

		org.copyTo(tmp);
		cur_pt = Point(x, y);
		rectangle(tmp, pre_pt, cur_pt, Scalar(0, 255, 0, 0), 1, 8, 0);

		imshow("img", tmp);//画的时候显示框



	}



	else if (event == CV_EVENT_LBUTTONUP){


		org.copyTo(img);

		//cur_pt = Point(x, y);

		rectangle(img, pre_pt, cur_pt, Scalar(0, 255, 0, 0), 1, 8, 0);


		imshow("img", img);//画完后显示框



						   //img.copyTo(tmp);



		int width = abs(pre_pt.x - cur_pt.x);



		int height = abs(pre_pt.y - cur_pt.y);

		dst = org(Rect(min(cur_pt.x, pre_pt.x), min(cur_pt.y, pre_pt.y), width, height));
		namedWindow("dst");
		imshow("dst", dst);
		
	}
}



void main(){

	org = imread("234.jpg");

	org.copyTo(img);

	namedWindow("img");

	setMouseCallback("img", on_mouse, 0);

	imshow("img", img);
	waitKey();

	Mat src_gray;  
	cvtColor(dst, src_gray, CV_WINDOW_AUTOSIZE); 
	Mat src_canny; 
	Canny(src_gray, src_canny, 120, 200); 
	//threshold(src_gray, src_canny, 60, 255, THRESH_OTSU);
	//边缘检测  
	imshow("edge img", src_canny);   
	waitKey();

	//霍夫直线检测  
	vector<Vec4f> line_data;  
	HoughLinesP(src_canny, line_data, 1, CV_PI/180.0, 80, 10 ,20);    //把得到的直线显示在图中  
	Scalar color = Scalar(255, 0, 0);   
	for (size_t i = 0; i < line_data.size(); i++){    
		Vec4f temp = line_data[i];     
		line(dst, Point(temp[0], temp[1]), Point(temp[2], temp[3]), color, 2);  
	}   
	imshow("houghLinesP img", dst);

	waitKey(0);



}

效果差强人意,待优化:

 

接下来打算采用垂直投影和水平投影检测方法: 

猜你喜欢

转载自blog.csdn.net/qq_35054151/article/details/83586199