Java OpenCV 图像处理34 图形图像 分水岭 watershed
package com.xu.opencv;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class Image {
static {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
public static void main(String[] args) {
watershed();
}
public static void watershed() {
Mat source = Imgcodecs.imread("D:\\OneDrive\\桌面\\1.png", Imgcodecs.IMREAD_COLOR);
HighGui.imshow("mask", source);
Mat gray = new Mat(source.rows(), source.cols(), CvType.CV_8UC1);
Imgproc.cvtColor(source, gray, Imgproc.COLOR_BGR2GRAY);
Mat binary = Mat.zeros(gray.rows(), gray.cols(), CvType.CV_8UC1);
Imgproc.threshold(gray, binary, 100, 255, Imgproc.THRESH_BINARY);
Mat fg = new Mat(source.size(), CvType.CV_8U);
Imgproc.erode(binary, fg, new Mat(), new Point(-1, -1), 2);
Mat bg = new Mat(source.size(), CvType.CV_8U);
Imgproc.dilate(binary, bg, new Mat(), new Point(-1, -1), 3);
Imgproc.threshold(bg, bg, 1, 128, Imgproc.THRESH_BINARY_INV);
Mat temp1 = new Mat(binary.size(), CvType.CV_8U, new Scalar(0));
Mat temp2 = new Mat(binary.size(), CvType.CV_8U, new Scalar(0));
Mat temp3 = new Mat(binary.size(), CvType.CV_8U, new Scalar(0));
Mat mask = new Mat(binary.size(), CvType.CV_8U, new Scalar(0));
Core.add(fg, bg, mask);
mask.convertTo(temp1, CvType.CV_32S);
Imgproc.watershed(source, temp1);
temp1.convertTo(temp2, CvType.CV_8UC1);
temp1.convertTo(temp3, CvType.CV_8U, 255, 255);
temp1.convertTo(temp1, CvType.CV_8UC1);
HighGui.imshow("mask", mask);
HighGui.imshow("temp1", temp1);
HighGui.imshow("temp2", temp2);
HighGui.imshow("temp3", temp3);
HighGui.waitKey();
HighGui.destroyAllWindows();
}
}