Last active
January 1, 2023 23:08
-
-
Save nitori/17c5a9de41d460f95783d02f778cab2c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from __future__ import annotations | |
from PIL import Image, ImageDraw | |
def neighbours(x, y): | |
return [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1), (x - 1, y - 1), (x + 1, y - 1), (x - 1, y + 1), | |
(x + 1, y + 1)] | |
def find_ocean_coords(filename, testsize=(128, 128)): | |
im = Image.open(filename) | |
mapim = im.resize(testsize) | |
# take top left corner... if it's land, you might need to test other corners. | |
# but I'm lazy, so I'm just going to assume it's always water. | |
water_color = mapim.getpixel((0, 0)) | |
orig_w, orig_h = im.size | |
w, h = mapim.size | |
ratio_w = orig_w / w | |
ratio_h = orig_h / h | |
# find all connected water pixels of the same color | |
seen = set() | |
valid_coords = set() | |
x, y = 0, 0 | |
stack = [(x, y)] | |
# add all edges with same water color | |
for x in range(w): | |
if mapim.getpixel((x, 0)) == water_color: | |
valid_coords.add((x, 0)) | |
stack.append((x, 0)) | |
if mapim.getpixel((x, h - 1)) == water_color: | |
valid_coords.add((x, h - 1)) | |
stack.append((x, h - 1)) | |
for y in range(h): | |
if mapim.getpixel((0, y)) == water_color: | |
valid_coords.add((0, y)) | |
stack.append((0, y)) | |
if mapim.getpixel((w - 1, y)) == water_color: | |
valid_coords.add((w - 1, y)) | |
stack.append((w - 1, y)) | |
# flood fill | |
while stack: | |
x, y = stack.pop() | |
if (x, y) in seen or x < 0 or x >= w or y < 0 or y >= h: | |
continue | |
seen.add((x, y)) | |
if mapim.getpixel((x, y)) == water_color: | |
valid_coords.add((x, y)) | |
stack.extend(neighbours(x, y)) | |
# convert to original image coordinates | |
return {(int(x * ratio_w), int(y * ratio_h)) for x, y in valid_coords} | |
def main(): | |
ocean_coords = find_ocean_coords('maps/border_image.png') | |
im = Image.open('maps/image.png') | |
draw = ImageDraw.Draw(im) | |
for x, y in ocean_coords: | |
draw.ellipse((x - 2, y - 2, x + 2, y + 2), fill=(255, 0, 0)) | |
im.show() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment