使用openCV在Android中的PerspectiveTransform和Crop Rectangle

时间:2015-06-29 03:57:05

标签: android opencv

我使用CvCameraViewListener2来从Android相机收到图像 我的程序检测到一个黄色矩形板 问题是在我知道矩形角的4个点后,我想裁剪矩形并显示在JavaCameraView
这是我的程序在检测矩形时的屏幕截图。

enter image description here

首先,我应用perspectiveTransform将图像转换为正确的视角。但结果非常糟糕,如

enter image description here

我不知道如何正确地做到这一点 以下是我的代码。

private Mat getTransform(Mat inputFrame, List<Point> corners) {
    Mat outputFrame = inputFrame.clone();
    //compute width of new image
    double widthA = Math.sqrt(Math.pow(corners.get(3).x - corners.get(2).x, 2) + Math.pow(corners.get(3).y - corners.get(2).y, 2));
    double widthB = Math.sqrt(Math.pow(corners.get(1).x - corners.get(0).x, 2) + Math.pow(corners.get(1).y - corners.get(0).y, 2));
    double maxWidth = max(widthA, widthB);

    // compute heigh of new image
    double heightA = Math.sqrt(Math.pow(corners.get(1).x - corners.get(3).x, 2) + Math.pow(corners.get(1).y - corners.get(3).y, 2));
    double heightB = Math.sqrt(Math.pow(corners.get(0).x - corners.get(2).x, 2) + Math.pow(corners.get(0).y - corners.get(2).y, 2));
    double maxHeight = max(heightA, heightB);

    Log.d(MAINTAG, "Width: " + maxWidth + ", Height: " + maxHeight);

    List<Point> output = new ArrayList<>();
    output.add(new Point(0, 0));
    output.add(new Point(0, maxHeight));
    output.add(new Point(maxWidth, maxHeight));
    output.add(new Point(maxWidth, 0));

    Mat inputMat = Converters.vector_Point2f_to_Mat(corners);
    Mat outputMat = Converters.vector_Point2f_to_Mat(output);

    Mat outputTransform = Imgproc.getPerspectiveTransform(inputMat, outputMat);

    Imgproc.warpPerspective(inputFrame, outputFrame, outputTransform, new Size(outputMat.width(), outputMat.height()), Imgproc.INTER_LINEAR);

    return outputFrame;

corners排列为topLeft,topRight,bottomLeft,bottomRight
在纠正透视后,屏幕会冻结!!!

其次,我想在修正其视角并在JavaCameraView中显示后裁剪矩形。我该怎么办?

感谢您提供所有解决方案和建议。

0 个答案:

没有答案