Java 查找图像上的透明像素并使相同像素在另一图像上透明

Java 查找图像上的透明像素并使相同像素在另一图像上透明,java,image,processing,png,transparency,Java,Image,Processing,Png,Transparency,我有两张照片。第二个是对第一个应用某种遮罩的结果。我需要的是得到那个面具,并能把它应用到其他图像上。 以下是两张图片: 正如你所看到的,第二个有破烂的边缘,它们是透明的,不是白色的。 (还有一些模糊,如果有一种方法我能找出它到底是什么,那就太好了,但这里真的没有必要) 我需要的是能够从第一个图像创建第二个图像 理论上,我应该创建一个遮罩-一个大小相同的图像,具有任何颜色,每个像素的透明度为0或255,这取决于上面第二个图像中相同像素的透明度值。然后我可以将任何输入图像的像素的alpha值设置为这

我有两张照片。第二个是对第一个应用某种遮罩的结果。我需要的是得到那个面具,并能把它应用到其他图像上。 以下是两张图片:

正如你所看到的,第二个有破烂的边缘,它们是透明的,不是白色的。 (还有一些模糊,如果有一种方法我能找出它到底是什么,那就太好了,但这里真的没有必要)

我需要的是能够从第一个图像创建第二个图像

理论上,我应该创建一个遮罩-一个大小相同的图像,具有任何颜色,每个像素的透明度为0或255,这取决于上面第二个图像中相同像素的透明度值。然后我可以将任何输入图像的像素的alpha值设置为这个掩码的alpha值

然而,我不知道如何切实做到这一点。我使用BuffereImage在java中尝试了它,但是,它不起作用。当我尝试从所选像素的颜色获取Alpha时,它始终是255,即使对于应该是透明的像素也是如此。我确实在处理过程中获得了alpha值(它们实际上不仅仅是0或255,中间有很多值),但是,当我尝试将此值应用到新图像并保存它时,它会保存为完全不透明的图像,当我加载它时,alpha值都是255

  PImage mask = loadImage("some/path/1.png");
  PImage img = loadImage("some/path/2.png");

  img.loadPixels();
  for (int x = 0; x < img.width; x++) {
    for (int y = 0; y < img.height; y++) {
      color maskColor = mask.get(x, y);
      if (alpha(maskColor) < 255) {
        color imgColor = img.get(x, y);
        img.pixels[y*img.width + x] = color(red(imgColor), green(imgColor), blue(imgColor), alpha(maskColor));
      }
    }
  }
  img.updatePixels();
  img.save("some/path/3.png"); 
