Skip to content

Month: December 2009

Gimp Small Miracles

Some times a good picture is ruined by a little detail or someone that shouldn’t be there. If you are willing to trade a complete portraying of the reality for a better photo, here are some tips for Gimp. Use them wisely.

Here is the original photo of two friends playing a game, and an unwanted stranger raising his arms right in the middle of the picture.

Here is the most useful tools from the Gimp tool box and how to use them:

Clone tool. The most common tool to create remove unwanted things. Usually you use them by getting a background theme and cloning it to cover what you want to hide. The best way to use this tool is when you have a not uniform background, like a wall or grass, where a small pattern repeats.

Free Selection (Lasso). When the clone tool is not enough because patterns are too big or too shapeless, the best is use the lasso tool. Get a good piece of the background or another object and them copy and paste over what you want to hide. Maybe what you need to select and copy is not in the same image you are working, you can get information from another picture and use in your main picture. This was what I had to do in this example.

Sometimes you have to change the brightness and contrast to match the pasted selection with the main picture.

Perpective tool. This is a very powerful tool because allows you to use a selection from another image but was taken from another point of view and you need to correct it’s perspective. By doing that you can retrieve a lot of information that your picture don’t have by taking them from another pictures. You can also use to fit a pattern.

Smudge tool. When you are handling uniform colors and straight shapes this is a good tool. You can smudge a pasted selection in the boundaries to it match with the main picture. You can also use it to stretch or squeeze shapes, but they have to be very color uniform to it work well. For more complex shapes you can use the IWarp filter.

So, I guess this is the most important about them. Another time I can do some videos showing how to use them better. In this work you can spot several little mistakes because I was very clumsy and in hurry, but the result is satisfactory.

Before

After

Next time ask people to get out of the way when taking a picture.

Python Fast XML Parsing

Here is a useful tip on Python XML decoding.

I was extending xml.sax.ContentHandler class in a example to decode maps for a Pygame application when my connection went down and I noticed that the program stop working raising a exception regarded a call to urlib (a module for retrieve resources by url). I noticed that the module was getting the remote DTD schema to validate the XML.


This is not a requirement for my applications and it’s a huge performance overhead when works (almost 1 second for each map loaded) and when the applications is running in a environment without Internet it just waits for almost a minute and then fail with the remain decoding. A dirty workaround is open the XML file and get rid of the line containing the DTD reference.

But the correct way to programming XML decoding when we are not concerned on validate a XML schema is just the xml.parsers.expat. Instead of using a interface you just have to set some callback functions with the behaviors we want. This is a example from the documentation:

import xml.parsers.expat

# 3 handler functions
def start_element(name, attrs):
    print 'Start element:', name, attrs
def end_element(name):
    print 'End element:', name
def char_data(data):
    print 'Character data:', repr(data)

p = xml.parsers.expat.ParserCreate()

p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data

p.Parse("""
Text goes here
More text
""", 1)

The output:

Start element: parent {'id': 'top'}
Start element: child1 {'name': 'paul'}
Character data: 'Text goes here'
End element: child1
Character data: '\n'
Start element: child2 {'name': 'fred'}
Character data: 'More text'
End element: child2
Character data: '\n'
End element: parent

OpenCV on Ubuntu

digital_eye

Open Computer Vision Library or just OpenCV, is a cross-platform computer vision library focused on real-time image processing for video files or webcams.

You have two options to obtain the environment to develop on OpenCV. You can insert a new repository in your package manager or compile it by yourself.

For Ubuntu 9.10 Karmic Koala there’s this repository with OpenCV’s package.

To compile it you have to install some additional libraries compile it by your self. And it’s instructions vary for each distribution and version. For example, from Ubuntu Linux 9.10 to 9.04, the process varies slightly. I followed the instructions on this post “Installing OpenCV 2.0 on Ubuntu 9.10 Karmic Koala”.

After you have installed and have a well configured OpenCV development environment, you can compile a “source.c” file into a “program” binary like this:

gcc gcc source.c -o program `pkg-config opencv ‑‑libs ‑‑cflags`

Tiled TMX Map Loader for Pygame

I’m using the Tiled Map Editor for a while, I even wrote that tutorial about it. It’s a general purpose tile map editor, written in Java but now migrating to C++ with Qt, that can be easily used with my set of free pixelart tiles.

map editor tiles tileset game deveopment

A map done with Tiled is stored in a file with TMX extension. It’s just a XML file, easy to understand.

As I’m creating a map loader for my owns purposes, the procedure I’m doing here works we need some simplifications. I’m handling orthogonal maps only. I’m not supporting tile properties as well. I also don’t want to handle base64 and zlib encoding in this version, so in the Tiled editor, go at the menu Edit → Preferences and in the Saving tab unmark the options “Use binary encoding” and “Compress Layer Data (gzip)”, like this:

Tiled Preferences Window

When saving a map it will produce a TMX file like this:




 
  
  
 
 
  
 
 
  
   
   
    ...
   
   
  
 

