Beam Me Up, Scotty
# Function for testing the chromakey function. This is from the Pictures section of the course
def testChromakey():
fgFile = getMediaPath("bart2.png")
fgPic = makePicture(fgFile)
bgFile = getMediaPath("sting2.jpg")
bgPic = makePicture(bgFile)
show(bgPic)
bgColor = green # Because the Bart picture has a green background
chromakeyBlend(fgPic, bgPic, bgColor, 0.5)
repaint(bgPic)
# Function for doing chromakey of a foreground(fg) picture on a background(bg), using a reference color
# We covered this in the Pictures section of the course.
def chromakey(fgPic, bgPic, refColor):
threshold = 100
offset = getHeight(bgPic) - getHeight(fgPic)
for fgPixel in getPixels(fgPic):
if distance(getColor(fgPixel), refColor) > threshold:
bgPixel = getPixel(bgPic, getX(fgPixel), getY(fgPixel) + offset)
setColor(bgPixel, getColor(fgPixel))
# Almost exact copy of chromakey. The difference, is that we blend pixels instead of replacing them.
# Which means we need a degree parameter to say how much to blend the fg into the bg.
# You can implement chromakey using chromakeyBlend if you use a degree of 1.0
def chromakeyBlend(fgPic, bgPic, refColor, degree):
threshold = 100
offset = getHeight(bgPic) - getHeight(fgPic)
for fgPixel in getPixels(fgPic):
if distance(getColor(fgPixel), refColor) > threshold:
bgPixel = getPixel(bgPic, getX(fgPixel), getY(fgPixel) + offset)
r = getRed(fgPixel)*degree + getRed(bgPixel)*(1.0-degree)
g = getGreen(fgPixel)*degree + getGreen(bgPixel)*(1.0-degree)
b = getBlue(fgPixel)*degree + getBlue(bgPixel)*(1.0-degree)
setColor(bgPixel, makeColor(r,g,b))
# Use chromakeyBlend to simulate a materialization video effect.
# The fourth parameter is the length of the movie in frames. (Use a small number or you will be waiting a long time).
def materializeMovie(fg, bg, refColor, frames):
for frameNum in range(0, frames):
printNow("Frame " + str(frameNum))
printNow(" duplicating...")
canvas = duplicatePicture(bg)
printNow(" blending...")
# This line makes fg image materialize. Comment it out and replace by the next line to make fg dematerialize
#chromakeyBlend(fg, canvas, refColor, ((frameNum*1.0)/frames))
# Next line makes fg image dematerialize. Comment out previous line and remove comment on next line to make it work
# In class, I had a senior moment and suggested we do frames-(((frames/100.0)*frameNum) (actually, we were using frames=20).
# You should, of course, subtract from the maximum value, which is 1.0, not frames.
chromakeyBlend(fg, canvas, refColor, 1.0-((frameNum*1.0)/frames))
frameString = str(frameNum)
if frameNum < 10:
frameString = "0" + frameString
writePictureTo(canvas, getMediaPath("materialize" + frameString + ".jpg"))
Link to this Page