Skip to content

Month: December 2009

Pygame: Running Orcs

Here is a Pygame Sprite animation using the approach presented by Joe Wreschnig and Nicolas Crovatti. It’s not yet exactly what I need but is very suitable.

import pygame, random
from pygame.locals import *

class Char(pygame.sprite.Sprite):
	x,y = (100,0)
	def __init__(self, img, frames=1, modes=1, w=32, h=32, fps=3):
		original_width, original_height = img.get_size()
		self._w = w
		self._h = h
		self._framelist = []
		for i in xrange(int(original_width/w)):
		self.image = self._framelist[0]		
		self._start = pygame.time.get_ticks()
		self._delay = 1000 / fps
		self._last_update = 0
		self._frame = 0
		self.update(pygame.time.get_ticks(), 100, 100)	

	def set_pos(self, x, y):
		self.x = x
		self.y = y

	def get_pos(self):
		return (self.x,self.y)

	def update(self, t, width, height):
		# postion
			self.x = random.randint(0,height-self._w)
			self.y = -self._h

		# animation
		if t - self._last_update > self._delay:
			self._frame += 1
			if self._frame >= len(self._framelist):
				self._frame = 0
			self.image = self._framelist[self._frame]
			self._last_update = t

SCREEN_W, SCREEN_H = (320, 320)

def main():
	screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
	background = pygame.image.load("field.png")
	img_orc = pygame.image.load("orc.png")
	orc = Char(img_orc, 4, 1, 32, 48)
	while pygame.event.poll().type != KEYDOWN:
		screen.blit(background, (0,0))
		screen.blit(orc.image,  orc.get_pos())
		orc.update(pygame.time.get_ticks(), SCREEN_W, SCREEN_H)

if __name__ == '__main__': main()

Here is it working:

Uptade: I put this source and images at the OpenPixel project in Github

Audiência Pública Debate Mobilidade Urbana e Ciclovias

Audi̻ncia P̼blica debate mobilidade urbana e ciclovias РDebate sobre os projetos de lei que prop̵em a cria̤̣o e o incentivo ao uso de bicicleta.
Data: 11/12 (sexta-feira)
Horário: 09:30
Local: Auditório da Câmara Municipal de Fortaleza – Rua Thompson Bulcão, 830 – Luciano Cavalcante
Informações: 3444-8361

Participe do trajeto ciclista à câmara!
Saída: Praça da Imprensa (Des. Moreira x Antônio Sales)
Concentração a partir das 8h.

Pygame Simple Key Handling

Here’s a simple key handle in Pygame wheres you move a circle using keyboard.

import pygame
from pygame.locals import *

def main():
	x,y = (100,100)
	screen = pygame.display.set_mode((400, 400))
	while 1:
      # exit handle
		for event in pygame.event.get():
			if event.type == QUIT:
			elif event.type == KEYDOWN and event.key == K_ESCAPE:

      # keys handle 
		if key[K_LEFT]:
		if key[K_RIGHT]:
		if key[K_UP]:
		if key[K_DOWN]:

		# fill background and draw a white circle
		screen.fill((255,255,255)), (0,0,0), [x,y], 30)

if __name__ == '__main__': main()

Here’s a video of it working:

Function pygame.key.get_pressed Returns a sequence of boolean values representing the state of every key on the keyboard. It’s very useful because usually on others game platforms I have to create it by myself.

This approach allow me to handle more than one key at time. For example, left and up keys can be pressed and each one is handled separately creating a diagonal movement.


Este é um personagem eu que eu desenho a muito tempo, desde 2003 pelo que eu tenho de registro. Ele é um robô-filósofo chamado Hugo. Esse eu desenhei no Nokia N800.

Algumas colorizações feitas a partir desse desenho, usando o Gimp.

Código-fonte: hugo_sketch.xcf.

hugo sketch yellow

hugo sketch purple

hugo sketch gray

hugo sketch texture

hugo sketch gray paint



OpenCV: Hue, Saturation and Value.

Here a simple OpenCV example of separation of a image into its hue, saturation and value channels.


int main( int argc, char **argv ){
    IplImage *img, *hsv, *hue, *sat, *val;
    int key = 0, depth;
    CvSize size;

    /* Load command line passed image, check it. */
    if (argc>1) {
        img = cvLoadImage(argv[1], CV_LOAD_IMAGE_COLOR);
            printf("Could not open image.");
            exit -1;
            printf("We need color image!");
            exit -1;
    } else {
        printf("Usage: %s VIDEO_FILE\n", argv[0]);
        return 1;

    /* Create a hsv image with 3 channels and hue, sat e val with 1 channel.
       All with the same size */
    size = cvGetSize(img);
    depth = img->depth;
    hue = cvCreateImage(size, depth, 1);
    sat = cvCreateImage(size, depth, 1);
    val = cvCreateImage(size, depth, 1);
    hsv = cvCreateImage(size, depth, 3);

    /* Convert from Red-Green-Blue to Hue-Saturation-Value */
    cvCvtColor( img, hsv, CV_BGR2HSV );

    /* Split hue, saturation and value of hsv on them */
    cvSplit(hsv, hue, sat, val, 0);
    /* Create windows, display them, wait for a key */
    cvNamedWindow("original", CV_WINDOW_AUTOSIZE);
    cvNamedWindow("hue", CV_WINDOW_AUTOSIZE);
    cvNamedWindow("saturation", CV_WINDOW_AUTOSIZE);
    cvNamedWindow("value", CV_WINDOW_AUTOSIZE);

    cvShowImage("original", img);
    cvShowImage("hue", hue);
    cvShowImage("saturation", sat);
    cvShowImage("value", val);


    /* Free memory and get out */


    return 0;

Resized original image, photo by Robert Bradshaw at Wikimedia Commons.

Sunset Peter Iredale

Hue channel:

hue sunset Peter Iredale

Saturation channel:

saturation sunset Peter Iredale

Value channel:

value sunset Peter Iredale

OpenCV: adding two images

This is a very simple example of how to open two images and display them added.

I got two pictures at project Commons from Wikimedia that were highlighted on Featured Pictures. I did a crop on both to have the same size, as I’m trying to make this example as simple as possible.

The first one is a photo of our Milky Way, taken at Paranal Observatory by Stéphane Guisard.


The second one is a California surfer inside wave, taken by Mila Zinkova.


In this simple OpenCV code below, we open the images, create a new one to display the result and use cvAdd to add them. We do not save the result or handle more than the ordinary case of two images with the same size.


int main( int argc, char **argv ){
    IplImage *surfer, *milkyway, *result;
    int key = 0;
    CvSize size;

    /* load images, check, get size (both should have the same) */
    surfer = cvLoadImage("surfer.jpg", CV_LOAD_IMAGE_COLOR);
    milkyway = cvLoadImage("milkyway.jpg", CV_LOAD_IMAGE_COLOR);
        printf("Could not open one or more images.");
        exit -1;
    size = cvGetSize(surfer);

    /* create a empty image, same size, depth and channels of others */
    result = cvCreateImage(size, surfer->depth, surfer->nChannels);

    /* result = surfer + milkyway (NULL mask)*/
    cvAdd(surfer, milkyway, result, NULL);
    /* create a window, display the result, wait for a key */
    cvNamedWindow("example", CV_WINDOW_AUTOSIZE);
    cvShowImage("example", result);

    /* free memory and get out */
    return 0;

/* gcc add.c -o add `pkg-config opencv --libs --cflags` */

Compile it (on a well configured OpenCV development environment) and run it:

gcc add.c -o add `pkg-config opencv –libs –cflags`

The result got pretty cool, a milky way surfer.

surfer in the milk way