[英]How to threshold any image (for black and white color seperation) in java?
SOLVED : Issue was "jpeg compression".已解决:问题是“jpeg 压缩”。 Saving as ".png" worked.保存为“.png”有效。
I had detected edges of an image using a canny filter program in java.我使用java中的canny过滤器程序检测到图像的边缘。 After applying filter ...应用过滤器后...
This is my image If zoomed in ... Zoomed这是我的形象如果放大...缩放
All have different shades of black and white.都有不同深浅的黑色和白色。
I want all my edge pixels as pure white(#FFFFFF) and the remaining portion black.我希望我的所有边缘像素为纯白色(#FFFFFF),其余部分为黑色。
Note: Different pixels may have different shades apart from the one above(#F7F7F7).注意:除了上述(#F7F7F7)之外,不同的像素可能具有不同的阴影。 The zoomed image above is just an example.上面的放大图像只是一个例子。
Edit: I had written this code to take effect on image ...编辑:我写了这段代码来对图像生效......
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){
}
}
Even after running the code, there is no change in my image.即使在运行代码之后,我的图像也没有变化。
Even if the red, green and blue values are above 200, my image is not changing.即使红色、绿色和蓝色值高于 200,我的图像也没有变化。
UPDATE : Saving the image as ".png" rather than ".jpg" worked!更新:将图像保存为“.png”而不是“.jpg”有效!
You can go through each pixel in the image and determine if it is above a certain threshold, if it is set its value to pure white.您可以查看图像中的每个像素并确定它是否高于某个阈值,是否将其值设置为纯白色。 You can also do the same for the darker areas if needed.如果需要,您也可以对较暗的区域执行相同操作。
Example:例子:
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.