The results of the inpaint function really worked best for me. I wrote an extremely naive algorithm in python to normalize to a specified set of colors after some slight anti-aliasing has occurred. It works for very simple rasters like the types above. I have no idea how it would work on a photo, but it has worked on millions of simple images. It requires the "pillow" spin-off of the Python Image Library (PIL).
The script takes an image followed by a comma-delimited list of hex values as input. Quite primitive, I know
OK: both linking to the code and putting it in the post gives me "Your post looks too spamy for a new user, please remove off-site URLs." so I will share when I am able.
Update: ok, it let me post it!
#! /usr/bin/python
import os, sys
from PIL import Image
from collections import Counter
filename = sys.argv[1]
img = Image.open(filename)
im = img.load()
width, height = img.size
colorsin = sys.argv[2].split(',')
def hex_to_rgb(value):
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3))
colors = []
for color in colorsin:
colors.append(hex_to_rgb(color))
def is_valid(c, max):
"Ensure that pixel coordinate is not out of range of the image"
if (c >= 0 and c < max):
return True
else:
return False
def neighbor_pixels(x,y):
"Find all valid neighboring pixels"
neighbors = []
for dx in range(-1,2):
for dy in range(-1,2):
tempx = x + dx
tempy = y + dy
if (is_valid(tempx, width) and is_valid(tempy, height)):
neighbors.append([tempx, tempy])
return neighbors
def calc_color(x,y):
"Find the most commonly occuring valid color in neighboring pixels"
cnt = Counter()
neighbors = neighbor_pixels(x,y)
for neighbor in neighbors:
temp_image = im[neighbor[0],neighbor[1]]
if temp_image in colors:
cnt[temp_image] +=1
try:
return cnt.most_common(1)[0][0]
except IndexError:
print neighbor[0],neighbor[1],x,y
print 'INDEX ERROR'
return (0,0,0)
y = 0
while y<height:
x = 0
while x<width:
if im[x,y] not in colors:
im[x,y] = calc_color(x,y)
x = x+1
y = y+1
newfile = filename.partition('.')
newfile = newfile[0] + "-clean.png"
img.save(newfile)