Java 替换图像的背景
Java replacing the background of an image
我正在编写一个程序,拍一张照片并替换该照片的背景。
我的图片是:
我为猫使用的背景是:
我知道为此我必须使用猫图片并采用小于 255 的彩色像素,因为白色的红色、绿色和蓝色值为 255。然后我采用那些像素小于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();
}
}
我只是想知道您能否帮我弄清楚如何将我理解的这个程序的概念转化为代码
谢谢
你所拥有的几乎是正确的。只需阅读你的第二张图片,就像你在这里看到你的第一张图片一样:
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
我正在编写一个程序,拍一张照片并替换该照片的背景。
我的图片是:
我为猫使用的背景是:
我知道为此我必须使用猫图片并采用小于 255 的彩色像素,因为白色的红色、绿色和蓝色值为 255。然后我采用那些像素小于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();
}
}
我只是想知道您能否帮我弄清楚如何将我理解的这个程序的概念转化为代码
谢谢
你所拥有的几乎是正确的。只需阅读你的第二张图片,就像你在这里看到你的第一张图片一样:
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