Java替换图像的背景

Java替换图像的背景,java,image,colors,background,pixel,Java,Image,Colors,Background,Pixel,我正在写一个程序,在这个程序中,我拍摄了一张照片并替换了那张照片的背景 我的照片是: 我在猫身上使用的背景是: 我知道,为了实现这一点,我必须使用cat图片并拍摄小于255的彩色像素,因为白色的红色、绿色和蓝色值为255。然后,我把组成cat的小于255的像素放在背景图片的相同X和Y位置。我遇到的问题是,我不知道如何编写代码使其工作 我的基本代码是: import java.awt.*; public class TrueColors { public static void mai

我正在写一个程序,在这个程序中,我拍摄了一张照片并替换了那张照片的背景

我的照片是:

我在猫身上使用的背景是:

我知道,为了实现这一点,我必须使用cat图片并拍摄小于255的彩色像素,因为白色的红色、绿色和蓝色值为255。然后,我把组成cat的小于255的像素放在背景图片的相同X和Y位置。我遇到的问题是,我不知道如何编写代码使其工作

我的基本代码是:

import java.awt.*;
public class TrueColors
{

   public static void main(String [] args) 
   {
       Picture pictureObj2 = new Picture("9.01 cat picture.jpg");
       pictureObj2.explore();
       int redValue = 0; int greenValue = 0; int blueValue = 0;

       Pixel targetPixel = new Pixel(pictureObj2, 0, 0);
       Color pixelColor = null;

       for(int y = 0; y < pictureObj2.getHeight(); y++)
       {
           for(int x = 0; x < pictureObj2.getWidth(); x++)
           {
               targetPixel = pictureObj2.getPixel(x,y);
               pixelColor = targetPixel.getColor();

               redValue = pixelColor.getRed();
               greenValue = pixelColor.getGreen();
               blueValue = pixelColor.getBlue();

               pixelColor = new Color(redValue, greenValue, blueValue);
               targetPixel.setColor(pixelColor);

           }
       }

       pictureObj2.explore();
       pictureObj2.write("ColoredCat.jpg");
       pictureObj2.show();

   }   
}
import java.awt.*;
公共类真彩色
{
公共静态void main(字符串[]args)
{
Picture pictureObj2=新图片(“9.01 cat Picture.jpg”);
pictureObj2.explore();
int redValue=0;int greenValue=0;int blueValue=0;
像素targetPixel=新像素(pictureObj2,0,0);
颜色像素颜色=空;
对于(int y=0;y
我只是想知道你是否能帮我弄明白如何把我理解的这个程序的概念转化成代码


谢谢你

你所说的几乎是正确的。只需阅读第二张图片,就像这里有第一张图片一样:

Picture background = new Picture("background.png");
background.explore();
然后在内部循环中,只需执行以下操作:

targetPixel = pictureObj2.getPixel(x,y);
pixelColor = targetPixel.getColor();

if(!pixelColor.equals(WHITE)) //test if you have a blank pixel
    background.getPixel(x,y).setColor(pixelColor); //if not its a cat pixel so add it on top of the background
实际上,RGB(0,0,0)是黑色的。您需要的是RGB(255255255)(所有颜色的最大值),它是白色的。