OpenCV.自适应阈值.Adaptive

自适应阈值.Adaptive

对于自适应阈值除了OTSU与TRIANGLE外,还有使用图像自适应阈值的方法,该方法具体有C均值与高斯C均值两种。其在OpenCV中实现依赖于adaptiveThreshold() 函数,下面是其声明:

adaptiveThreshold(gray, dst, maxValue, adaptiveMethod, thresholdType, blockSize, C);

各参数解释如下:

    src 表示此操作的源(输入图像)的Mat对象。 dst 表示此操作的目标(输出图像)的Mat对象。 maxValue 最大灰度值,通常为255。 adaptiveMethod 自适应方法,通常为C均值或高斯C均值。 thresholdType 阈值方法,通常为THRESH_BINARY。 blockSize 分块大小,奇数。 C 常数,阈值化的时候使用计算得到的+C之后作分割。

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

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

                } catch (IOException e) {
          
   
                    e.printStackTrace();
                }
            }
        }).start();
    }
    
    private WritableImage thresholdOfAdaptive(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.adaptiveThreshold(gray, dst, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 15, 10);

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

}

运行图

经验分享 程序员 微信小程序 职场和发展