Created
December 27, 2018 20:49
-
-
Save sam-thecoder/9acd42ddd664530e44608513d8f00ea3 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 PIL import Image | |
def get_pixels(image): | |
im = Image.open(image) | |
pixels = [] | |
pix = im.load() | |
width,height = im.size | |
img_width, img_height = 0,0 | |
for _ in range(width * height): | |
if img_width == width: | |
img_height += 1 | |
img_width = 0 | |
pixels.append(pix[img_width, img_height]) | |
img_width += 1 | |
return pixels | |
def pixel_index(pixels): | |
pix_index = {} | |
for pixel in pixels: | |
if pixel in pix_index.keys(): | |
pix_index[pixel] += 1 | |
else: | |
pix_index[pixel] = 1 | |
return pix_index | |
def pixels_check(top_pixels, pixel): | |
for pix in top_pixels: | |
result = valid_check(pix, pixel) | |
if result == True: | |
return True | |
return False | |
def valid_check(first_color, second_color, offset=10): | |
off_1 = abs(first_color[0] - second_color[0]) | |
off_2 = abs(first_color[1] - second_color[1]) | |
off_3 = abs(first_color[2] - second_color[2]) | |
if off_1 < offset and off_2 < offset and off_3 < offset: | |
return True | |
return False | |
def colourfest(image): | |
image_name = image | |
pix = pixels = get_pixels(image) | |
pix = pixel_index(pix) | |
top_pixels = sort_pixels(pix) | |
image = Image.open(image) | |
pix_load = image.load() | |
width,height = image.size | |
new_image = Image.new(image.mode, image.size) | |
img_width, img_height = 0,0 | |
for _ in range(width * height): | |
if img_width == width: #checks if width exceeded and jumps to next row | |
img_height += 1 | |
img_width = 0 | |
pixel = pix_load[img_width, img_height] | |
top_pix = pixels_check(top_pixels, pixel) | |
if top_pix == True: | |
new_image.putpixel([img_width, img_height],pixel) | |
else: | |
gray = (pixel[0] + pixel[1] + pixel[2])/3 | |
new_image.putpixel([img_width, img_height], (gray, gray, gray)) | |
img_width += 1 | |
new_image.save('colored/'+image_name) | |
In [1]: from colorfest import * | |
In [2]: colourfest('58c7814d7857c.jpeg') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment