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

前端 未结 2 518
北恋
北恋 2020-12-18 07:08

I\'ve been struggling to implement a quad to quad system in my Android application. The aim is to let the user take a picture, add 4 cornerpoints and have that quad extracte

相关标签:
2条回答
  • 2020-12-18 07:39

    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;
    }
    
    0 讨论(0)
  • 2020-12-18 07:43

    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);
    
    0 讨论(0)
提交回复
热议问题