均值模糊
均值模糊可降低图像的噪声、模糊图形及降低图像的对比度。该操作的kernel所有系数相同。均值模糊所依赖的函数为blur()(一些现代语言或框架也提供了类似的方法或函数),该函数定义如下:
blur(src, dst, ksize, anchor, borderType);
各参数解释如下:
Java代码(JavaFX Controller层)
public class Controller{
@FXML private Text fxText;
@FXML private ImageView imageView;
@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 = blurOfSmooth(filePath);
Platform.runLater(new Runnable() {
@Override
public void run() {
imageView.setImage(writableImage);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private WritableImage blurOfSmooth(String filePath) throws IOException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat src = Imgcodecs.imread(filePath);
Mat dst = new Mat();
Imgproc.blur(src, dst, new Size(5,5), new Point(-1,-1), Core.BORDER_DEFAULT);
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;
}
}
说明:这里使用的kernal大小为5x5,若要使其在水平或竖直方向上模糊只要把ksize的其中某个参数设为1即可。如下示例:
-
kisze = new Size(5,1); 水平方向模糊 -
kisze = new Size(1,5); 竖直方向模糊
运行图
图1 - kernal为(5,5)时的均值模糊处理图
图2 - Lenna原图
|