P
P
Phoen1xx2020-12-12 23:25:15
OpenCV
Phoen1xx, 2020-12-12 23:25:15

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:
26159966_38674.jpg
a2b22acc18b6bb9227550d4e8b30796bcb21058er1-1080-1221v2_hq.jpg
I need to get just the text: "reg" and "blue"

Answer the question

In order to leave comments, you need to log in

4 answer(s)
P
Phoen1xx, 2020-12-13
@Phoen1xx

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

V
Vladimir Kuts, 2020-12-13
@fox_12

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)

5fd5c6a7ca653162348895.png

D
Dimonchik, 2020-12-12
@dimonchik2013

normalization

V
Viktor T2, 2020-12-13
@Viktor_T2

g python hex color to name
https://stackoverflow.com/questions/9694165/conver...
https://pypi.org/project/webcolors/1.3/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question