Why is my copyTo function Not copying the mask to the correct Mat?

asked 2016-01-13 09:59:49 -0500

Solace gravatar image

I started with the following image, named rgbaMat4Mask.bmp:

enter image description here

Then I converted it to HSV, and then did inRange() to find contours, and got the following Mat named maskedMat:

enter image description here

Then I went on to draw the first contour (the bigger one), on a newly created empty Mat named newMatWithMask, which has been given the same size as that of the first image I started with:

enter image description here

So far so good, but the problem starts now. I created a new Mat and gave it the same size as that of the first contour (the bigger one), and then set its background color to new Scalar(120, 255, 255). Then I copied the newMat4MaskFinished to it using copyTo function. But neither is the size of the resulting Mat same as that of the contour, nor is its background color set to new Scalar(120, 255, 255) which is blue.

enter image description here

It is rather an image with size same as that of the entire mask, and has a black background. why? What am I doing wrong?

public void doProcessing(View view) {
        // READING THE RGBA MAT
        Mat rgbaMat4Mask = Highgui.imread("/mnt/sdcard/DCIM/rgbaMat4Mask.bmp");

        // CONVERTING TO HSV
        Mat hsvMat4Mask = new Mat();
        Imgproc.cvtColor(rgbaMat4Mask, hsvMat4Mask, Imgproc.COLOR_BGR2HSV);
        Highgui.imwrite("/mnt/sdcard/DCIM/hsvMat4Mask.bmp", hsvMat4Mask);//check

        // CREATING A FILTER/MASK FOR RED COLORED BLOB
        Mat maskedMat = new Mat();
        Core.inRange(hsvMat4Mask, new Scalar(0, 100, 100), new Scalar(10, 255, 255), maskedMat);
        Highgui.imwrite("/mnt/sdcard/DCIM/maskedMat.bmp", maskedMat);// check

        // COPYING THE MASK TO AN EMPTY MAT
        // STEP 1:
        List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
        Imgproc.findContours(maskedMat, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);

        //STEP 2: 
        Mat newMat4Mask = new Mat(rgbaMat4Mask.rows(), rgbaMat4Mask.cols(), CvType.CV_8UC1);
        newMat4Mask.setTo(new Scalar(0));
        Imgproc.drawContours(newMat4Mask, contours, 0, new Scalar(255), -1);//TODO Using -1 instead of CV_FILLED.
        Highgui.imwrite("/mnt/sdcard/DCIM/newMatWithMask.bmp", newMat4Mask);// check


        //STEP 3
        Log.i(TAG, "HAPPY rows:"+contours.get(0).rows()+"   columns:"+contours.get(0).cols());
        Mat newMatwithMaskFinished = new Mat(contours.get(0).rows(), contours.get(0).cols(), CvType.CV_8UC3);
        newMatwithMaskFinished.setTo(new Scalar(120, 255, 255));
        rgbaMat4Mask.copyTo(newMatwithMaskFinished, newMat4Mask);
        Highgui.imwrite("/mnt/sdcard/DCIM/newMatwithMaskFinished.bmp", newMatwithMaskFinished);//check*/
    }
edit retag flag offensive close merge delete