Ask Your Question

Solace's profile - activity

2020-12-08 18:25:43 -0600 received badge  Popular Question (source)
2020-10-10 21:53:09 -0600 received badge  Student (source)
2020-05-19 10:04:31 -0600 received badge  Popular Question (source)
2020-01-07 02:08:48 -0600 received badge  Popular Question (source)
2019-06-06 17:20:56 -0600 received badge  Popular Question (source)
2016-07-23 10:03:13 -0600 commented answer Is it possible to overlay a transparent image over a live camera view, such that it is overlayed over the captured photo as well?

If I use addweighted method to overlay the image in the live camera preview, will the overlayed image also be added automatically to the photo I capture?

2016-07-23 06:33:19 -0600 commented question Is it possible to overlay a transparent image over a live camera view, such that it is overlayed over the captured photo as well?

@berak So if I wanted to draw it separately on the captured image, I wouldn't know the exact and precise locations of points and may be sizeas well.

2016-07-23 06:28:29 -0600 commented question Is it possible to overlay a transparent image over a live camera view, such that it is overlayed over the captured photo as well?

@berak I want the polygon to be at the exact same place in the captured image as it was in the live camera preview. For example, say the overlayed image was the boundary of a closed shape like a human's face (like in this image.), and in the live camera preview it is used to to guide a user where to place their face in the camera frame. Now in the image captured, I would want to merge that boundary lines into the captured image, and I would want them to be exactly where they were in the camera preview; I would not want the captured image having the face on one position, and the overlayed face-boundary displaced to somewhere else.

2016-07-23 04:59:00 -0600 asked a question Is it possible to overlay a transparent image over a live camera view, such that it is overlayed over the captured photo as well?

The transparent image I want to overlay is just the boundary of a polygon in black color, the rest of the image is transparent. Like this:

image description

Using OpenCV4Android, I want to overlay it over live camera preview, such that it is overlayed on the image captured as well (i.e. the polygon is blended over the image captured, I mean the polygon should become a part of the image captured.)

How can I achieve that?

ADDENDUM:

