Skip to content

Instantly share code, notes, and snippets.

@jrg94
Last active July 11, 2020 07: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 jrg94/f9339f0c8e9c93be85f0444b9e897a80 to your computer and use it in GitHub Desktop.
Save jrg94/f9339f0c8e9c93be85f0444b9e897a80 to your computer and use it in GitHub Desktop.
Finds the closest RGB value
from PIL import Image
import numpy
def color_diff(color1, color2):
return numpy.sum((color1 - color2) ** 2) ** 1/2
def hsv(rgb):
hue = numpy.array(rgb) / 255
value_index = numpy.argmax(hue)
value = hue[value_index]
delta = value - numpy.min(hue)
if delta == 0:
hue = 0
elif value_index == 0:
hue = 60 * ((hue[1] - hue[2]) / delta)
elif value_index == 1:
hue = 60 * (((hue[2] - hue[0]) / delta) + 2)
else:
hue = 60 * (((hue[0] - hue[1]) / delta) + 4)
saturation = 0 if value == 0 else delta / value
return hue, saturation, value
def rgb(h, s, v):
c = v * s
x = c * (1 - abs(((h / 60) % 2) - 1))
m = v - c
if 0 <= h < 60:
prime = (c, x, 0)
elif 60 <= h < 120:
prime = (x, c, 0)
elif 120 <= h < 180:
prime = (0, c, x)
elif 180 <= h < 240:
prime = (0, x, c)
elif 240 <= h < 300:
prime = (x, 0, c)
else:
prime = (c, 0, x)
prime = numpy.array(prime)
return tuple((prime + m) * 255)
def search(path, rgb):
im: Image.Image = Image.open(path)
pix = im.load()
minimum = (0, 0)
for x in range(im.width):
for y in range(im.height):
dist = color_diff(numpy.array(rgb), numpy.array(pix[x, y]))
if dist < color_diff(numpy.array(rgb), numpy.array(pix[minimum[0], minimum[1]])):
minimum = (x, y)
reticle = Image.open('pso2/reticle.png')
im.paste(reticle, (minimum[0] - 13, minimum[1] - 13), reticle)
im.show()
im.save('pso2/dump2.png')
nagatoro_skin = (233, 183, 146) # nagatoro
search('pso2/human-newman.png', nagatoro_skin)
nagatoro_iris = (81,113,80)
h, s, v = hsv(nagatoro_iris)
print(h, s, v)
nagatoro_iris = rgb(h, 1, v)
print(nagatoro_iris)
search('pso2/cast.png', nagatoro_iris)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment