Recognize the color of a python image

Asked

Viewed 1,848 times

1

As part of my learning in python, I decided to create a simple program that detects the color of an image (solid color). The problem is that I have no idea how to do this, there is some python library that detects the color and gives its value in RGB or Hex?

1 answer

2


One of the Python libraries for working with image is Pillow. With it, you can pick up the colors that appear in an image.

from PIL import Image

# Abre a imagem
img = Image.open("Path/minhaImagem.jpg")

After opening an image, you can scroll pixel by pixel with the .getdata() and see the RGB color of each. If you only want to know which colors appear, just save the unique values. Example:

cores = []
for cor_rgb in img.getdata():
    if cor_rgb not in cores:
        cores.append(cor_rgb)

>>> print(cores)
   [(163, 78, 90), (158, 69, 88), (70, 44, 65), (38, 30, 48)]

An easier way is to use your own .getcolors(), which returns both the colors and the amount in which they appear. It has a parameter maxcolors, which by default is 256 colors. If the number of colors in your image changes from the value of maxcolors, the function returns None.

>>> cores = img.convert('RGB').getcolors()
>>> print(cores)
   None

>>> cores = img.convert('RGB').getcolors(maxcolors=1000)
>>> print(cores)
   [(10, (163, 78, 90)), (1, (158, 69, 88)), ...]
#  [(quantidade, cor_rgb), (quantidade, cor_rgb),...]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.