2014-04-15 79 views
0

使用ImageFilter,我們如何過濾Java中的多種顏色?在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(250,251,255),RGB(253,255,241),RGB的不同組合等

是使用我們的肉眼你可能沒有注意到,但如果我們要使用數字色彩計或任何可能檢查圖像的工具,我們可以注意到它們之間的差異。

是否可以過濾多種顏色?有什麼建議麼。

在此先感謝。

回答

1

有多種方法可以做到這一點取決於你想要

什麼,我會建議你創建一個決定需要過濾

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); 
} 
+0

感謝BevynQ什麼顏色的方法。我會嘗試這一個。 – chadtooltwist