灰度转换 cvtColor(Mat src, Mat dst, int code) 方法可以完成目标矩阵与输入矩阵之间的灰度转换,其中code系转换模式,这里为灰度模式,即Imgproc.COLOR_RGB2GRAY。
Java代码
@FXML public void handleButtonEvent(ActionEvent actionEvent) {
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);
imageView.setImage(this.toGray(file.getPath()));
}
private WritableImage toGray(String filePath){
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Imgcodecs imageCodecs = new Imgcodecs();
String input = filePath;
Mat src = imageCodecs.imread(input, Imgcodecs.IMREAD_COLOR);
Mat dst = new Mat();
Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGB2GRAY);
byte[] data = new byte[src.rows() * src.cols() * (int) (src.elemSize())];
dst.get(0, 0, data);
BufferedImage bufImage = new BufferedImage(dst.cols(), dst.rows(), BufferedImage.TYPE_BYTE_GRAY);
bufImage.getRaster().setDataElements(0, 0, dst.cols(), dst.rows(), data);
WritableImage writableImage = SwingFXUtils.toFXImage(bufImage, null);
return writableImage;
}
运行图:
|