View difference between Paste ID: aNVR4CST and xEtK139R
SHOW: | | - or go back to the newest paste.
1
from pygame.image import load as load_image, save as save_image
2
from pygame.surfarray import array3d, make_surface
3
from pygame import Surface
4
from colorsys import rgb_to_hls
5
from sys import argv
6
from math import sqrt
7
from numpy import array
8
9
formatted_colors = {}
10
def fmt_color(c):
11
	rgb = c if isinstance(c,tuple) else color_components(c)
12
	get_fmt = lambda c:"#{:02X}{:02X}{:02X}".format(*rgb)
13
	#get_fmt = lambda c:"rgb({},{},{})".format(*rgb)
14
	if c not in formatted_colors:
15
		formatted_colors[c] = get_fmt(c)
16
	return formatted_colors[c]
17
18
def gba_component(std_component):
19
	return int(round((((std_component / 255) * 31))) * 8)
20
21
def gba_filter(c):return tuple(map(gba_component,c))
22
23
def color_distance(a,b):
24
	hsl_a, hsl_b = rgb_to_hls(*map(int,a)),rgb_to_hls(*map(int,b))
25
	return sqrt(sum(map(lambda a,b:((a-b)**2), hsl_a,hsl_b)))
26
27
def n_to_t(n):return (n[0],n[1],n[2])
28
def t_to_n(t):return array(t)
29
30
def process_surface(surf):
31
	rows = array3d(surf)
32
	to_swap,color_heat = {},{}
33
	for row in rows:
34
		for pixel in row:
35
			pixel = n_to_t(pixel)
36
			if pixel in to_swap:
37
				color_heat[to_swap[pixel]]-=1
38
				continue
39
			nc = gba_filter(pixel)
40
			to_swap[pixel] = nc
41
			color_heat[nc] = -1
42
	colors = sorted(map(to_swap.get,to_swap.keys()),key=color_heat.get)
43
	used_colors = colors[:16]
44
	r_cs = [c for c in to_swap.keys() if to_swap[c] not in used_colors]
45
	for color in r_cs:
46
		dist_to = lambda cc:(cc,-1 * color_distance(color,cc))
47
		color_distances = dict(map(dist_to,used_colors))
48
		s = sorted(color_distances.keys(),key=color_distances.get)
49
		to_swap[color] = s[0]
50-
	dimensions = rows.shape
50+
51-
	for x in range(dimensions[1]):
51+
52-
		for y in range(dimensions[2]):
52+
53-
			n = rows[x,y]
53+
54-
			t = (n[0],n[1],n[2])
54+
55-
			rows[x,y] = to_swap.get(t,t)
55+
56
	new_things = array([column(row) for row in rows])
57
	u_colors = set(u_colors)
58
	print(*map(fmt_color,u_colors),sep='\n')
59
	return make_surface(new_things)
60
61
def append_fn(fn,ap):return fn[:fn.find(".")] + ap + fn[fn.find("."):]
62
def base_fn(fn):return fn[fn.rfind("\\")+1:]
63
64
for fn in argv[1:]:
65
	nfn = append_fn(fn,"-processed")
66
	print(base_fn(fn),":",base_fn(nfn))
67
	img = load_image(fn)
68
	new_img,dimensions = process_surface(img), img.get_size()
69
	new_image = Surface(tuple(map(lambda a,b:a*b,dimensions,[2,1])))
70
	new_image.blit(img,(0,0))
71
	new_image.blit(new_img,(img.get_width(),0))
72
	save_image(new_img, nfn)
73
	save_image(new_image, append_fn(fn,"-combined"))
74
	print("="*80)