Khashayar
Khashayar

Reputation: 2034

Tracing a pixel in a Picture

I have a picture of a road like this

enter image description here

Now I want to look only at the bottom of the picture pic up the white lane marking on the left side and follow it till I cover the whole shape.

I don not want to use the findContour function cause I will get a lot of bad data and it's not time efficient to go through all the possibilities to figure the right one.

I want the algorithm to be fast so just follow and starting point on the bottom and go up and follow the line in the same picture.

Now my question is there any openCV functionality available to track a pixel or maybe a little dash line to follow the line?

What do you suggest? Thanks in advance

Upvotes: 2

Views: 549

Answers (1)

Tobias Hermann
Tobias Hermann

Reputation: 10936

If you know a seed point the segmentation can easily and quite fast (about 0.001s on my current machine) be done via floodFill:

#include <opencv2/opencv.hpp>

#include <boost/chrono/include.hpp>

#include <iostream>
#include <ctime>

std::vector<std::vector<cv::Point>> segment_lane(const cv::Mat& img, const cv::Point& seed, int tol)
{
    cv::Mat mask = cv::Mat::zeros(img.rows + 2, img.cols + 2, CV_8UC1);
    cv::floodFill(img, mask, seed, 255, 0, cv::Scalar(tol, tol, tol), cv::Scalar(tol, tol, tol), 4 + (255 << 8) + cv::FLOODFILL_MASK_ONLY + cv::FLOODFILL_FIXED_RANGE);
    std::vector<std::vector<cv::Point>> contours;
    cv::findContours(mask, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(-1, -1));
    return contours;
}

int main()
{
    cv::Mat img = cv::imread("Ph2PK.png");

    auto start = boost::chrono::system_clock::now();
    auto contours = segment_lane(img, cv::Point(21, 461), 40);
    auto end = boost::chrono::system_clock::now();

    boost::chrono::duration<double> elapsed_seconds = end - start;
    std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";

    cv::drawContours(img, contours, 0, cv::Scalar(255, 0, 0), 2);
    cv::imshow("img", img);
    cv::imwrite(out.png", img);
    cv::waitKey(0);
}

If the following contour is not enough, try to adjust the tolerance values or leave out FLOODFILL_FIXED_RANGE.

contour

Upvotes: 2

Related Questions