自适应阈值.OTSU
对于阈值操作,不仅可以手动设置阈值,还可以自动计算阈值,即根据输入源本身特征进行自适应阈值。本节自适应为OTSU。OTSU的含义为将灰度输入源的直方图划为两个部分,并计算其类内方差和类间方差,最小类内方差或最大类间方差即为阈值T。在OpenCV中,其枚举为Imgproc.THRESH_OTSU。
其数学描述解释如下:
假设src为双峰图像,则OTSU将会找到一个阈值t,以最小化由关系给出的加权类内方差:
其中,
实际上找到了一个位于两个峰值之间的 t 值,使得两个类的方差最小。
Java代码(JavaFX Controller层)
public class Controller{
@FXML private Text fxText;
@FXML private ImageView imageView;
@FXML private Label resultLabel;
@FXML public void handleButtonEvent(ActionEvent actionEvent) throws IOException {
Node source = (Node) actionEvent.getSource();
Window theStage = source.getScene().getWindow();
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.png");
fileChooser.getExtensionFilters().add(extFilter);
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JPG Files(*.jpg)", "*.jpg"));
File file = fileChooser.showOpenDialog(theStage);
runInSubThread(file.getPath());
}
private void runInSubThread(String filePath){
new Thread(new Runnable() {
@Override
public void run() {
try {
WritableImage writableImage = thresholdOfOTSU(filePath);
Platform.runLater(new Runnable() {
@Override
public void run() {
imageView.setImage(writableImage);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private WritableImage thresholdOfOTSU(String filePath) throws IOException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat src = Imgcodecs.imread(filePath);
Mat dst = new Mat();
// Construct an empty mat instance to change src into gray image.
Mat gray = new Mat();
Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(gray, dst, 80, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", dst, matOfByte);
byte[] bytes = matOfByte.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage bufImage = ImageIO.read(in);
WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
return writableImage;
}
}
运行图