其他分享
首页 > 其他分享> > OpenCV.反阈值二值化

OpenCV.反阈值二值化

作者:互联网

反阈值二值化

反阈值二值化与阈值二值化互为逆操作。在OpenCV中该类的实现依赖于threshold() 函数。下面是该函数的声明:

threshold(src, dst, thresh, maxval, type);

各参数解释

其数学描述解释如下:

在这里插入图片描述

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 = thresholdOfNonBinary(filePath);

                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImage(writableImage);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    
    private WritableImage thresholdOfNonBinary(String filePath) throws IOException {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        Mat src = Imgcodecs.imread(filePath);
        Mat dst = new Mat();

        Imgproc.threshold(src, dst, 130, 255, Imgproc.THRESH_BINARY_INV);

        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;
    }

}


运行图
在这里插入图片描述

标签:src,Mat,阈值,dst,private,OpenCV,new,二值化
来源: https://blog.csdn.net/kicinio/article/details/121364440