Answer the question
In order to leave comments, you need to log in
How to determine the color of an image in opencv?
Hello. I have several images with dominant colors on them (for example, 90% of the image is bright red), most of the articles on the net easily give information on how to highlight the dominant color, but it always turns out different. the images have slightly different brightness and many tints, how do i turn a bunch of rgb tints into color: "red", "green".
PS An example with two pictures, and their dominant colors:
I need to get just the text: "reg" and "blue"
Answer the question
In order to leave comments, you need to log in
The solution turned out to be much simpler, you just need to calculate the distance between colors: https
://en.wikipedia.org/wiki/%D0%A4%D0%BE%D1%80%D...
list (php)?
Found an example on js:
https://github.com/dtao/nearest-color
Hastily written. Adapt as needed:
import matplotlib.pyplot as plt
%matplotlib inline
import cv2
from PIL import Image, ImageDraw
import numpy
def get_colors(infile, numcolors=10, swatchsize=20, resize=150):
plt.rcParams['figure.figsize'] = [15, 3]
f,ax = plt.subplots(1,2)
image = Image.open(infile)
orig = image.copy()
image = image.resize((resize, resize))
result = image.convert('P', palette=Image.ADAPTIVE, colors=numcolors)
result.putalpha(0)
colors = result.getcolors(resize*resize)
pal = Image.new('RGB', (swatchsize*numcolors, swatchsize))
draw = ImageDraw.Draw(pal)
posx = 0
for count, col in sorted(colors, key=lambda x: x[0], reverse=True):
draw.rectangle([posx, 0, posx+swatchsize, swatchsize], fill=col)
posx = posx + swatchsize
img = numpy.asarray(pal)
del draw
print('File: ', infile)
for im in sorted(colors, key=lambda x: x[0], reverse=True):
if im[1].index(max(im[1])) == 0:
print(im, 'red')
elif im[1].index(max(im[1])) == 1:
print(im, 'green')
elif im[1].index(max(im[1])) == 2:
print(im, 'blue')
ax[0].imshow(orig)
ax[1].imshow(img)
if __name__ == '__main__':
get_colors('D:\\00\\sample01.jpg', numcolors=1)
get_colors('D:\\00\\sample02.jpg', numcolors=1)
get_colors('D:\\00\\sample03.jpg', numcolors=1)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question