A
A
ag3nt77z2019-03-26 14:33:17
Python
ag3nt77z, 2019-03-26 14:33:17

How do I select an area in an image (python)?

I need to highlight a specific area of ​​an image.
This code displays the name of the image color:

from PIL import Image
import webcolors

def get_main_color():
    img = Image.open("image.jpg")
    colors = img.getcolors(1920 * 1920) 
    max_occurence, most_present = 0, 0
    try:
        for c in colors:
            if c[0] > max_occurence:
                (max_occurence, most_present) = c
        return most_present
    except TypeError:
        raise Exception("more colours")
    # функция для определение цвета
    # функция для перевод 3 чисел в наименование цвета
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 = ((get_main_color()))
actual_name, closest_name = get_colour_name(requested_colour)
    
print ("Название цвета обычное:", actual_name, ", Другое название цвета:", closest_name)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question