sábado, 10 de março de 2012

Visões

Numa aula anterior andámos com o problema de desenvolver um algoritmo simples para reconhecer padrões. No caso analisado os padrões eram dígitos. O padrão era codificado como uma lista de listas. Por exemplo, o número um era codificado como:


[[0,0,1,0,0,],[0,1,1,0,0],[0,0,1,0,0],[0,0,1,0,0],[0,0,1,0,0]]

Vamos exemplificar como podemos mostrar o número como se de uma imagem se tratasse. para isso vamos pedir auxílio ao módulo pygame (pygame.org).

E primeiro lugar definimos uma classe Grid que representa os nossos padrões.

class Grid(object):
def __init__(self, width,height):
self.width = width
self.height = height
self.grid = [[0]* width for i in range(height)]

def initialize(self):
for x in range(self.width):
for y in range(self.height):
self.grid[y][x] = random.randint(0,1)

def set_cell(self, x,y, value):
self.grid[y][x] = value

def set_grid(self,figure):
for x in range(self.width):
for y in range(self.height):
self.set_cell(x,y,figure[y][x])

def show_grid(self):
for y in range(self.height):
print self.grid[y]

Feito isto usamos o pygame para desenhar o padrão. A lógica é a de fazer corresponder um elemento da lista de listas a um quadrado na imagem com um número de pixeis configurável (ver imagem).





Os guiões (scripts) em pygame seguem a metodologia IDEA (Initialize, Display, Entities, Action). Passemos ao código.

def draw(figure):
# Initialize
WHITE = (255,255,255)
BLACK = (0,0,0)
SIZE_X = len(figure)
SIZE_Y = len(figure[0])
DISP_SIZE = 50
# Display
pygame.init()
screen = pygame.display.set_mode((SIZE_X * DISP_SIZE, SIZE_Y * DISP_SIZE))
screen.fill(BLACK)
# Entities
figure_grid = Grid(SIZE_X, SIZE_Y)
figure_grid.set_grid(figure)
# Action
for x in range(figure_grid.width):
for y in range(figure_grid.height):
if figure_grid.grid[y][x] == 1:
pygame.draw.rect(screen,WHITE, pygame.Rect(x*DISP_SIZE,y*DISP_SIZE, DISP_SIZE,DISP_SIZE))

pygame.display.flip()

Executando o código:

if __name__ == '__main__':
figure = [[0,0,0,1,1,0,0,0],[0,0,1,0,0,1,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,0],[0,0,0,1,0,0,0,0],[0,0,1,0,0,0,0,0],[0,0,1,1,1,1,0,0]]
draw(figure)

Obtemos o lindo padrão:

Sem comentários:

Enviar um comentário