For processing it on Python I’m using the event oriented SAX approach for XML. So I create a ContentHandler that handles events the start and end of XML elements. In the first element, map, I know enough to create a Pygame surface with the correct size. I’m also storing the map properties so I can use it later for add some logics or effects on the map. After that we create a instance of the Tileset class from where we will get the each tile by an gid number. Each layer has it’s a bunch of gids in the correct order. So it’s enough information to mount and draw a map.

# Author: Silveira Neto
# License: GPLv3
import sys, pygame
from pygame.locals import *
from pygame import Rect
from xml import sax

class Tileset:
    def __init__(self, file, tile_width, tile_height):
        image = pygame.image.load(file).convert_alpha()
        if not image:
            print "Error creating new Tileset: file %s not found" % file
        self.tile_width = tile_width
        self.tile_height = tile_height
        self.tiles = []
        for line in xrange(image.get_height()/self.tile_height):
            for column in xrange(image.get_width()/self.tile_width):
                pos = Rect(
                        column*self.tile_width,
                        line*self.tile_height,
                        self.tile_width,
                        self.tile_height )
                self.tiles.append(image.subsurface(pos))

    def get_tile(self, gid):
        return self.tiles[gid]

class TMXHandler(sax.ContentHandler):
    def __init__(self):
        self.width = 0
        self.height = 0
        self.tile_width = 0
        self.tile_height = 0
        self.columns = 0
        self.lines  = 0
        self.properties = {}
        self.image = None
        self.tileset = None

    def startElement(self, name, attrs):
        # get most general map informations and create a surface
        if name == 'map':
            self.columns = int(attrs.get('width', None))
            self.lines  = int(attrs.get('height', None))
            self.tile_width = int(attrs.get('tilewidth', None))
            self.tile_height = int(attrs.get('tileheight', None))
            self.width = self.columns * self.tile_width
            self.height = self.lines * self.tile_height
            self.image = pygame.Surface([self.width, self.height]).convert()
        # create a tileset
        elif name=="image":
            source = attrs.get('source', None)
            self.tileset = Tileset(source, self.tile_width, self.tile_height)
        # store additional properties.
        elif name == 'property':
            self.properties[attrs.get('name', None)] = attrs.get('value', None)
        # starting counting
        elif name == 'layer':
            self.line = 0
            self.column = 0
        # get information of each tile and put on the surface using the tileset
        elif name == 'tile':
            gid = int(attrs.get('gid', None)) - 1
            if gid <0: gid = 0
            tile = self.tileset.get_tile(gid)
            pos = (self.column*self.tile_width, self.line*self.tile_height)
            self.image.blit(tile, pos)

            self.column += 1
            if(self.column>=self.columns):
                self.column = 0
                self.line += 1

    # just for debugging
    def endDocument(self):
        print self.width, self.height, self.tile_width, self.tile_height
        print self.properties
        print self.image

def main():
    if(len(sys.argv)!=2):
        print 'Usage:\n\t{0} filename'.format(sys.argv[0])
        sys.exit(2)
    pygame.init()
    screen = pygame.display.set_mode((800, 480))
    parser = sax.make_parser()
    tmxhandler = TMXHandler()
    parser.setContentHandler(tmxhandler)
    parser.parse(sys.argv[1])
    while 1:
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return
        screen.fill((255,255,255))
        screen.blit(tmxhandler.image, (0,0))
        pygame.display.flip()
        pygame.time.delay(1000/60)

if __name__ == "__main__": main()

Here is the result for opening a four layers map file:

netbeans python openning map

That’s it. You can get this code and adapt for your game because next versions will be a lot more coupled for my own purposes and not so general.

Download:packagemaploader.tar.bz2 It’s the Netbeans 6.7 (Python EA 2) project file but that can be opened or used with another IDE or without one. Also contains the village.tmx map and the tileset.

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):
		pygame.sprite.Sprite.__init__(self)
		original_width, original_height = img.get_size()
		self._w = w
		self._h = h
		self._framelist = []
		for i in xrange(int(original_width/w)):
			self._framelist.append(img.subsurface((i*w,0,w,h)))
		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.y+=1
		if(self.y>width):
			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():
	pygame.init()
	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)
		pygame.display.update()
		pygame.time.delay(10)

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

http://commons.wikimedia.org/wiki/File:Ordinary_bicycle02.jpg

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)
	pygame.init()
	screen = pygame.display.set_mode((400, 400))
	while 1:
		pygame.time.delay(1000/60)
      # exit handle
		for event in pygame.event.get():
			if event.type == QUIT:
				return
			elif event.type == KEYDOWN and event.key == K_ESCAPE:
				return

      # keys handle 
		key=pygame.key.get_pressed()
		if key[K_LEFT]:
			x-=1
		if key[K_RIGHT]:
			x+=1
		if key[K_UP]:
			y-=1
		if key[K_DOWN]:
			y+=1

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

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.

hugo

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

hugo_sketch_yellow_paint

hugo_sketch_effect