我想删除一个图像的白色背景,并将其另存为另一个图像。我已经写了一段代码来提取背景,但它留下了一些像素值。检出原始图像:

检出裁剪后的图像:

它仍然会留下一些白色的背景。
我也想把它去掉。
下面是我的代码:
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有最终图像。
发布于 2016-09-18 17:56:24
正如吉姆所说,身体附近的颜色不是纯白的。因此,您可以修改代码的以下语句&它将为您带来极大的好处。替换以下命令行
if (!new Color(b21.getRGB(x, y)).equals(Color.WHITE)) 通过
if (new Color(b21.getRGB(x, y)).getRGB()<-1000000) 这将为您提供所需的输出。你可以改变白色和灰色的阴影,从-1000000到-2000000
发布于 2016-09-18 13:30:40
如果你用任何像样的图像编辑器检查图像,你会发现模型头部、左手和右肘附近的像素不是纯白色(0xFFFFFF)。

您需要调整算法,以便在所有3个通道上允许与全强度的一些轻微偏差。允许多大的回旋余地由您决定。
发布于 2020-03-02 16:34:36
我创建了一个将白色背景转换为透明背景的函数
public Image makeWhiteBGToTransparent(final BufferedImage im) {
final ImageFilter filter = new RGBImageFilter() {
public int markerRGB = 0xFFFFFFFF;
public final int filterRGB(final int x, final int y, final int rgb) {
if ((rgb | 0xFF000000) == markerRGB) {
return 0x00FFFFFF & rgb;
} else {
return rgb;
}
}
};
final ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(ip);
}现在,如果我们想要将这个Image转换成BufferedImage,那么使用这个函数
public BufferedImage toBufferedImage(Image img) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
BufferedImage bImage = new BufferedImage(img.getWidth(null), img.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics2D bGr = bImage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
return bImage;
}https://stackoverflow.com/questions/39554300
复制相似问题