如果我有数字的 RBG 代码,例如-16777216
(黑色),如何使用此颜色代码找到其他类似的黑色阴影?
我试图通过标记所有不是-16777216
白色的像素来将图像转换为单色。但是,通常会发现不同深浅的黑色,但由于不完全匹配而丢失了。
编辑:我遇到了一些麻烦。当我尝试使用这种颜色来查找黑色阴影时,我可以在将其他像素转换为白色时忽略它们,这是我的结果:
资源:
结果:
代码:
package test;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
public class Test
{
public static void main(String[] args)
{
try
{
BufferedImage source = ImageIO.read( new URL("http://i.imgur.com/UgdqfUY.png"));
//-16777216 = black:
BufferedImage dest = makeMonoChromeFast(source, -16777216);
File result = new File("D:/result.png");
ImageIO.write(dest, "png", result);
}
catch (Exception e)
{
e.printStackTrace();;
}
}
public static BufferedImage makeMonoChromeFast(BufferedImage source, int foreground)
{
int background = -1; //white;
Color fg = new Color(foreground);
int color = 0;
for (int y = 0; y < source.getHeight(); y++)
{
for (int x = 0; x < source.getWidth(); x++)
{
color = source.getRGB(x, y);
if ( color == foreground )
continue;
if (! isIncluded(fg, color, 50))
source.setRGB(x, y, background);;
}
}
return source;
}
public static boolean isIncluded(Color target, int pixelColor, int tolerance)
{
Color pixel = new Color(pixelColor);
int rT = target.getRed();
int gT = target.getGreen();
int bT = target.getBlue();
int rP = pixel.getRed();
int gP = pixel.getGreen();
int bP = pixel.getBlue();
return(
(rP-tolerance<=rT) && (rT<=rP+tolerance) &&
(gP-tolerance<=gT) && (gT<=gP+tolerance) &&
(bP-tolerance<=bT) && (bT<=bP+tolerance) );
}
}