Search code examples
c#emgucvcontourangle

CvInvoke.MinAreaRect(contour) returns the wrong angle


I have a contour of a number plate and I want to check if it's tilted or not. I used CvInvoke.MinAreaRect(contour) but it always returns the angle == -90 even when the plate is obviously tilted, you can see the contour I draw in the picture below.

return values

contour draw

original image

Does anyone know what happened and solution for my problem?

Here is the code:

Image<Gray, byte> gray = new Image<Gray, byte>("2.PNG");
Image<Gray, byte> adaptive_threshold_img = gray.ThresholdAdaptive(new Gray(255), AdaptiveThresholdType.GaussianC, ThresholdType.BinaryInv, 11, new Gray(2));

VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
Mat hier = new Mat();
CvInvoke.FindContours(adaptive_threshold_img, contours, hier, RetrType.Tree, ChainApproxMethod.ChainApproxSimple);

double max_area = 0;
VectorOfPoint max_contour = new VectorOfPoint();

for (int i = 0; i < contours.Size; i++)
{
    double temp = CvInvoke.ContourArea(contours[i]);
    if (temp > max_area)
    {
        max_area = temp;
        max_contour = contours[i];
    }
}

VectorOfVectorOfPoint contour_to_draw = new VectorOfVectorOfPoint(max_contour);
CvInvoke.DrawContours(gray, contour_to_draw, 0, new MCvScalar(255), 2);

CvInvoke.Imshow("plate", gray);

RotatedRect plate_feature = CvInvoke.MinAreaRect(max_contour);

CvInvoke.WaitKey();
CvInvoke.DestroyAllWindows();

Solution

  • Try CvInvoke.threshold() instead of gray.ThresholdAdaptive(). Set proper threshold and you'll get better contour than before.