Created
September 3, 2011 01:01
-
-
Save adambard/1190327 to your computer and use it in GitHub Desktop.
This file contains 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
# Color of each block at 10, 10 | |
COLORS = ( | |
(158, 221, 255), # Diamond | |
(247, 183, 0), #Yellow | |
(1, 185, 1), # Green | |
(186, 115, 255), # Purple | |
(242, 0, 16), # Red | |
(6, 104, 253)) # Blue | |
def downsample_pixarray(pixarray, factor=40.): | |
""" | |
Get the nearest color index match from the COLORS tuple | |
from every square. | |
Diamond dash squares are 40x40. | |
""" | |
factor = float(factor) | |
rows, cols, _ = pixarray.shape | |
new_rows = int(math.ceil(rows / factor)) | |
new_cols = int(math.ceil(cols / factor)) | |
counts = numpy.zeros((new_rows, new_cols)) | |
out_pixarray = numpy.zeros((new_rows, new_cols, 3)) | |
# Downsample instead of averaging | |
for i in range(new_rows): | |
for j in range(new_cols): | |
# Get a point from 10,10 in a 40px square, which should be the right color | |
i_ind = int(i * factor + factor/4) | |
j_ind = int(j * factor + factor/4) | |
pixel = pixarray[i_ind][j_ind] | |
c = nearest_index_to_color(pixel) | |
counts[i][j] = c | |
return counts | |
def nearest_index_to_color(color_tuple): | |
"Get the index in COLORS closest to color_tuple" | |
distances = [color_distance(c, color_tuple) for c in COLORS] | |
return distances.index(min(distances)) | |
def normalize_color(color_tuple): | |
"Get the color closest to color_tuple" | |
return COLORS[nearest_index_to_color(color_tuple)] | |
def color_distance(c1, c2): | |
"""Get the sum of squares of the difference between two colors""" | |
return (c1[0] - c2[0]) ** 2 + (c1[1] - c2[1]) ** 2 + (c1[2] - c2[2]) ** 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment