Hello guys. I need to remove background from image using openCV and java.
What methods can you recomend me?
what have you tried so far?
I found this tutorial and try to make the same thing on java
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class Main {
static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
public static void main(String[] args) {
System.out.println("Welcome to OpenCV " + Core.VERSION);
Imgcodecs imageCodecs = new Imgcodecs();
String file ="src/myCode/img.jpg";
Mat image = imageCodecs.imread(file);
System.out.println("Image Loaded ..........");
Rect rectangle = new Rect(0, 0, image.width(), image.height());
Mat result = Mat.zeros(image.height(),image.width(),CvType.CV_8U);
Mat bgdModel = Mat.zeros(1,65,CvType.CV_64F);
Mat fgdModel = Mat.zeros(1,65,CvType.CV_64F);
Mat source = new Mat(1, 1, CvType.CV_8U, new Scalar(3));
Imgproc.grabCut(image, result, rectangle, bgdModel, fgdModel, 8, Imgproc.GC_INIT_WITH_MASK);
Core.compare(result, source, result, Core.CMP_EQ);
Mat foreground = new Mat(image.size(), CvType.CV_8UC3, new Scalar(255, 255, 255));
image.copyTo(foreground, result);
//Imgcodecs.imwrite(fileNameWithCompletePath, foreground);
//Writing the image
String file2 = "src/myCode/img2.jpg";
Imgcodecs.imwrite(file2, foreground);
System.out.println("Image Saved ............");
}
}
But right now I’m getting the exceptions
Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: OpenCV(4.5.0) C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\imgproc\src\grabcut.cpp:386: error: (-215:Assertion failed) !bgdSamples.empty() && !fgdSamples.empty() in function 'initGMMs'
]
at org.opencv.imgproc.Imgproc.grabCut_0(Native Method)
at org.opencv.imgproc.Imgproc.grabCut(Imgproc.java:7074)
at myCode.Main.main(Main.java:23)
I fixed this problem by changing rectangle size to
Rect rectangle = new Rect(1, 1, image.width(), image.height());
The problem was in that rectangle shouldn’t cover the whole image
Now I have another question
How to make background transparent?