analytics

Saturday, October 4, 2014

map cardinal traversal rectification

This program takes a map of a certain number of different colors like:
And produces this:
This map preserves the order that you will reach different colored areas (including white) of the map by traveling purely in North, East, South or West increments. It's also the simplest such map.
The way it works is it takes a row of pixels making a list of the colors that it reaches along that row. It does this for each row and takes all the lists and removes any duplicate lists that are adjacent in this list of lists. It also does this for every column. This gives you a grid of colors.

**Python Source Code**
import Image
def order(rorc, which, map):
    o = []
    if rorc == 0:
        nlastcolor = (255,255,255)
        lastcolor = map.getpixel((0,which))
        o.append(lastcolor)
        for i in range(1, map.size[0]):
            thiscolor = map.getpixel((i, which))
            if thiscolor != lastcolor:
                o.append(thiscolor)
                lastcolor = thiscolor
    if rorc == 1:
        nlastcolor = (255,255,255)
        lastcolor = map.getpixel((which,0))
        o.append(lastcolor)
        for i in range(1, map.size[1]):
            thiscolor = map.getpixel((which, i))
            if thiscolor != lastcolor:
                o.append(thiscolor)
                lastcolor = thiscolor
    return o

def markchange(rorc, map):
    mark = [0]
    if rorc==0:
        for i in range(1, map.size[1]):
            o = order(0, i, map)
            p = order(0, i-1, map)
            if p!=o:
                mark.append(i)
    if rorc==1:
        for i in range(1, map.size[0]):
            o = order(1, i, map)
            p = order(1, i-1, map)
            if p!=o:
                mark.append(i)
    return mark
def makemap(map, mapout, r, c):
    for i in range(1, len(c)):
        for j in range(1, len(r)):
            coord = ((c[i-1]*1.0+c[i])/2, (r[j-1]*1.0+r[j])/2.0)
            color = map.getpixel(coord)
            for x in range((i-1)*20, (i+1)*20):
                for y in range((j-1)*20, (j+1)*20):
                    mapout.putpixel((x,y), color)
def main():
    map = Image.open("map.png")
    r= markchange(0, map)
    c= markchange(1, map)
    mapout = Image.new("RGB", (21*len(c), 21*len(r)), (255,255,255))
    makemap(map, mapout, r, c)
    mapout.save("m.png")
main()

No comments:

Post a Comment