PImage mask=loadImage(“some/path/1.png”);
PImage img=loadImage(“some/path/2.png”);
img.loadPixels();
对于(int x=0;x
您可以尝试获取原始图像和破损图像的alpha通道之间的差异

PImage tattered = loadImage("some/path/1.png");
PImage img = loadImage("some/path/2.png");
PImage mask = image.copy();

img.loadPixels();

for (int x = 0; x < img.width; x++) {
   for (int y = 0; y < img.height; y++) {
      mask[x][y] = abs(alpha(img.get(x, y)) - alpha(tattered.get(x, y)));
    }
}

mask.updatePixels();
mask.save("some/path/3.png"); 

PImage-tattered=loadImage(“some/path/1.png”);
PImage img=loadImage(“some/path/2.png”);
PImage mask=image.copy();
img.loadPixels();
对于(int x=0;x
您也可以将破损图像用作其他图像的遮罩。您只需要来自遮罩的alpha信息。
使用BuffereImage创建破损边界的实现:

public class Test {

    public static void main(String[] args) throws IOException {
        
         BufferedImage mask = loadImage("e:\\mask.png");
         BufferedImage img = loadImage("e:\\1.png");

         int width = mask.getWidth();
         int height = mask.getHeight();
         
         BufferedImage processed = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);

          for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
              int rgb = mask.getRGB(x,y);
              int maskAlpha = alpha(rgb);
              int imgColor = img.getRGB(x, y);
              if (maskAlpha < 255) {
                processed.setRGB(x,y,maskAlpha(imgColor, maskAlpha));
              } else {
                  processed.setRGB(x,y,imgColor);
              }
            }
          }
         
          writeImage(processed, "e:\\2.png");
    }

    static BufferedImage loadImage(String imagePath) {
        File file = new File(imagePath);
        BufferedImage image = null;
        try {
            image = ImageIO.read(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }
    
    static void writeImage(BufferedImage img,String filePath){
        String format = filePath.substring(filePath.indexOf('.')+1);
        //Get Picture Format
        System.out.println(format);
        try {
            ImageIO.write(img,format,new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    static int maskAlpha(int rgb, int alpha) {
        //strip alpha from original color
        int color = (0x00ffffff&rgb);
        return color + ((alpha)<<24);
    }
    
    static int alpha(int rgb) {
        return (0xff&(rgb>>24));
    }
    
    static int red(int rgb) {
        return (0xff&rgb);
    }
    static int green(int rgb) {
        return (0xff&(rgb>>8));
    }
    static int blue(int rgb) {
        return (0xff&(rgb>>16));
    }
}

使用
buffereImage
Graphics2D
AlphaComposite
,您可以像这样合成图像:

BufferedImage image = ImageIO.read(new File("image.png"));
BufferedImage mask = ImageIO.read(new File("mask.png"));

BufferedImage composed = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = composed.createGraphics();
try {
    g.setComposite(AlphaComposite.Src); // Possibly faster than SrcOver
    g.drawImage(image, 0, 0, null);

    // Clear out the transparent parts from mask
    g.setComposite(AlphaComposite.DstIn);
    g.drawImage(mask, 0, 0, null);
}
finally {
    g.dispose();
}

if (!ImageIO.write(composed, "PNG", new File("composed.png"))) {
    throw new IIOException("Could not write image using PNG format: " + composed);
}

PS:如果你知道你的源图像(
image
在上面的代码中)包含透明度,并且之后不需要原始图像,你可以直接在上面合成遮罩。这将更快,使用更少的内存,因为您跳过了内存分配和额外的排版。

我不确定为什么在您的特定示例中需要进行检查。如果目标图像不使用alpha通道(完全不透明),则可以使用源图像的alpha通道覆盖数据

顺便说一下,如果您使用的是
像素[]
,单循环应该可以:

PImage withAlpha;
PImage noAlpha;

void setup(){
  size(120, 130);
  background(0);
  
  withAlpha = loadImage("8fXFk.png");
  noAlpha = loadImage("AOsi0.png");
  
  copyAlphaChannel(withAlpha, noAlpha);
}

void draw(){
  background(map(sin(frameCount * 0.1), -1.0, 1.0, 0, 192), 0, 0);
  image(withAlpha, 0, 0);
  image(noAlpha, 60, 0);
}

void copyAlphaChannel(PImage src, PImage dst){
  // quick error check
  if(src.width != dst.width || src.height != dst.height){
    println(String.format("error, mismatching dimensions src(%d,%d) != dst(%d,%d)",
            src.width, src.height, dst.width, dst.height));
    return;
  }
  // load pixel data
  src.loadPixels();
  dst.loadPixels();
  
  int numPixels = src.pixels.length;
  // for each pixel
  for(int i = 0 ; i < numPixels; i++){
      // extract source alpha
      int srcAlpha = (src.pixels[i] >> 24) & 0xFF;
      // apply it to the destination image
      //              src alpha      |   dst RGB
      dst.pixels[i] = srcAlpha << 24 | (dst.pixels[i] & 0xFFFFFF);
  }
  
  dst.updatePixels();
}
由于上述循环多次通过像素(一次创建遮罩,然后再次应用遮罩),因此首先创建
ARGB
PImage
,然后从一个
PImage
复制
RGB
数据和从另一个
ALPHA
复制
数据可能更有效:

PImage withAlpha;
PImage noAlpha;

void setup(){
  size(120, 130);
  background(0);
  
  withAlpha = loadImage("8fXFk.png");
  noAlpha = loadImage("AOsi0.png");
  
  println("before",withAlpha.format, noAlpha.format, ARGB, RGB); // notice noAlpha's format is RGB
  
  noAlpha = getAlphaChannelCopy(withAlpha, noAlpha);
  
  println("after",withAlpha.format, noAlpha.format, ARGB, RGB); // notice noAlpha's format is ARGB
  
  noAlpha.save("test.png");
  
}

void draw(){
  background(map(sin(frameCount * 0.1), -1.0, 1.0, 0, 192), 0, 0);
  image(withAlpha, 0, 0);
  image(noAlpha, 60, 0);
}

// copy src alpha and dst rgb into new ARGB PImage
PImage getAlphaChannelCopy(PImage src, PImage dst){
  // quick error check
  if(src.width != dst.width || src.height != dst.height){
    println(String.format("error, mismatching dimensions src(%d,%d) != dst(%d,%d)",
            src.width, src.height, dst.width, dst.height));
    return null;
  }
  PImage out = createImage(src.width, src.height, ARGB);
  // load pixel data
  src.loadPixels();
  dst.loadPixels();
  out.loadPixels();
  
  int numPixels = src.pixels.length;
  // for each pixel
  for(int i = 0 ; i < numPixels; i++){
      // extract source alpha
      int srcAlpha = (src.pixels[i] >> 24) & 0xFF;
      // apply it to the destination image
      //              src alpha      |   dst RGB
      out.pixels[i] = srcAlpha << 24 | (dst.pixels[i] & 0xFFFFFF);
  }
  
  out.updatePixels();
  
  return out;
}
PImage与alpha;
PImage noAlpha;
无效设置(){
大小(120130);
背景(0);
withAlpha=loadImage(“8fXFk.png”);
noAlpha=loadImage(“AOsi0.png”);
println(“before”,withAlpha.format,noAlpha.format,ARGB,RGB);//注意noAlpha的格式是RGB
noAlpha=获取Alpha通道拷贝(带Alpha,noAlpha);
println(“after”,withAlpha.format,noAlpha.format,ARGB,RGB);//注意noAlpha的格式是ARGB
noAlpha.save(“test.png”);
}
作废提款(){
背景(地图(sin(帧数*0.1),-1.0,1.0,0192),0,0);
图像(带alpha,0,0);
图像(noAlpha,60,0);
}
//将src alpha和dst rgb复制到新的ARGB PImage中
PImage getAlphaChannelCopy(PImage src、PImage dst){
//快速错误检查
如果(src.width!=dst.width | | src.height!=dst.height){
println(String.format(“错误,尺寸不匹配,src(%d,%d)!=dst(%d,%d)”,
src.width、src.height、dst.width、dst.height);
返回null;
}
PImage out=createImage(src.width、src.height、ARGB);
//加载像素数据
src.loadPixels();
加载像素();
out.loadPixels();
int numPixels=src.pixels.length;
//对于每个像素
对于(int i=0;i>24)&0xFF;
//将其应用于目标图像
//src alpha | dst RGB

out.pixels[i]=srcAlpha它起作用了。非常感谢你的代码和解释,我现在明白了。我想问题是我没有指定buffereImage.TYPE_4BYTE_ABGR,所以alpha总是255。回答得好!就像指出有一个更简单的方法。只需创建一个透明的新图像,将图像绘制到其中,在DST\u即可ode>规则并绘制遮罩图像(以更改边缘的透明度)。它确实会在屏幕上加载两个图像的透明度,是的。但是,当我在setup()末尾添加noAlpha.save(“out.png”)时,出于某种原因,它会在不带透明度的情况下保存图像。@Jack确实如此!感谢您指出这一点。请参阅上面更新的内容
PImage withAlpha;
PImage noAlpha;

void setup(){
  size(120, 130);
  background(0);
  
  withAlpha = loadImage("8fXFk.png");
  noAlpha = loadImage("AOsi0.png");
  
  println("before",withAlpha.format, noAlpha.format, ARGB, RGB); // notice noAlpha's format is RGB
  
  forceAlphaChannel(noAlpha);
  
  println("after",withAlpha.format, noAlpha.format, ARGB, RGB); // notice noAlpha's format is ARGB
  
  copyAlphaChannel(withAlpha, noAlpha);
  
  noAlpha.save("test.png");
  
}

void draw(){
  background(map(sin(frameCount * 0.1), -1.0, 1.0, 0, 192), 0, 0);
  image(withAlpha, 0, 0);
  image(noAlpha, 60, 0);
}

void forceAlphaChannel(PImage src){
  // make an opaque mask
  PImage mask = createImage(src.width, src.height, ALPHA);
  java.util.Arrays.fill(mask.pixels, color(255));
  mask.updatePixels();
  // apply the mask force the RGB image into ARGB format
  src.mask(mask);
}

void copyAlphaChannel(PImage src, PImage dst){
  // quick error check
  if(src.width != dst.width || src.height != dst.height){
    println(String.format("error, mismatching dimensions src(%d,%d) != dst(%d,%d)",
            src.width, src.height, dst.width, dst.height));
    return;
  }
  // load pixel data
  src.loadPixels();
  dst.loadPixels();
  
  int numPixels = src.pixels.length;
  // for each pixel
  for(int i = 0 ; i < numPixels; i++){
      // extract source alpha
      int srcAlpha = (src.pixels[i] >> 24) & 0xFF;
      // apply it to the destination image
      //              src alpha      |   dst RGB
      dst.pixels[i] = srcAlpha << 24 | (dst.pixels[i] & 0xFFFFFF);
  }
  
  dst.updatePixels();
}
PImage withAlpha;
PImage noAlpha;

void setup(){
  size(120, 130);
  background(0);
  
  withAlpha = loadImage("8fXFk.png");
  noAlpha = loadImage("AOsi0.png");
  
  println("before",withAlpha.format, noAlpha.format, ARGB, RGB); // notice noAlpha's format is RGB
  
  noAlpha = getAlphaChannelCopy(withAlpha, noAlpha);
  
  println("after",withAlpha.format, noAlpha.format, ARGB, RGB); // notice noAlpha's format is ARGB
  
  noAlpha.save("test.png");
  
}

void draw(){
  background(map(sin(frameCount * 0.1), -1.0, 1.0, 0, 192), 0, 0);
  image(withAlpha, 0, 0);
  image(noAlpha, 60, 0);
}

// copy src alpha and dst rgb into new ARGB PImage
PImage getAlphaChannelCopy(PImage src, PImage dst){
  // quick error check
  if(src.width != dst.width || src.height != dst.height){
    println(String.format("error, mismatching dimensions src(%d,%d) != dst(%d,%d)",
            src.width, src.height, dst.width, dst.height));
    return null;
  }
  PImage out = createImage(src.width, src.height, ARGB);
  // load pixel data
  src.loadPixels();
  dst.loadPixels();
  out.loadPixels();
  
  int numPixels = src.pixels.length;
  // for each pixel
  for(int i = 0 ; i < numPixels; i++){
      // extract source alpha
      int srcAlpha = (src.pixels[i] >> 24) & 0xFF;
      // apply it to the destination image
      //              src alpha      |   dst RGB
      out.pixels[i] = srcAlpha << 24 | (dst.pixels[i] & 0xFFFFFF);
  }
  
  out.updatePixels();
  
  return out;
}