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 utilisé
Mat fgModel = new Mat();//grabCut utilisé
Mat mask;
Mat source = new Mat(1, 1, CvType.CV_8U, new Scalar(3.0));
//Rectangle de définition
Rect rect = new Rect(0, 0,150,200);
///Exécution coupure(Divisé)ligne
Imgproc.grabCut(img, firstMask, rect, bgModel, fgModel, 1, 0 );
//Premier plan
Core.compare(firstMask, source, firstMask, Core.CMP_EQ);
//Statue d'exportation de génération
Mat foreground = new Mat(img.size(), CvType.CV_8UC3, new Scalar(255,
255, 255));
//Dupliquer le premier plan,Zone cohérente
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);
//Couleur de remplacement après la sortie
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