I would simply add the polygon to the live camera preview by overlaying the JavaCameraView (which is the widget which displays live camera preview/frames) with an ImageView (Android's image container widget) containing the transparent image to overlay; by placing them both sequentially in a FrameLayout, which automatically Z-orders widgets added to it. Then I would separately add the image to overlay into to captured photo.

But the challenge here is:

The polygon in the live camera preview/frames is a guide. Just like the following image has a guide for positioning the face before taking the picture.

image description

Then when the photo is captured, I want the polygon to be overlayed at EXACTLY the position on which it was when the photo was captured.

So how do I achieve this?

2016-06-26 19:35:31 -0600 commented question Why does calcHist() method create an empty black histogram Mat?

@sturkmen Sorry I was wrong in previous comment. nimages parameter of histPrepareImages() is not what I passed to calcHist() as numberOfBins. Rather, after carefully comparing the parameters of histPrepareImages() here, calcHist() here for C++, and the ones shown in Eclipse (IDE) Javadoc, I learnt that Android API does not have a int nimages argument for calcHist(). For Android API, the calcHist() is Imgproc.calcHist(images, channels, mask, hist, histSize, ranges);

2016-06-26 19:22:35 -0600 commented question Why does calcHist() method create an empty black histogram Mat?

@sturkmen That code is just like mine here in this question. But looking at the definition of histPrepareImages() - the method in which I have got the error of j < nimages according the the OpenCV Error statement in logcat - given on line 115 of this class tells me that nimages is the second arg, which is numberOfBins in my code. So it means there is something with my numOfBins argument to calcHist(). Can you look into Line 115 of that file and see what might have caused j to be less than numOfBins I passed and any hint on what is going wrong? I don't understand C++ or OpenCV well.

2016-06-26 18:48:31 -0600 commented question Why does calcHist() method create an empty black histogram Mat?

@sturkmen Thank you. I tried to write an Android version from the tutorial you pointed me too. But I am getting an here. If you have some time, could you have a look into my new question?

2016-06-26 18:44:38 -0600 asked a question Why am I getting this Assertion Failed error in my calcHist() call?

Using OpenCV4Android, I wanted to calculate, draw and display the histogram (in an ImageView) of the red color channel in a bgr image. I have tried to follow this Python (?) tutorial and imitate it using Android API. I have also logged out some simple statements after each step which tells me that the step has executed successfully. I get an OpenCV Error and through these log statements, I know that it has occured in my calcHist() call.

Following is from Logcat:

06-26 23:22:26.160: I/MainActivity(1299): GRANNY rgbaMat read successfully!
06-26 23:22:26.160: I/MainActivity(1299): GRANNY rgbaMatBitmap added to imageView successfully!
06-26 23:22:26.160: I/MainActivity(1299): GRANNY Color space converted to HSV successfully!
06-26 23:22:26.160: I/MainActivity(1299): GRANNY Core.split() carried out successfully!
06-26 23:22:26.164: E/cv::error()(1299): OpenCV Error: Assertion failed (j < nimages) in void cv::histPrepareImages(const cv::Mat *, int, const int *, const cv::Mat &, int, const int *, const float **, bool, vector<uchar *> &, vector<int> &, Size &, vector<double> &), file /hdd2/buildbot/slaves/slave_ardbeg1/50-SDK/opencv/modules/imgproc/src/histogram.cpp, line 148
06-26 23:22:26.180: A/libc(1299): Fatal signal 11 (SIGSEGV) at 0x99703ff4 (code=2), thread 1299 (sts.testsixcopy)

Here is my code. The comments in code show what each step is aiming to do. Please tell me what mistake I am making and how to correct it?

// Get the image from file path
            rgbaMat = new Mat();
            rgbaMat = Highgui.imread(filePath);
            Log.i(TAG, "GRANNY rgbaMat read successfully!");// check

            Bitmap rgbaMatBitmap = Bitmap.createBitmap(rgbaMat.cols(), rgbaMat.rows(), Bitmap.Config.ARGB_8888);
            Utils.matToBitmap(rgbaMat, rgbaMatBitmap);
            imageView.setImageBitmap(rgbaMatBitmap);
            Log.i(TAG, "GRANNY rgbaMatBitmap added to imageView successfully!");// check

            // Split 3 channel Mat into 1 channel arrays
            List<Mat> separatedChannelsList = new ArrayList<>();
            Core.split(rgbaMat, separatedChannelsList);
            Log.i(TAG, "GRANNY Core.split() carried out successfully!");// check

            // Start configuring histogram
            List<Mat> listOfRedChannelMat = new ArrayList<>();
            listOfRedChannelMat.add(separatedChannelsList.get(2));
            MatOfInt numberOfBins = new MatOfInt(256); // From 0 to 255
            MatOfFloat rangeOfValues = new MatOfFloat(0f, 256f); // The upper bound is exclusive
            //boolean uniform = true;//does not exist in android api
            boolean accumulate = false;
            MatOfInt numberOfDims = new MatOfInt(1);
            Mat redHistogram = new Mat();

            // Calculate the histograms
            Imgproc.calcHist(listOfRedChannelMat, numberOfDims, new Mat(), redHistogram, numberOfBins, rangeOfValues, accumulate);
            Log.i(TAG, "GRANNY Imgproc.calcHist() carried out successfully!");// check

            // Draw the histogram
            int histogramWidth = 512;
            int histogramHeight = 400;
            int binWidth = Math.round(   (float) (histogramWidth / numberOfBins.get(0, 0)[0])   );
            Mat histogramImage = new Mat(histogramHeight, histogramWidth, CvType.CV_8UC3, new Scalar(0, 0, 0));

            // Normalize the histogram so its values fall in the range indicated by the parameters entered
            Core.normalize(redHistogram, valueHistogram, 0, histogramImage.rows(), Core.NORM_MINMAX, -1, new Mat());
            Log.i(TAG, "GRANNY Core.normalize() carried out successfully!");// check

            // Finally, observe that to access the bin (in this case in this 1D-Histogram):
            for (int i = 1; i < 256; i++) {
                    Core.line(histogramImage,
                            new Point(binWidth * (i - 1), histogramHeight - Math.round(redHistogram.get(i - 1, 0)[0 ...
(more)
2016-06-26 15:39:47 -0600 commented question Why does calcHist() method create an empty black histogram Mat?

I am going to do some web search to understand those steps a bit better. If I still don't get it, I will post more specific questions. Thank you so much so far.

2016-06-26 13:47:13 -0600 commented question Why does calcHist() method create an empty black histogram Mat?

@sturkmen I am not able to understand step 5 in their explanation. How do they know that they have to use 512 and 400 as width and height values? Actually all steps after this one is confusing.

2016-06-26 10:10:45 -0600 asked a question Why does calcHist() method create an empty black histogram Mat?

I have written code to read in an image from gallery, then apply inRange() on it to find blue colored blob and create mask, then used findContours() to find contours, and the drawContours() to draw the contours, then boundingRect() to find a rectangle around the first contour, and then submat() to extract out the submatrix. Then I used Mat.zeroes() to create a mask from that rectangular submat. Then I applied Imgproc.calcHist() to create a histogram, and passed in the Mask as the 3rd argument so that the histogram calculated is that of the area inside the contour only.

Following is a screenshot from my Genymotion emulator, showing the original Mat with green contours around blue detected blobs and then the submatrix I mentioned and then the histogram created by calcHist(), which is black vertical line The question is why is it like this, where is my histogram graph?

image description

Code:

//Get the image from file path
            rgbaMat = new Mat();
            rgbaMatCopy = new Mat();
            rgbaMat = Highgui.imread(filePath);
            rgbaMatCopy = Highgui.imread(filePath);

            //Preprocessing - color space conversion
            Imgproc.cvtColor(rgbaMat, rgbaMat, Imgproc.COLOR_BGR2RGB);
            Imgproc.cvtColor(rgbaMatCopy, rgbaMatCopy, Imgproc.COLOR_BGR2RGB);
            Mat hsvMat = new Mat();
            Imgproc.cvtColor(rgbaMatCopy, hsvMat, Imgproc.COLOR_RGB2HSV);

            //Make the mask from the detected blue colored blob(s)
            Scalar lowerThreshold = new Scalar(100, 146, 148);
            Scalar upperThreshold = new Scalar(134, 255, 255);
            Mat mask = new Mat();
            Core.inRange(hsvMat, lowerThreshold, upperThreshold, mask);

            //Preprocessing
            Mat dilatedMask = new Mat();
            Imgproc.dilate(mask, dilatedMask, new Mat());
            Imgproc.dilate(dilatedMask, dilatedMask, new Mat());

            //Find the contours
            contours = new ArrayList<>();
            Imgproc.findContours(dilatedMask, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

            //Draw the contours
            for (int contourIdx = 0; contourIdx < contours.size(); contourIdx++) {
                Imgproc.drawContours(rgbaMatCopy, contours, contourIdx, new Scalar(0, 255, 0), 1);
            }

            //Convert the mat with contours drawn to bitmap and display in imageView
            Bitmap theBitmap = Bitmap.createBitmap(rgbaMatCopy.cols(), rgbaMatCopy.rows(),
                    Bitmap.Config.ARGB_8888);
            Utils.matToBitmap(rgbaMatCopy, theBitmap);
            imageView.setImageBitmap(theBitmap);

            //Find and cut out the smallest bounding rectangle around the first contour from the list of contours
            MatOfPoint firstContour = contours.get(0);
            Rect firstContourBoundingRect = Imgproc.boundingRect(firstContour);
            Mat objectSubmat = new Mat();
            objectSubmat = rgbaMat.submat(firstContourBoundingRect);

            Bitmap objectSubmatBitmap = Bitmap.createBitmap(objectSubmat.cols(), objectSubmat.rows(), Bitmap.Config.ARGB_8888);
            Utils.matToBitmap(objectSubmat, objectSubmatBitmap);
            imageViewOne.setImageBitmap(objectSubmatBitmap);

            //Create mask of the region inside the contour
            Mat regionMask = Mat.zeros(objectSubmat.rows(), objectSubmat.cols(), CvType.CV_8UC1);
            List<MatOfPoint> firstList = new ArrayList<MatOfPoint>();
            firstList.add(firstContour);
            Imgproc.drawContours(regionMask, firstList, 0, new Scalar(255), -1);

            //Preprocessing - color space conversion
            Mat regionHsv = new Mat();
            Imgproc.cvtColor(objectSubmat, regionHsv, Imgproc.COLOR_RGB2HSV);


            //Calculate Histogram
            List<Mat> sourceImageList = new ArrayList<Mat>();
            sourceImageList.add(regionHsv);
            Mat histogram = new Mat();
            //histogramMat.convertTo(histogramMat, CvType.CV_8UC2);
            Imgproc.calcHist(sourceImageList, new MatOfInt(2), regionMask, histogram, new MatOfInt(256), 
                    new MatOfFloat(0f, 256f));


        Highgui.imwrite("/mnt/sdcard/histogram.bmp", histogram);// check
        Mat hish = Highgui.imread("/mnt/sdcard/histogram.bmp");
        Bitmap histogramBitmap = 
                Bitmap.createBitmap(hish.cols(), hish.rows(), Bitmap.Config.ARGB_8888);
        Utils.matToBitmap(hish, histogramBitmap);
        imageViewTwo.setImageBitmap(histogramBitmap);
2016-06-26 09:15:09 -0600 asked a question Converting histogram Mat to BitMap - Getting OpenCV Error (src.type() == CV_8UC1 || src.type() == CV_8UC3 || src.type() == CV_8UC4)

I am trying to calculate the histogram from this image and trying to convert it to a Bitmap and display it.

image description

And I am getting the following error. The question is why, and how can I fix it?

06-26 14:07:18.972: E/cv::error()(1278): OpenCV Error: Assertion failed (src.type() == CV_8UC1 || src.type() == CV_8UC3 || src.type() == CV_8UC4) in void Java_org_opencv_android_Utils_nMatToBitmap2(JNIEnv *, jclass, jlong, jobject, jboolean), file /hdd2/buildbot/slaves/slave_ardbeg1/50-SDK/opencv/modules/java/generator/src/cpp/utils.cpp, line 98
06-26 14:07:18.992: A/libc(1278): Fatal signal 11 (SIGSEGV) at 0x997fcff4 (code=2), thread 1278 (tests.testfive)

Following is the relevant part of my code.

    //Get the image from file path
    rgbaMat = new Mat();
    rgbaMat = Highgui.imread(filePath);

    Bitmap objectSubmatBitmap = Bitmap.createBitmap(rgbaMat.cols(), rgbaMat.rows(), Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(rgbaMat, objectSubmatBitmap);
    imageViewOne.setImageBitmap(objectSubmatBitmap);

    //Preprocessing - color space conversion
    Imgproc.cvtColor(rgbaMat, rgbaMat, Imgproc.COLOR_BGR2RGB);
    Mat hsvMat = new Mat();
    Imgproc.cvtColor(rgbaMat, hsvMat, Imgproc.COLOR_RGB2HSV);


    //Calculate Histogram
    List<Mat> sourceImageList = new ArrayList<Mat>();
    sourceImageList.add(hsvMat);
    Mat histogram = new Mat();
    //histogramMat.convertTo(histogramMat, CvType.CV_8UC1);
    Imgproc.calcHist(sourceImageList, new MatOfInt(2), new Mat(), histogram, new MatOfInt(256), 
                    new MatOfFloat(0f, 256f));

    //Highgui.imwrite("/mnt/sdcard/histogram.bmp", histogram);// check
    Bitmap histogramBitmap = 
    Bitmap.createBitmap(histogram.cols(), histogram.rows(), Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(histogram, histogramBitmap);
    imageViewOne.setImageBitmap(histogramBitmap);
2016-06-26 04:12:59 -0600 commented question How to draw contours INSIDE the edges of detected shape/blob?

@sturkmen Thank you. I posted the complete code and the original image in the question.

2016-06-25 05:57:54 -0600 asked a question How to draw contours INSIDE the edges of detected shape/blob?

Following is an image of a blue colored blob detected in an Android app using OpenCV4Android. I used Core.inRange() and Imgproc.findContours() methods to find the contours, and Imgproc.drawContours() to draw em.

Mat mask = new Mat();
Core.inRange(rgbaMat, lowerThreshold, upperThreshold, mask);
...
contours = new ArrayList<>();
Imgproc.findContours(dilatedMat, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
...
for ( int contourIdx=0; contourIdx < contours.size(); contourIdx++ ) { 
    Imgproc.drawContours ( rgbaMat, contours, contourIdx, new Scalar(0, 255, 0), 1);
}

The contour (light green boundary) is outside the detected shape.

So, as you can see, it also includes some white area around the detected blue blob. I want the contour boundary to be inside the edges of the blue blob/shape. How can I do that?

image description


EDIT: @sturkmen

Original Image:

image description

(These are my complete files:*

MainActivity.java:

public class MainActivity extends Activity implements CvCameraViewListener2 {
    private static final String TAG = MainActivity.class.getSimpleName();
    private static Mat rgbaFrame;
    private static final int pickImageRequestCode = 99;
    private Mat rgbaMat;
    private Mat rgbaMatCopy;
    private ArrayList<MatOfPoint> contours;
    private ImageView imageView;


    private CameraBridgeViewBase cameraBridgeViewBase;

    private BaseLoaderCallback baseLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
            case LoaderCallbackInterface.SUCCESS: {
                Log.i(TAG, "OpenCV loaded successfully!");
                if (cameraBridgeViewBase != null) {
                    cameraBridgeViewBase.enableView();
                }
            }
                break;
            default: {
                super.onManagerConnected(status);
            }
                break;
            }
        }
    };




    @Override
    public void onCameraViewStarted(int width, int height) {
        rgbaFrame = new Mat(height, width, CvType.CV_8UC4);
    }

    @Override
    public void onCameraViewStopped() {
        rgbaFrame.release();
    }

    @Override
    public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
        rgbaFrame = inputFrame.rgba();
        return rgbaFrame;
    }





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.mainActivity_imageView);

        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, baseLoaderCallback);

        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, pickImageRequestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        if (resultCode == Activity.RESULT_OK && requestCode == pickImageRequestCode) {
            Uri selectedImageUri = imageReturnedIntent.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();

            rgbaMat = new Mat();
            rgbaMatCopy = new Mat();
            rgbaMat = Highgui.imread(filePath);
            rgbaMatCopy = Highgui.imread(filePath);

            Imgproc.cvtColor(rgbaMat, rgbaMat, Imgproc.COLOR_BGR2RGB);
            Imgproc.cvtColor(rgbaMatCopy, rgbaMatCopy, Imgproc.COLOR_BGR2RGB);

            Mat hsvMat = new Mat();
            Imgproc.cvtColor(rgbaMatCopy, hsvMat, Imgproc.COLOR_RGB2HSV);

            Scalar lowerThreshold = new Scalar(100, 146, 148);
            Scalar upperThreshold = new Scalar(134, 255, 255);
            Mat mask = new Mat();
            Core.inRange(hsvMat, lowerThreshold, upperThreshold, mask);

            Mat dilatedMask = new Mat();
            Imgproc.dilate(mask, dilatedMask, new Mat());
            Imgproc.dilate(dilatedMask, dilatedMask, new Mat());

            contours = new ArrayList<>();
            Imgproc.findContours(dilatedMask, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

            for (int contourIdx = 0; contourIdx < contours.size(); contourIdx++) {
                Imgproc.drawContours(rgbaMatCopy, contours, contourIdx, new Scalar(0, 255, 0), 1);
            }

            Bitmap theBitmap = Bitmap.createBitmap(rgbaMatCopy.cols(), rgbaMatCopy.rows(),
                    Bitmap.Config.ARGB_8888);
            Utils.matToBitmap(rgbaMatCopy, theBitmap);
            imageView.setImageBitmap(theBitmap);
        }

    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <ImageView
        android:id="@+id/mainActivity_imageView"
        android:layout_width="match_parent"
        android:layout_height ...
(more)
2016-04-21 00:22:40 -0600 asked a question My contours smaller than a certain value are Not being removed from list of contours, despite of correct logic. Why?

I started with this image:

[![enter image description here][1]]

Then I applied Canny Edge Detector like:

Mat originalMatGreyScale = new Mat();
Imgproc.cvtColor(originalPhotoMat, originalMatGreyScale, Imgproc.COLOR_BGR2GRAY);
Mat edgesMat = new Mat();
Imgproc.Canny(originalMatGreyScale, edgesMat , 50, 70);

I got:

[![enter image description here][2]]

Then I found a list of contours (contours) by Imgproc.findContours().Then I did some coding to (1)find the area of largest contour (maximumContourArea) (2) Remove from contours any contour which has an area less than the maximumContourArea. Code given as follows.

What I was expecting was that all those little smudges and noise should be removed by this, but instead I still got this:

[![enter image description here][3]]

Moreover, the Log.i() messages in the following code print this:

Number of contours initially: 27

Number of contours after processing: 27

List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(edgesMap, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);


Log.i(TAG, "Number of contours initially: " + contours.size());//check

double maximumContourArea = 0;

Iterator<MatOfPoint> contoursIterator = contours.iterator();

while(contoursIterator.hasNext()) {
    MatOfPoint nextContour = contoursIterator.next();
    double nextContourArea = Imgproc.contourArea(nextContour);

    if (nextContourArea > maximumContourArea) {
        maximumContourArea = nextContourArea;
    }
}

while(contoursIterator.hasNext()) {
    MatOfPoint nextContour = contoursIterator.next();
    if (Imgproc.contourArea(nextContour) < maximumContourArea*(10 / 100)) {
        contours.remove(contours.indexOf(nextContour));
    }
}

Log.i(TAG, "Number of contours after processing: " + contours.size());//check
2016-04-20 06:40:12 -0600 commented answer Why is the drawContour() in OpenCV generating this strange Mask?

This helped get rid of the garbage in the mask, but still not working correctly. Tried a couple of things, which have confused me more. Can you see the edit in the question?

2016-04-20 00:36:34 -0600 asked a question Why is the drawContour() in OpenCV generating this strange Mask?

I started by reading in a Mat.

Then I converted it to Greyscale and applied Imgproc.canny() to it, getting the following mask.

Then I used Imgproc.findContours() to find the contours, Imgproc.drawContours(), and Core.putText() to label the contours with numbers

Then I did Rect boundingRect = Imgproc.boundingRect(contours.get(0)); Mat submatrix = new Mat(); submatrix = originalMat.submat(boundingRect); to get following submatrix:

So far so good. The Problem starts hereafter:

NOW I NEEDED A MASK OF THE submatrix. So I decided to use Imgproc.drawContours() to get the mask:

Mat mask = new Mat(submatrix.rows(), submatrix.cols(), CvType.CV_8UC1);
        List<MatOfPoint> contourList = new ArrayList<>();
        contourList.add(contours.get(0));
        Imgproc.drawContours(mask, contourList, 0, new Scalar(255), -1);

I got the following mask:

enter image description here

WHAT I WAS EXPECTING was a filled (in white color) diamond shape on black background.

WHy am I getting this unexpected result?

2016-04-20 00:36:04 -0600 marked best answer How to create an ROI (Region-Of-Interest or submat) from a contour?

Given an image Mat, and a contour (which is a MatOfPoint) in it, how can I create a ROI (Region Of Interest)/submat?

I can see three interesting methods on docs of Mat,

Mat submat(int rowStart, int rowEnd, int colStart, int colEnd) Extracts a rectangular submatrix.

Mat submat(Range rowRange, Range colRange) Extracts a rectangular submatrix.

Mat submat(Rect roi) Extracts a rectangular submatrix.

  • Is there a way to find out rowStart, rowEnd, colStart and colEnd from the contour?

or

  • Is there a way to get rowRange and colRange from the contour?

or

  • Can I make a Rect from the contour?