OpenCV 检测 ROI,创建 submat 并复制到原始 mat

adh*_*dhg 0 java opencv roi mat

我正在尝试将图像中所有人的脸变成灰色。虽然我可以检测到他们的脸部并将其灰色化为较小的垫子,但我无法将灰色的脸部“复制”到原始垫子上。这样最终的结果将是一个所有面都是灰色的垫子。

        faceDetector.detectMultiScale(mat, faceDetections);
        for (Rect rect : faceDetections.toArray()) 
        {   
            Rect rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);
            Mat imageROI = new Mat(mat,rectCrop);

            //convert to B&W 
            Imgproc.cvtColor(imageROI, imageROI, Imgproc.COLOR_RGB2GRAY);

            //Uncomment below will grayout the faces (one by one) but my objective is to have them grayed out on the original mat only.
            //Highgui.imwrite(JTestUtil.DESKTOP_PATH+"cropImage_"+(++index)+".jpg",imageROI);

            //add to mat? doesn't do anything :-(
            mat.copyTo(imageROI); 
        }
Run Code Online (Sandbox Code Playgroud)

Vas*_*nth 6

imageROI 是 3 或 4 通道图像。cvtColor 到 grey 给出单通道输出,并且 imageROI 对 mat 的引用可能被破坏。

使用缓冲区进行灰度转换并转换回 RGBA 或以 dst 作为 imageROI 的 RGB。

faceDetector.detectMultiScale(mat, faceDetections);
    for (Rect rect : faceDetections.toArray()) 
    {   
        Rect rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);
        //Get ROI
        Mat imageROI = mat.submat(rectCrop);

        //Move this declaration to onCameraViewStarted
        Mat bw = new Mat();

        //Use Imgproc.COLOR_RGB2GRAY for 3 channel image.
        Imgproc.cvtColor(imageROI, bw, Imgproc.COLOR_RGBA2GRAY);
        Imgproc.cvtColor(bw, imageROI, Imgproc.COLOR_GRAY2RGBA);
    }
Run Code Online (Sandbox Code Playgroud)

结果看起来像在此输入图像描述