Last active
December 13, 2015 21:18
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bfs(imagen, origen, color): | |
"""colorea todo el objeto recibe como parametros el | |
nuevo color con el que se pinta,la coordenada de inicio y | |
la imagen, y regresa un arreglo con la masa y la imagen | |
""" | |
cola = [] | |
cont = 0 | |
masa = [] | |
pixeles = imagen.load() | |
alto, ancho = imagen.size | |
cola.append(origen) | |
original = pixeles[origen] | |
while len(cola) > 0: | |
(x, y) = cola.pop(0) | |
actual = pixeles[x, y] | |
if actual == original or actual == color: | |
for dx in [-1, 0, 1]: | |
for dy in [-1, 0, 1]: | |
candidato = (x + dx, y + dy) | |
pix_x = candidato[0] | |
pix_y = candidato[1] | |
if pix_x >= 0 and pix_x < alto and pix_y >= 0 and pix_y < ancho: | |
contenido = pixeles[pix_x, pix_y] | |
if contenido == original: | |
pixeles[pix_x, pix_y] = color | |
masa.append((pix_x,pix_y)) | |
imagen.putpixel((pix_x, pix_y), color) | |
cont += 1 | |
cola.append((pix_x, pix_y)) | |
imagen.save('prueba', 'png') | |
return imagen, cont, masa | |
def encuentra_formas(imagen): | |
"""cambia el color de cada objeto en | |
la imagen llamando por cada uno a la | |
funcion bfs | |
""" | |
alto, ancho = imagen.size | |
pixeles = imagen.load() | |
colores = [] | |
porcentaje = [] | |
for i in range(alto): | |
for j in range(ancho): | |
if pixeles[i,j] == (0,0,0): | |
r = int(random.random()*250) | |
g = int(random.random()*250) | |
b = int(random.random()*250) | |
nuevo_color = (r,g,b) | |
imagen, cont, masa = bfs(imagen, (i,j), nuevo_color) | |
print "CAMBIA" | |
total_x = 0 | |
total_y = 0 | |
por = (float(cont)/float(alto*ancho))*100 | |
for l in range(len(masa)): | |
total_x = total_x + masa[l][0] | |
total_y = total_y + masa[l][1] | |
x_centro = total_x/len(masa) | |
y_centro = total_y/len(masa) | |
colores.append([nuevo_color,(x_centro, y_centro), por]) | |
porcentaje.append(por) | |
pixeles = imagen.load() | |
masa = [] | |
figura_mayor = max(porcentaje) | |
i = porcentaje.index(figura_mayor) | |
color_mayor = colores[i][0] | |
print color_mayor | |
imagen.save('antes_fondo.png', 'png') | |
identifica_fondo(imagen, color_mayor) | |
imagen.save('resultado.png', 'png') | |
return imagen, colores | |
def identifica_fondo(imagen, color_max): | |
""" se pinta la imagen que tiene mayor area | |
""" | |
pixeles = imagen.load() | |
x, y = imagen.size | |
for a in range(x): | |
for b in range(y): | |
if pixeles[a, b] == color_max: | |
color = (210,210,210) | |
imagen, masa, n = bfs(imagen, (a, b), color) | |
return imagen |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment