unity OpenCV生成mask 进行抠图

遮罩生成代码:

Mat MatMask(Texture2D imgTexture)
    {
        Mat imgMat = new Mat (imgTexture.height, imgTexture.width, CvType.CV_8UC4);
        Utils.texture2DToMat (imgTexture, imgMat);

        Mat grayMat = imgMat;
        Imgproc.cvtColor (grayMat, grayMat, Imgproc.COLOR_RGBA2GRAY);
        //        Imgproc.Canny (grayMat, grayMat, 50, 200);

        int thresh_size = (100 / 4) * 2 + 1;
        Imgproc.adaptiveThreshold (grayMat, grayMat, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, thresh_size,          thresh_size / thresholdValue);
        Imgproc.morphologyEx (grayMat, grayMat, Imgproc.MORPH_OPEN, new Mat ());

        Mat hierarchy = new Mat ();
        List<MatOfPoint> contours = new List<MatOfPoint> ();
        Imgproc.findContours (grayMat, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);// 找轮廓

        Mat hole = new Mat (grayMat.size (), CvType.CV_8U, new Scalar (0, 0, 0));

        Imgproc.drawContours (hole, contours, -1, new Scalar (255, 255, 255), -1);

        Texture2D newTexture2 = new Texture2D (imgMat.cols (), imgMat.rows (), TextureFormat.RGBA32, false);

        Utils.matToTexture2D (hole, newTexture2);

        //go2.GetComponent<Renderer> ().material.mainTexture = newTexture2;

        return hole;

    }

开始抠图:

void ChangeAlpha (Texture2D imgTexture) {

        Mat hole = MatMask(imgTexture);

        Mat imgMat = new Mat (imgTexture.height, imgTexture.width, CvType.CV_8UC4);
        Utils.texture2DToMat (imgTexture, imgMat);

        Mat crop = new Mat(imgMat.rows(), imgMat.cols(), CvType.CV_8UC3);

        imgMat.copyTo (crop,hole);

        newTexture = new Texture2D (imgMat.cols (), imgMat.rows (), TextureFormat.RGBA32, false);
        Utils.matToTexture2D (crop, newTexture);

        //go.GetComponent<Renderer> ().material.mainTexture = newTexture;
    }


猜你喜欢

转载自blog.csdn.net/lw450770448/article/details/56840702