Search code examples
javaandroidopencvthreshold

Why my BGR2GRAY Mat returns a color blue in a basic threshold function? [OPENCV]


I am new to stackoverflow and I sincerely apologize for my format if I'll be doing it wrong (Please don't hesitate to tell what to fix about this thread).

I am trying to create an Image segmentation from an original picture, It returns a white background and a blue color for the green leaf. I was expecting a black and white pixels from the function and I really don't know if I'm doing it right.

I want to use the BGR2GRAY Mat Object as a marker for the original object, trying to separate the leaf from the background. Here is my code.

    // IMAGE SEGMENTATION USING WATERSHED ALGORITHM //
    //Create a Mat Object using originalPicture as is:

    //Create an instance of Mat Object using originalPicture as BGR2GRAY:
    Mat imageSegmentationMat = Imgcodecs.imread(originalFilePathStr, Imgproc.COLOR_BGR2GRAY);
    //Use basic threshold for imageSegmentationMat:
    Imgproc.threshold(originalPicMat,imageSegmentationMat, 86,255, Imgproc.THRESH_BINARY);
    //test:
    Bitmap imageSegmentationBmp = Bitmap.createBitmap(imageSegmentationMat.cols(), imageSegmentationMat.rows(),Bitmap.Config.ARGB_8888);
    Utils.matToBitmap(imageSegmentationMat, imageSegmentationBmp);
    imgView_segmentation.setImageBitmap(imageSegmentationBmp);

I was expecting to get a black and white only as what I've seen in the OpenCV tutorials. Can anyone please help me by explaining what is happening? Thank you.

Here is a screenshot my output: http://imageshack.com/a/img924/8520/qPaMdX.png

UPDATE: I forgot to tell that I was following this tutorial about image segmentation and this line is where I got my problem:

ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

And I just had to convert it to java (The tutorial is written in phyton which I have zero knowledge of it, though it looks so easy to read) here is mine:

Imgproc.threshold(grayscaleMat,testThresholdMat,0,255, Imgproc.THRESH_BINARY_INV+Imgproc.THRESH_OTSU);

So to ANSWER my question: my threshold function lacks THRESH_OTSU which creates the problem. AND I SHOULD ALSO READ MORE DOCUMENTATION.

I should really thank the people here in stackoverflow who actively help people. I love this place <3


Solution

  • The flag for imread seems to be the wrong one. I think it should be IMREAD_GRAYSCALE from Imgcodecs the BGR2GRAY is for the function cvtColor

    so it should be

    Mat imageSegmentationMat = Imgcodecs.imread(originalFilePathStr, Imgcodecs.IMREAD_GRAYSCALE);
    

    UPDATE:

    You may need to convert it to RGBA before bitmap (bug maybe?)

    Imgproc.cvtColor(imageSegmentationMat, tmp, Imgproc.COLOR_GRAY2RGBA, 4);