2016-09-18 125 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個通道從全強一些輕微的偏差。這取決於你決定有多少餘量。