Bil*_*ins 2 java image-processing
你好我将图像从彩色转换为纯黑色和白色,结果是一个黑暗的图像.我没理由.以下是我的代码,它受到SO上其他代码的启发.任何指导都会有所帮助.
BufferedImage coloredImage = ImageIO.read(new File("/home/discusit/ninja.png"));
BufferedImage blackNWhite = new BufferedImage(coloredImage.getWidth(),coloredImage.getHeight(),BufferedImage.TYPE_BYTE_BINARY);
Graphics2D graphics = blackNWhite.createGraphics();
graphics.drawImage(blackNWhite, 0, 0, null);
Run Code Online (Sandbox Code Playgroud)
我没有得到我做错的事.使用任何其他开源库的任何更多想法都可以.
工作:::::
BufferedImage coloredImage = ImageIO.read(new File("/home/abc/ninja.png"));
BufferedImage blackNWhite = new BufferedImage(coloredImage.getWidth(),coloredImage.getHeight(),BufferedImage.TYPE_BYTE_BINARY);
Graphics2D graphics = blackNWhite.createGraphics();
graphics.drawImage(coloredImage, 0, 0, null);
ImageIO.write(blackNWhite, "png", new File("/home/abc/newBlackNWhite.png"));
Run Code Online (Sandbox Code Playgroud)
小智 8
如果你想控制所谓的阈值处理过程,这里就是一个现成的代码片段.从128开始作为阈值,然后你得到其他方法的作用.
/**
* Converts an image to a binary one based on given threshold
* @param image the image to convert. Remains untouched.
* @param threshold the threshold in [0,255]
* @return a new BufferedImage instance of TYPE_BYTE_GRAY with only 0'S and 255's
*/
public static BufferedImage thresholdImage(BufferedImage image, int threshold) {
BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
result.getGraphics().drawImage(image, 0, 0, null);
WritableRaster raster = result.getRaster();
int[] pixels = new int[image.getWidth()];
for (int y = 0; y < image.getHeight(); y++) {
raster.getPixels(0, y, image.getWidth(), 1, pixels);
for (int i = 0; i < pixels.length; i++) {
if (pixels[i] < threshold) pixels[i] = 0;
else pixels[i] = 255;
}
raster.setPixels(0, y, image.getWidth(), 1, pixels);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15301 次 |
| 最近记录: |