我正在尝试使用sobel滤镜在BufferedImage上进行边缘检测。但似乎Java过滤器系统没有正确处理图像中的负值(而手动实现只是abs()
它们)。如果不手动编写整个过滤器,是否可以避免此问题?
代码:
BufferedImage image, converted_image;
try {
image = ImageIO.read(new File("image.png"));
// convert image from ARGB to RGB
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
g.dispose();
image = newImage;
} catch (IOException ex) {
System.exit(1);
}
float sobel[] = {
1.0f, 0.0f, -1.0f,
2.0f, 0.0f, -2.0f,
1.0f, 0.0f, -1.0f
};
BufferedImageOp sobelFilter = new ConvolveOp(new Kernel(3, 3, sobel));
converted_image = sobelFilter.filter(image, null);
try {
ImageIO.write(converted_image, "png", new File("image2.png"));
} catch (IOException ex) {
System.exit(1);
}
示例图片:
错误的边缘检测。请注意,虽然过滤器只应处理垂直边,但它只处理black | white
个边,而不是white | black
个边。