[英]How to threshold any image (for black and white color seperation) in java?
已解決:問題是“jpeg 壓縮”。 保存為“.png”有效。
我使用java中的canny過濾器程序檢測到圖像的邊緣。 應用過濾器后...
都有不同深淺的黑色和白色。
我希望我的所有邊緣像素為純白色(#FFFFFF),其余部分為黑色。
注意:除了上述(#F7F7F7)之外,不同的像素可能具有不同的陰影。 上面的放大圖像只是一個例子。
編輯:我寫了這段代碼來對圖像生效......
public void convert(){
try{
BufferedImage img = ImageIO.read(new File("input.jpg"));
int rgb;
int height = img.getHeight();
int width = img.getWidth();
File f = new File("newThreshold.jpg");
Color white = new Color(255,255,255);
int wh = white.getRGB();
for (int h = 0; h<height; h++){
for (int w = 0; w<width; w++){
rgb = img.getRGB(w, h);
red = (rgb & 0x00ff0000) >> 16;
green = (rgb & 0x0000ff00) >> 8;
blue = rgb & 0x000000ff;
if(red >= 200 || blue >= 200 || green >= 200){
img.setRGB(w,h,wh);
}
}
}
ImageIO.write(img,"jpg",f);
}
catch(Exception e){
}
}
即使在運行代碼之后,我的圖像也沒有變化。
即使紅色、綠色和藍色值高於 200,我的圖像也沒有變化。
更新:將圖像保存為“.png”而不是“.jpg”有效!
您可以查看圖像中的每個像素並確定它是否高於某個閾值,是否將其值設置為純白色。 如果需要,您也可以對較暗的區域執行相同操作。
例子:
public Image thresholdWhite(Image in, int threshold)
{
Pixel[][] pixels = in.getPixels();
for(int i = 0; i < pixels.length; ++i)
{
for(int j = 0; j < pixels[i].length; ++j)
{
byte red = pixels[i][j].getRed();
byte green = pixels[i][j].getGreen();
byte blue = pixels[i][j].getBlue();
/* In case it isn't a grayscale image, if it is grayscale this if can be removed (the block is still needed though) */
if(Math.abs(red - green) >= 16 && Math.abs(red - blue) >= 16 && Math.abs(blue- green) >= 16)
{
if(red >= threshold || blue >= threshold || green >= threshold)
{
pixels[i][j] = new Pixel(Colors.WHITE);
}
}
}
}
return new Image(pixels);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.