图像中最长的线

时间:2016-02-29 12:56:58

标签: performance opencv line detection

我要在图像中找到线条,所以我使用霍夫变换来做到这一点。 但是现在我试图找到图像中最长的一行(我的图像中必须存在最长的一行),有没有什么方法可以做到这一点而不牺牲计算速度?

using namespace std;
using namespace cv;

int main()
{
VideoCapture cap("D:\\DataBox\\v0.avi");

if (!cap.isOpened())
    cout << "fail to open!" << endl; //return -1;
else
    cout << "Video Load Succeed" << endl;

while (true)
{
    cout << "----------------------------------------------------" << endl;

    Mat src;
    cap >> src;
    pyrDown(src, src, Size(src.cols / 2, src.rows / 2));
    pyrDown(src, src, Size(src.cols / 2, src.rows / 2));

    cvtColor(src, src, CV_BGR2GRAY);

    Mat tsrc;
    threshold(src, tsrc, 90, 255, THRESH_BINARY_INV);

    Mat grad_x, grad_y;
    Mat abs_grad_x, abs_grad_y;
    Mat sobel;
    int scale = 1;
    int delta = 0;
    int ddepth = CV_16S;
    Sobel(tsrc, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
    convertScaleAbs(grad_x, abs_grad_x);
    Sobel(tsrc, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT);
    convertScaleAbs(grad_y, abs_grad_y);
    addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, sobel);

    vector<Vec2f> lines;
    int threshold = 250;
    HoughLines(sobel , lines, 1, CV_PI / 180, threshold, 0, 0);

    Mat cdst;
    cvtColor(sobel, cdst, CV_GRAY2BGR);

    for (size_t i = 0; i < lines.size(); i++)
    {
        float rho = lines[i][0], theta = lines[i][1];
        Point pt1, pt2;
        double a = cos(theta), b = sin(theta);
        double x0 = a*rho, y0 = b*rho;
        pt1.x = cvRound(x0 + 1000 * (-b));
        pt1.y = cvRound(y0 + 1000 * (a));
        pt2.x = cvRound(x0 - 1000 * (-b));
        pt2.y = cvRound(y0 - 1000 * (a));
        line(cdst, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
    }

    imshow("Video", cdst);
    waitKey(30);
}

}

0 个答案:

没有答案