0

I am using OpenCV android library thresholding method for image segmentation, but the problem is that the output bitmap contains black background which I do not want please note that original image does not have any black background it is actually white. I am attaching the code for your reference, I am new to opencv and don't have much understanding about it also so kindly help me out.

private void Segmentation() {
    Mat srcMat = new Mat();
    gray = new Mat();

    Utils.bitmapToMat(imageBmp, srcMat);
    Imgproc.cvtColor(srcMat, gray, Imgproc.COLOR_RGBA2GRAY);
    grayBmp = Bitmap.createBitmap(imageBmp.getWidth(), imageBmp.getHeight(), Bitmap.Config.RGB_565);
    Utils.matToBitmap(gray, grayBmp);

    grayscaleHistogram();

    Mat threshold = new Mat();
    Imgproc.threshold(gray, threshold, 0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU);
    thresBmp = Bitmap.createBitmap(imageBmp.getWidth(), imageBmp.getHeight(), Bitmap.Config.RGB_565);
    Utils.matToBitmap(threshold, thresBmp);

    Mat closing = new Mat();
    Mat kernel = Mat.ones(5, 5, CvType.CV_8U);
    Imgproc.morphologyEx(threshold, closing, Imgproc.MORPH_CLOSE, kernel, new Point(-1, -1), 3);
    closingBmp = Bitmap.createBitmap(imageBmp.getWidth(), imageBmp.getHeight(), Bitmap.Config.RGB_565);
    Utils.matToBitmap(closing, closingBmp);

    result = new Mat();
    Core.subtract(closing, gray, result);
    Core.subtract(closing, result, result);


    resultBmp = Bitmap.createBitmap(imageBmp.getWidth(), imageBmp.getHeight(), Bitmap.Config.RGB_565);
    Utils.matToBitmap(result, resultBmp);

    Glide.with(ResultActivity.this).asBitmap().load(resultBmp).into(ivAfter);
}

enter image description here

Kdon Patel
  • 107
  • 1
  • 15
  • What do you mean by "remove blzck background"? Do you want your background pixels to be white instead of black? – vSomers Dec 11 '19 at 09:36

1 Answers1

0

What exactly do you want it to be then? Binary thresholding works like this:

if value < threshold:
  value = 0
else:
  value = 1

Of course you can convert it to a grayscale / RGB image and adjust the background to your liking. You can also invert your image (white background, black segmentation) by using the ~ operator.

segmented_image = ~ segmented_image

Edit: OpenCV has a dedicated flag to invert the results: CV_THRESH_BINARY_INV You are already using it, maybe try changing it to CV_THRESH_BINARY

code-lukas
  • 1,586
  • 9
  • 19