OpenCV.金字塔(Pyramid).均值偏移金字塔

均值偏移金字塔

对于给定的一定数量样本,任选其中一个样本,以该样本为中心点划定一个圆形区域,求取该圆形区域内样本的质心,即密度最大处的点,再以该点为中心继续执行上述迭代过程,直至最终收敛。可以利用均值偏移算法,可实现彩色图像分割。pyrMeanShiftFiltering实现图像在色彩层面的平滑滤波,它可以中和色彩分布相近的颜色,平滑色彩细节,侵蚀掉面积较小的颜色区域,算法跟金字塔图像分割相比耗时较长。在OpenCV中该类的实现依赖于pyrMeanShiftFiltering() 函数。下面是该函数的声明:

pyrMeanShiftFiltering(src, dst, sp, sr);

各参数解释

  • src
    表示此操作的源(输入图像)的Mat对象。

  • mat
    表示目标(输出)图像的类Mat的对象。

  • sp
    类型为double的空间窗口半径变量。

  • sr
    类型为double的变量,表示颜色窗口半径。

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

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

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

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

        Imgproc.pyrMeanShiftFiltering(src, dst, 100, 100);

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

}

运行图

在这里插入图片描述

おすすめ

転載: blog.csdn.net/kicinio/article/details/121315062