00001 #include "opencv2/highgui/highgui.hpp"
00002 #include "opencv2/imgproc/imgproc.hpp"
00003
00004 #include <iostream>
00005
00006 using namespace cv;
00007 using namespace std;
00008
00009 void help()
00010 {
00011 cerr << "\nThis program demonstrates line finding with the Hough transform.\n"
00012 "Call:\n"
00013 "./houghlines <img1 img2 ...>" << endl;
00014 }
00015
00016 float lineLength2D (int x1, int y1, int x2, int y2)
00017 {
00018 float dist = sqrt ((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2));
00019 return dist;
00020 }
00021
00022 int main(int argc, char** argv)
00023 {
00024
00025 if (argc == 1)
00026 {
00027 help();
00028 exit(2);
00029 }
00030 for (int image = 1; image < argc; image++)
00031 {
00032 const char* filename = argv[image];
00033
00034 Mat src = imread(filename, 0);
00035 if(src.empty())
00036 {
00037 cerr << "Image %s " << filename << "read failed" << endl;
00038 }
00039
00040 int min_line_length = 120;
00041 int max_line_gap = 10;
00042 int dilate_iter = 8;
00043 int erode_iter = 2;
00044
00045 Mat dst, cdst, dilated, eroded, dilated2, harris;
00046 Canny(src, dst, 50, 200, 3);
00047 dilate(dst, dilated, Mat(), Point(-1,-1), dilate_iter);
00048
00049 erode(dilated, eroded, Mat(), Point(-1,-1), erode_iter);
00050
00051
00052 cvtColor(eroded, cdst, CV_GRAY2BGR);
00053
00054
00055 harris = Mat::zeros (eroded.rows, eroded.cols, CV_32FC1);
00056 cornerHarris(eroded, harris, 7, 3, 0.1);
00057 for (int i = 0; i < harris.rows; i++)
00058 {
00059 for (int j = 0; j < harris.cols; j++)
00060 {
00061 if (harris.at <float> (i, j) > 0.02)
00062 {
00063 cerr << i << "," << j << endl;
00064
00065 circle(cdst, cvPoint(j, i), 5, cvScalar(0, 255, 0));
00066 }
00067 }
00068
00069 }
00070
00071 double * min_r = new double;
00072 double * max_r = new double;
00073 minMaxLoc (harris, min_r, max_r);
00074
00075 cerr << "min: " << *min_r << " max: " << *max_r << endl;
00076 delete min_r;
00077 delete max_r;
00078
00079 vector<Vec4i> lines;
00080 HoughLinesP(eroded, lines, 1, CV_PI/180, 50, min_line_length, max_line_gap );
00081 for( size_t i = 0; i < lines.size(); i++ )
00082 {
00083 Vec4i l = lines[i];
00084 float length = lineLength2D (l[0], l[1], l[2], l[3]);
00085 float angle = atan2 (l[3] - l[1], l[2] - l[0]) * 180 / CV_PI;
00086 if (length < 180 && (((80.0 < angle) && (angle < 110.0)) || ((-1.0 < angle) && (angle < 1.0))))
00087 {
00088 cv::Scalar color(std::rand() % 256, std::rand() % 256, std::rand() % 256);
00089 line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), color, 3, CV_AA);
00090
00091
00092 cerr << "angle: " << angle << endl;
00093 cerr << "length: " << length << endl;
00094 }
00095 }
00096
00097
00098 imshow("source", dilated);
00099 imshow("detected lines", cdst);
00100
00101
00102
00103 waitKey();
00104 }
00105 return 0;
00106 }
00107