OpenCV.Scharr梯度
作者:互联网
Scharr梯度
Scharr梯度算子分为X方向Y与方向,可以分别计算其各自方向的梯度图像,然后将其进行平均权重相加即可。其声明如下:
Scharr(src, dst, ddepth, dx, dy);
各参数解释如下:
-
src
表示此操作的源(输入图像)的Mat对象。 -
dst
表示此操作的目标(输出图像)的Mat对象。 -
ddepth
表示输出图像的深度,通常为CV_32F或CV_64F等。 -
dx
表示X方向的梯度,为1则启用,0则禁用,下同。 -
dy
表示Y方向的梯度
Scharr算子的Kernel如下所示:
Scharr算子可看作为Sobel算子的增强版,对边缘检测比较有效。
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 = gradOfScharr(filePath);
Platform.runLater(new Runnable() {
@Override
public void run() {
imageView.setImage(writableImage);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private WritableImage gradOfScharr(String filePath) throws IOException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat src = Imgcodecs.imread(filePath);
Mat dst = new Mat();
// X-direction gradient
Mat grad_x = new Mat();
Imgproc.Scharr(src, grad_x, CvType.CV_32F, 1, 0);
Core.convertScaleAbs(grad_x, grad_x);
// Y-direction gradient
Mat grad_y = new Mat();
Imgproc.Scharr(src, grad_y, CvType.CV_32F, 0, 1);
Core.convertScaleAbs(grad_y, grad_y);
Core.addWeighted(grad_x, 0.5, grad_y, 0.5, 0, dst);
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;
}
}
运行图
标签:Mat,梯度,dst,private,OpenCV,Scharr,new,grad 来源: https://blog.csdn.net/kicinio/article/details/121546315