Search code examples
opencvopencv3.0angle

Read angle from a 360 degre meter


I have a meter that I have managed to extract using openCV Image of the meter in different positions The white thing in the middle is a pointer that can go from 0-360.

My code:

void readAngleOfMeter(Mat image, int number)
{
    cvtColor(image, image, COLOR_BGR2GRAY);
    inRange(image, Scalar(255, 255, 255), Scalar(255, 255, 255), image);

    vector<Vec2f> lines;
    HoughLines(tmp, lines, 1, CV_PI / 360, 30, 0, 0);

    if (lines.size() == 0) {
        cout << "No lines found" << endl;
        return;
    }

    float thetasum = 0;
    for (size_t i = 0; i < lines.size(); i++)
    {
        float theta = lines[i][1];
        thetasum += theta;
    }
    thetasum = thetasum / static_cast<int>(lines.size());
    cout << "Theta " << thetasum << endl;
}

My problem is now that I want to read the angle of the meter. So I thought about using the average angle of each line but the problem is that it doesn't work because a line can be interpreted in two ways (example 90 is the same as 270) and also when it goes from 360 to 0.

Any ideas?


Solution

  • You don't even need to use Hough transform. Write a loop that iterates from 0 to 360 degress in 1 degree increments looking at pixels in a circle centred at the centre of the image. Remember the angle of the first white pixel and when you find the next black one going around the circle, take its angle and average with the starting angle.

    You may want to blur a little first or dilate the meter needle to fill any gaps.

    Experiment with the radius - a smaller radius will give you less resolution as the needle appears thicker there. A larger radius will give you more resolution but you risk missing the needle as it is thinner further from the centre.