2016-09-18 35 views
1

我想删除图像的白色背景并将其另存为另一图像。 我写了一段代码,它提取背景,但它留下一些像素值。 结帐原始图像:enter image description here如何删除图像的白色背景 - java

结帐裁剪图像:enter image description here

它仍然留下的白色背景的一些量。

我想删除它也。

这里是我的代码:

 int x1=0; 
    int y1=0; 
    boolean res = false; 
    System.out.println("in formatImage"); 

// Widht去除...

for (int x = 0; x <= w-1; x++) { 
      for (int y = 0; y <= h-1; y++) { 
       if(new Color(bi1.getRGB(x, y)).getRGB()==-1) 
       {res=false;} 
       else if (!new Color(bi1.getRGB(x, y)).equals(Color.WHITE)) { 
        res = true; 
       } 
       if (res) { 
        for (int p = y; p <= h-1; p++) { 
         b21.setRGB(x1,p,new Color(bi1.getRGB(x, p)).getRGB());       
        } 
        x1++; 
        res = false; 
        break; 
       } 
      } 
     } 
     b21=new BufferedImage(x1,h,BufferedImage.TYPE_INT_RGB); 
     x1=0; 
     for (int x = 0; x <= w-1; x++) { 
      for (int y = 0; y <= h-1; y++) { 
       if(new Color(bi1.getRGB(x, y)).getRGB()==-1) 
       {res=false;} 
       else if (!new Color(bi1.getRGB(x, y)).equals(Color.WHITE)) { 
        res = true; 
       } 
       if (res) { 
        for (int p = 0; p <= h-1; p++) { 
         b21.setRGB(x1,p,new Color(bi1.getRGB(x, p)).getRGB()); 
        } 
        x1++; 
        res = false; 
        break; 
       } 
      } 
     } 

//高度去除

for (int y = 0; y <= h-1; y++) { 
    System.out.println("Y = "+y); 
    for (int x = 0; x <= x1-1; x++) { 
     System.out.println("("+x+","+y+") : "+b21.getRGB(x, y)); 
     if (!new Color(b21.getRGB(x, y)).equals(Color.WHITE)) { 
      res = true; 
     } 
     if (res) { 
      for (int p = 0; p <= x1-1; p++) { 
       b31.setRGB(p,y1,new Color(b21.getRGB(p, y)).getRGB()); 

      } 
      y1++; 
      res = false; 
      break; 
     } 
    } 
} 
b31=new BufferedImage(x1,y1,BufferedImage.TYPE_INT_RGB); 
int ty=y1; 
y1=0; 
for (int y = 0; y <= h-1; y++) { 
    for (int x = 0; x <= x1-1; x++) { 
     if (!new Color(b21.getRGB(x, y)).equals(Color.WHITE)) { 
      res = true; 
     } 
     if (res) { 
      for (int p = 0; p <= x1-1; p++) { 
       b31.setRGB(p,y1,new Color(b21.getRGB(p, y)).getRGB()); 
      } 
      y1++; 
      res = false; 
      break; 
     } 
    } 
} 

B31拥有最终图像。

+0

你是什么意思的“删除白色背景”?你真的在问如何修剪图像吗?这似乎是你的代码所做的。什么不起作用?什么部分的白色背景没有被删除?你的问题不清楚。 –

+0

近手背景不会被删除。您可以通过下载图像来查看相同的内容 –

回答

1

正如Jim所说, 身体附近的颜色不是纯白色。 因此,您修改了代码&的以下声明,它对您很有帮助。 通过

if (new Color(b21.getRGB(x, y)).getRGB()<-1000000) 

替换以下命令行

if (!new Color(b21.getRGB(x, y)).equals(Color.WHITE)) 

这会给你想要的输出。 你可以改变白色&灰色从-1000000到-2000000的色调

2

如果使用任何体面的图像编辑器检查图像,您会发现靠近模型头部,左手和右手肘的像素不是纯白色(0xFFFFFF)。

enter image description here

您需要调整您的算法,允许在所有3个通道从全强一些轻微的偏差。这取决于你决定有多少余量。