java - 在Java中过滤多种颜色?

标签 java colors awt imagej

使用ImageFilter,我们如何在Java中过滤多种颜色?

在这篇文章中。

http://www.javaworld.com/article/2074105/core-java/making-white-image-backgrounds-transparent-with-java-2d-groovy.html

他成功过滤了白色(RGB - 255, 255, 255)。

public static Image makeColorTransparent(final BufferedImage im, final Color color)
{
  final ImageFilter filter = new RGBImageFilter()
  {
     // the color we are looking for (white)... Alpha bits are set to opaque
     public int markerRGB = color.getRGB() | 0xFFFFFFFF;

     public final int filterRGB(final int x, final int y, final int rgb)
     {
        if ((rgb | 0xFF000000) == markerRGB)
        {
           // Mark the alpha bits as zero - transparent
           return 0x00FFFFFF & rgb;
        }
        else
        {
           // nothing to do
           return rgb;
        }
     }
  };

  final ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
  return Toolkit.getDefaultToolkit().createImage(ip);
}
}

我想过滤相关颜色,因为我们图像的背景没有完美的白色背景 - RGB(255, 255, 255)。

白色有不同的 RGB 组合,如 RGB(250, 251, 255)、RGB (253, 255, 241) 等。

您可能不会用我们的肉眼注意到这一点,但如果我们要使用数字色度计或任何可以检查图像的工具,我们可以注意到差异。

是否可以过滤多种颜色?任何建议。

提前致谢。

最佳答案

根据您的需要,您可以通过多种方式实现此目的

我建议您创建一个方法来确定需要过滤哪些颜色

if (filterColour(rgb)){
...
}


// method one predefine a set of colours that are near white
// suitable if you do not have too many colours or colors you want to
// filter are distinct from one another
private boolean filterColour(int rgb){
     return whiteishColours.contains(rgb);
}


//method two convert to HSV then use brightness and saturation to determine
//a zone of colours to filter
//I have not merged the components for this
private boolean filterColour(int r, int g, int b){
    float[] hsv = new float[3];
    Color.RGBtoHSB(r,g,b,hsv);
    return (hsv[2] > 0.9 && hsv.[1] < 0.1);
}

关于java - 在Java中过滤多种颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23075015/

相关文章:

java - Log4j,将 Web 应用配置为使用相对路径

java - 有没有一种简单的方法可以创建由多个附加文件组成的 Java InputStream?

twitter-bootstrap - 如何更改链接颜色( Bootstrap )

Android:是否可以在 colors.xml 中包含文件中的颜色定义

ios - 如何防止单元格在另一个单元格中镜像按钮按下操作?

java - 碰撞检查方法适用于 Mac,但不适用于 PC

java - Canvas 对象未显示,但位置在 Java Applet 中正确更新

java - 如何从像素绘制 3D 对象?

java - 抑制 Domino 控制台消息 "error connecting to server ... the remote server..."

java - 对象的内存大小(字节)