from PIL import Image, ImageDraw
leftPixelDict = {(0, 1): (0, 0), (0, -1): (-1, -1), (1, 0): (0, -1), (-1, 0): (-1, 0)}
rightPixelDict = {(0, 1): (-1, 0), (0, -1): (0, -1), (1, 0): (0, 0), (-1, 0): (-1, -1)}
def add(vector1, vector2):
return (vector1[0] + vector2[0], vector1[1] + vector2[1])
def mult(vector):
return (-vector[1], vector[0])
def testDirection(point, direction):
leftPixel = add(point, leftPixelDict[direction])
rightPixel = add(point, rightPixelDict[direction])
if (leftPixel in polygonPixels) and (rightPixel not in polygonPixels):
return True
return False
def getDirection(point, oldDirection):
direction = oldDirection
if testDirection(point, direction):
return direction
direction = mult(direction)
if testDirection(point, direction):
return direction
direction = mult(mult(direction))
if testDirection(point, direction):
return direction
raise Exception
def findBorder(startPoint):
#Point is uniquely defined by a pixel, which left upper vertice is this point
border = [startPoint]
direction = getDirection(startPoint, (0, 1))
point = add(startPoint, direction)
while (point != startPoint):
border.append(point)
direction = getDirection(point, direction)
point = add(point, direction)
return border
image = Image.open("test.png")
draw = ImageDraw.Draw(image)
width = image.size[0]
height = image.size[1]
pixels = image.load()
polygonPixels = []
for y in range(height):
for x in range(width):
pixel = pixels[x, y]
if pixel[0:3] == (0, 0, 255):
polygonPixels.append((x, y))
notVisited = polygonPixels
SVG = ''
while (notVisited != []):
pixel = notVisited[0]
print(pixel)
cLP = (add(pixel, (-1, 0)) in polygonPixels)
cRP = (add(pixel, (1, 0)) in polygonPixels)
cUP = (add(pixel, (0, -1)) in polygonPixels)
cDP = (add(pixel, (0, 1)) in polygonPixels)
if (cLP and cRP and cUP and cDP):
SVG += ' M ' + str(pixel[0]) + ' ' + str(pixel[1]) + ' z'
notVisited = list(set(notVisited).difference({pixel}))
else:
border = findBorder(pixel)
notVisited = list(set(notVisited).difference(set(border)))
SVG += ' M '
for pix in border:
SVG += str(pix[0]) + ' ' + str(pix[1]) + ' L '
SVG = SVG[:-2] + 'z'
print(SVG[1:])