Reputation: 686
I need to get the color of a pixels in a specifict region of image. Im using this script in python:
import cv2
image = cv2.imread('abc.jpg')
color = image[100,50]
print(color) # gives me the RGB color (12,156,222)
and if a need to get the hex of it:
hex = (color[0] << 16) + (color[1] << 8) + (color[2])
my question is: There is a way to tell me what color is it? (12,156,222)
thank you.
Upvotes: 2
Views: 3611
Reputation: 686
I found another way to solve this problem
using webcolor
i was able to detect the closest color
import webcolors
import time
start = time.time()
def closest_colour(requested_colour):
min_colours = {}
for key, name in webcolors.CSS3_HEX_TO_NAMES.items():
r_c, g_c, b_c = webcolors.hex_to_rgb(key)
rd = (r_c - requested_colour[0]) ** 2
gd = (g_c - requested_colour[1]) ** 2
bd = (b_c - requested_colour[2]) ** 2
min_colours[(rd + gd + bd)] = name
return min_colours[min(min_colours.keys())]
def get_colour_name(requested_colour):
try:
closest_name = actual_name = webcolors.rgb_to_name(requested_colour)
except ValueError:
closest_name = closest_colour(requested_colour)
actual_name = None
return actual_name, closest_name
requested_colour = (255, 0, 0)
actual_name, closest_name = get_colour_name(requested_colour)
print("Actual colour name:", actual_name, ", closest colour name:", closest_name)
print("Tempo: ", time.time() - start)
if anyone have another bester method please send here ^^
Upvotes: 1
Reputation: 20425
You can look it up at: https://shallowsky.com/colormatch/index.php?r=12&g=156&b=222
[spoiler alert: "DeepSkyBlue3"]
In general, you want to start with
Then it's a matter of computing distance between each of those and your target value. Return the corresponding name for whichever list entry has minimum distance to target.
A previous SO answer offers such an algorithm: Python - Find similar colors, best way
Using Euclidean distance (L2 norm) in some random color space is less than principled, though often sufficient. If you want to sweat the details, consider relying on https://python-colormath.readthedocs.io. (You might even want to discuss maintainership with the author.)
If "perceptually similar" matters to you, definitely use Lab: https://en.wikipedia.org/wiki/CIELAB_color_space
Upvotes: 0