Green Screen

Solve It

For this problem, you will implement the green screen (also known as "chromakey") algorithm. As you have learned, this problem involves taking a foreground image taken in front of a green screen and combining it with a background image. We will replace all green pixels in the foreground image with the corresponding pixel from the background image. We begin by making an output image the same size as the foreground. Then we copy pixels from the foreground into the new image, unless they are green. A green pixel does not get copied, but the corresponding background pixel gets copied instead.

We have provided a picture of Drew and Robert with a flat green background for you to use as a foreground image, as well as a picture of dinosaurs in outer space to use as a background image. Of course, you can also use your own images. Use your own background to put Drew and Robert somewhere fun and creative! Or, if you have an image with a flat green background, use your own foreground image too. Just make sure the background image is at least as large as the foreground.

Code It

//Start with the foreground image you want (fgImage) var fgImage = new SimpleImage("drewRobert.png"); //... and with the background image you want (bgImage) var bgImage = new SimpleImage("dinos.png"); //Make a blank image of the same size (output) var output = new SimpleImage(fgImage.getWidth(), fgImage.getHeight()); //write code for each of these steps: //For each pixel (currentPixel) in fgImage for (var pixel of fgImage.values()) { //Look at currentPixel and if it is green, if (pixel.getGreen() > pixel.getRed() + pixel.getBlue()) { //Look at same position in bgImage var x = pixel.getX(); var y = pixel.getY(); var bgPixel = bgImage.getPixel(x, y); //and set output's corresponding pixel to bgImage's pixel output.setPixel(x, y, bgPixel); } //Otherwise: set output's corresponding pixel to currentPixel else { output.setPixel(pixel.getX(), pixel.getY(), pixel); } } //show our answer! print(output);

See It


Available Images



Drop your images onto the area above to make it available within your code editor on this page. Note: your images will not be uploaded anywhere, they will stay on your computer.