Can't get OpenCV's warpPerspective to work on Android

一个人想着一个人 提交于 2019-11-29 07:28:09

Found it, the problem was in these lines:

Mat perspectiveTransform = new Mat(3, 3, CvType.CV_32FC1);
Core.perspectiveTransform(startM, endM, perspectiveTransform);

Which should be replaced by this:

Mat perspectiveTransform = Imgproc.getPerspectiveTransform(startM, endM);

I had some problems with your code, so I made changes until I get a working version, here is my code if someone had problems with the question code:

Bitmap warp(Bitmap image, Point topLeft, Point topRight, Point bottomLeft, Point bottomRight) {
    int resultWidth = (int)(topRight.x - topLeft.x);
    int bottomWidth = (int)(bottomRight.x - bottomLeft.x);
    if(bottomWidth > resultWidth)
        resultWidth = bottomWidth;

    int resultHeight = (int)(bottomLeft.y - topLeft.y);
    int bottomHeight = (int)(bottomRight.y - topRight.y);
    if(bottomHeight > resultHeight)
        resultHeight = bottomHeight;

    Mat inputMat = new Mat(image.getHeight(), image.getHeight(), CvType.CV_8UC1);
    Utils.bitmapToMat(image, inputMat);
    Mat outputMat = new Mat(resultWidth, resultHeight, CvType.CV_8UC1);

    List<Point> source = new ArrayList<>();
    source.add(topLeft);
    source.add(topRight);
    source.add(bottomLeft);
    source.add(bottomRight);
    Mat startM = Converters.vector_Point2f_to_Mat(source);

    Point ocvPOut1 = new Point(0, 0);
    Point ocvPOut2 = new Point(resultWidth, 0);
    Point ocvPOut3 = new Point(0, resultHeight);
    Point ocvPOut4 = new Point(resultWidth, resultHeight);
    List<Point> dest = new ArrayList<>();
    dest.add(ocvPOut1);
    dest.add(ocvPOut2);
    dest.add(ocvPOut3);
    dest.add(ocvPOut4);
    Mat endM = Converters.vector_Point2f_to_Mat(dest);

    Mat perspectiveTransform = Imgproc.getPerspectiveTransform(startM, endM);

    Imgproc.warpPerspective(inputMat, outputMat, perspectiveTransform, new Size(resultWidth, resultHeight));

    Bitmap output = Bitmap.createBitmap(resultWidth, resultHeight, Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(outputMat, output);
    return output;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!