如何使用OpenCV + Java裁剪图像

时间:2019-04-08 18:39:43

标签: java opencv opencv3.0

我正在尝试裁剪倾斜的图像,并从裁剪的部分创建新图像。

下面是原始图片

original image

我需要的是这张图片中的卡作为一张图片。

我已经遵循了一些示例,并且可以使用这种方法裁剪直线图像,但不适用于倾斜的图像。

    OpenCV.loadLocally();
    Mat imageMat = toMat(image);
    Mat imgSource = imageMat.clone();

    Mat imageHSV = new Mat(imgSource.size(), CvType.CV_8UC3);
    Mat imageBlurr = new Mat(imgSource.size(), CvType.CV_8UC3);
    Mat imageA = new Mat(imgSource.size(), CvType.CV_32F);
    Imgproc.cvtColor(imgSource, imageHSV, Imgproc.COLOR_BGR2GRAY);
    Imgproc.GaussianBlur(imageHSV, imageBlurr, new Size(5, 5), 0);
    //Imgproc.adaptiveThreshold(imageBlurr, imageA, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 7, 5);
    Imgproc.adaptiveThreshold(imageBlurr, imageA, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 29, 4);

    Imgcodecs.imwrite(filename+"Test.jpg", imageA);

    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Imgproc.findContours(imageA, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

    Vector<Mat> rectangles = new Vector<Mat>();
    Integer originalArea = imgSource.width() * imgSource.height();
    Integer cropArea = 0;
    Mat finalImage = new Mat();
    List<Point> source = new ArrayList<Point>();
     List<Point> target = new ArrayList<Point>();
     Rect rectPoint = null;
    for (int i = 0; i < contours.size(); i++) {
        if (Imgproc.contourArea(contours.get(i)) > 200) {
            Rect rect = Imgproc.boundingRect(contours.get(i));
            Rect rec = new Rect(rect.x, rect.y, rect.width, rect.height);
            Mat result = imageMat.submat(rec);
            if((cropArea >= originalArea) || ((cropArea<rect.width*rect.height) && (originalArea > rect.width*rect.height))) {
                finalImage = result;
                rectPoint = rec;
            }
            cropArea = rect.width * rect.height;
            Imgcodecs.imwrite(filename+i+".jpg", result);
        }
    }

    if(rectPoint!=null){
        source.add(new Point(rectPoint.x, rectPoint.y));
        source.add(new Point(rectPoint.x+rectPoint.width, rectPoint.y));
        source.add(new Point(rectPoint.x, rectPoint.y+rectPoint.height));
        source.add(new Point(rectPoint.x+rectPoint.width, rectPoint.y+rectPoint.height));


        target.add(new Point(0, 0));
        target.add(new Point(rectPoint.width, 0));
        target.add(new Point(0, rectPoint.height));
        target.add(new Point(rectPoint.width, rectPoint.height));

    }
    Mat m = new Mat();
    Mat s = Converters.vector_Point2f_to_Mat(source);
    Mat t = Converters.vector_Point2f_to_Mat(target);
    Mat p = Imgproc.getPerspectiveTransform(s, t);

    Imgproc.warpPerspective(finalImage, m, p, new Size(400,250));

0 个答案:

没有答案