How to find the ruler position from an image by using opencv?

c++, opencv, pixel

Solution

Here's what I've done:

- A bit improved your green range because yours is not detecting green color - it's detecting many other colors.

- Find contours on image.

- Find contour with area bigger than 100.

- Find up and low points of contour.

- Draw these 2 points.

Mat src = imread("input.png"), tmp;
cvtColor(src, tmp, CV_BGR2HSV_FULL);
inRange(tmp, Scalar(50, 50, 50), Scalar(70, 255, 255), tmp);

vector<vector<Point> > contours;
findContours(tmp, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

int upY = INT_MAX, lowY = 0, upX, lowX;
for (int i=0; i<contours.size(); i++)
{
    if (contourArea(contours[i]) > 100)
    {
        for (int j=0; j<contours[i].size(); j++)
        {
            if (contours[i][j].y > lowY)
            {
                lowY = contours[i][j].y;
                lowX = contours[i][j].x;
            }
            if (contours[i][j].y < upY)
            {
                upY = contours[i][j].y;
                upX = contours[i][j].x;
            }
        }

        cout << "low = (" << lowX << ", " << lowY << ")"<<  endl
             << "up  = (" << upX << ", " << upY << ")"<<  endl;
        break;
    }
}

circle(src, Point(lowX, lowY), 3, Scalar(255, 0, 255));
circle(src, Point(upX, upY), 3, Scalar(255, 0, 255));

imshow("Window", src);
waitKey();

Here's result:

Problem

I have to find the ruler position from an image by using opencv.I am able to detect the color of the ruler(green). How can i read all the pixel from an image and get the upper and lower position of ruler. ``` void findrulerPosition(cv::Mat image, int indx) { std::stringstream ss;//create a stringstream ss << indx;//add number to the stream cv::Mat hsv; cvtColor(image, hsv, CV_BGR2HSV); String filename = OUTPUT_FOLDER + "hsv" + ss.str() + ".png"; imwrite(filename, hsv ); cv::Mat hsvbw; inRange(hsv, cv::Scalar(30,0,0), cv::Scalar(80, 255, 255), hsvbw); //inRange(hsv, cv::Scalar(12,255,255), cv::Scalar(23, 245, 255), hsvbw); //inRange(image, cv::Scalar(0,64,255), cv::Scalar(0, 207, 255), hsvbw); filename = OUTPUT_FOLDER + "hsvbw" + ss.str() + ".png"; imwrite(filename, hsvbw ); vector<vector<Point> > contours; findContours(hsvbw.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); cv::Mat dst = Mat::zeros(image.size(), image.type()); drawContours(dst, contours, -1, Scalar::all(255), CV_FILLED); this->cmpddst &= dst; dst &= image; this->cmpddst &= image; filename = OUTPUT_FOLDER + "cmpddst" + ss.str() + ".png"; imwrite(filename, this->cmpddst ); filename = OUTPUT_FOLDER + "dst" + ss.str() + ".png"; imwrite(filename, dst ); ``` }

Original source