0

i'm trying to gray the faces of all people in an image. While I can detect their faces and gray them into smaller mat(s), I'm unable to 'copy' the grayed faces to the original mat. Such that the end result will have a mat with all faces in gray.

        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); 
        }
adhg
  • 10,437
  • 12
  • 58
  • 94

1 Answers1

6

imageROI is a 3 or 4 channel image. cvtColor to gray gives a single channel output and the imageROI's reference to mat is probably destroyed.

Use a buffer for gray conversion and convert back to RGBA or RGB with dst as 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);
    }

The result looks like enter image description here

Vasanth
  • 1,238
  • 10
  • 14
  • Thanks @Vasanth for the answer. Given an image with faces, my objective is to convert all the faces in the image to B&W. In my code, I'm able to convert the faces one by one (as images) but unable to have them all together in the original image. Thanks again! (I think the problem is somewhere in the channel as you wrote) – adhg Mar 15 '16 at 19:37
  • 1
    Accept the answer if it solves your issue. Might be useful to someone else too :). – Vasanth Mar 16 '16 at 10:50