So I'm pretty lost in Python. My teacher doesn't explain the commands for Python so I'm really confused on how to write this. I have to write a green screen type program that takes a picture with a green background and replaces it with another picture by looking at the color levels of each pixel and if the green color is a certain amount larger than blue/red then it will replace it with the other pictures pixel.

The pseudo code I have is:

#show the before pictures
#for each pixel in the foreground image:
# we first get the red, green and blue of this pixel
# if the red plus blue is greater than green (*)
# get the pixel from the background image at foreground pixel's location (**)
# set the background pixel's color to be the color obtained from the fg
#show the resulting picture (repaint)
#write the new picture to a file

You can use the writePictureTo(picture, path) function to save the image.

I know the basics to the program with the getRed()/blue/green and setRed(), but I don't know what to do about finding certain pixels in the foreground. Can someone help me with the code?

We are using JES version of python in class as well.

Any help would be greatly appreciated.

Recommended Answers

All 2 Replies

I use PIL and pygame for image processing stuff.

The best way to grab pixel data from PIL is:

import Image

im = Image.open("image.jpg")

#some redundant size variables, this is ugly and an example only
res = im.size
xres = im.size[0]
yres = im.size[1]

for x in range(0,xres):
    for y in range(0,yres):

        #do your pixel compare here

        print im[x,y] #show RBG pixel value
        print im[x,y][0] #show Red channel
        print im[x,y][1] #show Blue channel
        print im[x,y][2] #show Green channel

Pygame is just as trivial.
To blit pictures not from pygame to the screen, you will need to use something like:

shot = pygame.image.frombuffer(im.tostring(), res, "RGB")

This is not working code though, just snippets, you will need to look through the docs of both.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.