Deskew Image使用拟合椭圆opencv

时间:2017-11-30 22:57:28

标签: opencv image-rotation ellipse skew

我试图使用opencv的fitellipse返回的角度来对二进制阈值图像进行偏斜校正(包含“数字”)。

我尝试(此处未显示)对返回的图像使用各种变通方法,但图像中的数字从不垂直对齐,如结果所示。

enter image description here enter image description here

System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

int affineFlags = WARP_INVERSE_MAP|INTER_LINEAR;
Mat input = Imgcodecs.imread("4.png");
Mat grayImage = new Mat(input.size(), CV_8UC1 );

// convert the frame in gray scale
Imgproc.cvtColor(input, grayImage, Imgproc.COLOR_BGR2GRAY);

Core.bitwise_not(grayImage, grayImage);
Mat threshold = new Mat(grayImage.rows(), grayImage.cols(),grayImage.type());
Imgproc.threshold(grayImage, threshold, 0, 255, THRESH_OTSU);

Imgcodecs.imwrite("threshold.png", threshold);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();

Imgproc.findContours(threshold, contours, new Mat(), Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);

double angle=0;

for(MatOfPoint mp : contours)
{
    //RotatedRect rr = Imgproc.minAreaRect(new MatOfPoint2f(mp.toArray()));

    if(mp.total() > 35) // Cheat to find the biggest contour.
    {
        RotatedRect elipse = Imgproc.fitEllipse(new MatOfPoint2f(mp.toArray()));
        Imgproc.ellipse(input, elipse, new Scalar(0,255,0));
        angle = elipse.angle;               
    }

}

Imgcodecs.imwrite("elipse.png", input);

Point center = new Point(threshold.cols() /2 ,threshold.rows()/2);

Mat rotMat = Imgproc.getRotationMatrix2D(center,angle , 1.0 );
Mat imgOut = Mat.zeros(input.rows(), input.cols(), input.type());
Imgproc.warpAffine(threshold, imgOut, rotMat, imgOut.size(), affineFlags);
Imgcodecs.imwrite("Rotated.png", imgOut);

Original Elipse

0 个答案:

没有答案