#!/usr/bin/python import Image, sys, string, time, math from pyglet.gl import * if len(sys.argv) not in [5,6]: print "Usage: chromakey inimage r g b [distance]" sys.exit(1) def distanceSquared(a,b): d0 = a[0] - b[0] d1 = a[1] - b[1] d2 = a[2] - b[2] return d0*d0 + d1*d1 + d2*d2 inimg = Image.open(sys.argv[1]).convert('RGB') keyedTexImg = inimg.convert('RGBA') bgcolor = (string.atoi(sys.argv[2]), string.atoi(sys.argv[3]), string.atoi(sys.argv[4])) if len(sys.argv) == 6: maxdistance = string.atoi(sys.argv[5]) else: maxdistance = 0 maxdistanceSquared = maxdistance * maxdistance for x in range(0,inimg.size[0]): for y in range(0,inimg.size[1]): color = inimg.getpixel((x,y)) if distanceSquared(color,bgcolor) <= maxdistanceSquared: keyedTexImg.putpixel((x,y), (color[0], color[1], color[2], 0)) window = pyglet.window.Window() def createTexture(teximg): teximg = teximg.transpose(Image.FLIP_TOP_BOTTOM) textureIDs = (pyglet.gl.GLuint * 1) () glGenTextures(1,textureIDs) textureID = textureIDs[0] glBindTexture(GL_TEXTURE_2D, textureID) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, teximg.size[0], teximg.size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, teximg.tostring()) glBindTexture(GL_TEXTURE_2D, 0) return textureID class TexAlphaSquare: def __init__(self, width, height, xpos, ypos, texturefile, color): self.xpos = xpos self.ypos = ypos self.heading = 0 self.color = color if texturefile: if type(texturefile) == str: img = pyglet.image.load(texturefile) self.texture = img.get_texture() else: self.texture = texturefile self.texture.id = createTexture(texturefile) else: self.texture = None verts = [-width/2.0, -height/2.0, width/2.0, -height/2.0, -width/2.0, height/2.0, width/2.0, height/2.0] texcoords = [0,0, 1,0, 0,1, 1,1] self.vlist = pyglet.graphics.vertex_list(4, ('v2f', verts), ('t2f', texcoords)) def draw(self): glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) if self.texture: glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.texture.id) glColor4f(self.color[0], self.color[1], self.color[2], self.color[3]) glPushMatrix() glTranslatef(self.xpos, self.ypos, 0) glRotatef(self.heading, 0, 0, 1) self.vlist.draw(GL_TRIANGLE_STRIP) glPopMatrix() if self.texture: glBindTexture(GL_TEXTURE_2D, 0) glDisable(GL_TEXTURE_2D) glDisable(GL_BLEND) objects = [ TexAlphaSquare(640, 480, 0, 0, 'hst9904a.jpg', [1,1,1,1]), TexAlphaSquare(256, 384, 0, 0, keyedTexImg, [1,1,1,1]) ] @window.event def on_draw(): glClearColor(0, 0, 0, 0) glClear(GL_COLOR_BUFFER_BIT) glLoadIdentity() glTranslatef(320, 240, 0) for o in objects: o.draw() def update(dt): global objects angle = (time.time() % 10) * 36 objects[1].xpos = 192 * math.sin(angle * math.pi/180.0) objects[1].ypos = 192 * math.cos(angle * math.pi/180.0) objects[1].heading = 270 - angle pyglet.clock.schedule_interval(update,1/60.0) pyglet.app.run()