from PIL import Image

img_original = Image.open("laketour2.png")
img_original = Image.open("exlaketour.png")

noir = (0, 0, 0)
rouge = (255, 0, 0)
vert = (0, 255, 0)
bleu = (0, 0, 255)

width, height = img_original.size
width +=2
height += 2

img = Image.new(img_original.mode, (width, height))
img.paste(img_original.crop(), (1,1))

img = img.convert("RGB")

def contour(x, y, pixel_to_fill, pixels_to_match):
    global img
    global width
    global height

    res = 1
    countour = ???

    if y > 0 and img.getpixel((x,y-1)) in pixels_to_match:
        status, pixels, color1 = contour(x, y-1, pixel_to_fill, pixels_to_match)
        if not status:
            return False, 0, 0
        res += pixels
    if x < width-1 and img.getpixel((x+1,y)) in pixels_to_match:
        status, pixels, color2 = contour(x+1, y, pixel_to_fill, pixels_to_match)
        if not status:
            return False, 0, 0
        if color2 != color1:
            return False, 0, 0
        res += pixels
    if x > 0 and img.getpixel((x-1,y)) in pixels_to_match:
        status, pixels, color3 = contour(x-1, y, pixel_to_fill, pixels_to_match)
        if not status:
            return False, 0, 0
        if color3 != color1 or color3 != color2:
            return False, 0, 0
        res += pixels
    if y < height-1 and img.getpixel((x,y+1)) in pixels_to_match:
        status, pixels, color4 = contour(x, y+1, pixel_to_fill, pixels_to_match)
        if not status:
            return False, 0, 0
        if color4 != color1 or color4 != color2 or color4 != color3:
            return False, 0, 0
        res += pixels

    return True, res, color1

def fill(x, y, pixel_to_fill, pixels_to_match):
    global img
    global width
    global height

    img.putpixel((x,y), pixel_to_fill)
    res = 1

    if y > 0 and img.getpixel((x,y-1)) in pixels_to_match:
        pixels = fill(x, y-1, pixel_to_fill, pixels_to_match)
        res += pixels
    if x < width-1 and img.getpixel((x+1,y)) in pixels_to_match:
        pixels = fill(x+1, y, pixel_to_fill, pixels_to_match)
        res += pixels
    if x > 0 and img.getpixel((x-1,y)) in pixels_to_match:
        pixels = fill(x-1, y, pixel_to_fill, pixels_to_match)
        res += pixels
    if y < height-1 and img.getpixel((x,y+1)) in pixels_to_match:
        pixels = fill(x, y+1, pixel_to_fill, pixels_to_match)
        res += pixels

    return res

fleches = 0
for x in range(width):
    for y in range(height):
        if img.getpixel((x,y)) == noir:
            pixels = fill(x,y, bleu, [noir,])
            print(pixels)
            status, pixels_countour, color = contour(x, y, bleu, [vert,])
            print(status, pixels_countour, color)
            img.show()
            if status:
                fleches += (pixels+pixels_countour) * color
            else:
                fill(x,y, rouge, [bleu,])
            img.show()


img.save("laketour2_tmp.png")
img.show()

print(fleches)
