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

时间:2016-03-15 17:03:26

标签: java opencv mat roi

我试图让图像中所有人的脸部变灰。虽然我可以检测到他们的脸并将它们变成较小的垫子,但是我无法复制'灰色的面孔到原来的垫子。这样最终结果将具有所有面为灰色的垫子。

        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); 
        }

1 个答案:

答案 0 :(得分:1)

imageROI是3或4通道图像。 cvtColor to gray提供单个通道输出,imageROI对mat的引用可能已被破坏。

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

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);
    }

结果如enter image description here