OpenCV_GrabCut.java
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class OpenCV_GrabCut {
public static void main( String[] args )
{
try{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Mat source = Imgcodecs.imread("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\lena.jpg ",
Imgcodecs.CV_LOAD_IMAGE_COLOR);
bgSubtracting(source);
}catch (Exception e) {
System.out.println("error: " + e.getMessage());
}
}
private static void bgSubtracting(Mat img) {
Mat firstMask = new Mat();
Mat bgModel = new Mat();//grabCut 內 part math use
Mat fgModel = new Mat();//grabCut 內 part math use
Mat mask;
Mat source = new Mat(1, 1, CvType.CV_8U, new Scalar(3.0));
//Definition rectangle
Rect rect = new Rect(0, 0,150,200);
///Execution grab Cut(Split)line
Imgproc.grabCut(img, firstMask, rect, bgModel, fgModel, 1, 0 );
//Foreground
Core.compare(firstMask, source, firstMask, Core.CMP_EQ);
//Generated export image
Mat foreground = new Mat(img.size(), CvType.CV_8UC3, new Scalar(255,
255, 255));
//Duplicate foreground data,Consistent area
img.copyTo(foreground, firstMask);
mask = new Mat(foreground.size(), CvType.CV_8UC1, new Scalar(255, 255, 255));
Imgproc.cvtColor(foreground, mask, Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(mask, mask, 254, 255, Imgproc.THRESH_BINARY_INV);
//Post-expulsion replacement color
Mat vals = new Mat(1, 1, CvType.CV_8UC3, new Scalar(255.0));
img.setTo(vals, mask);
Imgcodecs.imwrite("D:\\projects\\Java\\OpenCV_Samples\\resource\\imgs\\grab_cut.jpg ", img);
}
}
Recommended Posts