Skip to content

Instantly share code, notes, and snippets.

@serg06
Created April 24, 2022 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serg06/f5e84b25cb2e216060e3299d315e8c29 to your computer and use it in GitHub Desktop.
Save serg06/f5e84b25cb2e216060e3299d315e8c29 to your computer and use it in GitHub Desktop.
from scipy import ndimage
import numpy as np
from PIL import Image
from random import randint
from copy import deepcopy
# set the file path to wherever your provinces.png is located
im = Image.open(r"colors.png")
print('-------------------------------------------')
# DEBUGGING: simply prints the format, size, and mode of your file
print(im.format, im.size, im.mode)
# saves the width and depth of the file
im_xsize = im.size[0]
im_ysize = im.size[1]
# DEBUGGING: prints it
print(im_xsize, im_ysize)
# DEBUGGNG: prints data bands, should be R, G, B
print(im.getbands())
# DEBUGGING: prints RGB value of pixel of choice
print(im.getpixel((0, 0)))
print('-------------------------------------------')
# creates array for pixel RGBs
rgb_array = [[None] * im_ysize for length in range(0, im_xsize)]
# fills pixel RGB array
for x in range(0, im_xsize):
for y in range(0, im_ysize):
rgb_array[x][y] = im.getpixel((x, y))
print(list(set([pixel for row in rgb_array for pixel in row])))
# Get coordinates of all clusters
def get_clusters(array):
visited = [[False] * len(row) for row in array]
clusters = []
def isValid(i, j):
return 0 <= i < len(array) and 0 <= j < len(array[0])
def dfs(i, j):
# Get all coordinates of cluster including coordinate (i, j)
stack = [(i, j)]
curr = array[i][j]
coords = []
while len(stack) > 0:
head = stack.pop()
(i2, j2) = head
if not isValid(i2, j2) or visited[i2][j2] or curr != array[i2][j2]:
continue
visited[i2][j2] = True
coords.append(head)
stack.append((i2 - 1, j2))
stack.append((i2 + 1, j2))
stack.append((i2, j2 - 1))
stack.append((i2, j2 + 1))
return coords
for i in range(len(array)):
for j in range(len(array[0])):
if not visited[i][j]:
clusters.append(dfs(i, j))
return clusters
def generate_colors(num):
return tuple((randint(0, 255), randint(0, 255), randint(0, 255)) for _ in range(num))
def assign_random_colors(array, clusters):
array = deepcopy(array)
colors = generate_colors(len(clusters))
for color, cluster in zip(colors, clusters):
for (i, j) in cluster:
array[i][j] = color
return array
# Run
clusters = get_clusters(rgb_array)
print(f'Found {len(clusters)} clusters')
# Generate colors
new_colors = assign_random_colors(rgb_array, clusters)
# Write them to pixels
for x in range(0, im_xsize):
for y in range(0, im_ysize):
# places province color based on which province current pixel is assigned to
im.putpixel((x, y), new_colors[x][y])
im.save(r"out.png", im.format)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment