THE DESSERT & TABLE ATELIER

Extract Colours from an Image with Python

Learn how to extract colors from an image with Python using Pillow, ColorThief and k-means clustering, and turn the results into clean hex codes for a palette.

8 min read48 viewsExtract Colours from an Image with Python
— · 0 votes
Contents
  1. What extracting colors from an image means
  2. Read the image with Pillow
  3. Get a quick palette with ColorThief
  4. Cluster pixels with k-means
  5. Steps from file to hex output
  6. Convert RGB values to hex codes
  7. Choose colors that suit a celebration palette
  8. Where the method can go wrong
  9. Questions about extracting image colors in Python
  10. How do I extract colors from an image in Python?
  11. Do I need k-means clustering to get a palette?
  12. Why do my extracted colors look different from the photo?
  13. How many colors should I ask for?
  14. How do I turn the result into hex codes?

You extract colors from an image in Python by reading the pixels with a library such as Pillow, then grouping those pixels into a short list of representative colors. Simple libraries return the dominant color or a small set of dominant colors, while k-means clustering gives you control over how many colors you get. The output is a set of RGB values you can convert to hex codes for a design or celebration palette.

  • Read the file with Pillow first so you have pixel data to analyze, and downscale large images before clustering.
  • ColorThief returns one dominant color or a short palette without any tuning of cluster counts.
  • K-means clustering lets you choose how many colors the palette holds and works on sampled pixels.
  • Convert each RGB result to a six-character hex output so the values fit design and CSS tools.
  • Lighting and the area you crop change the result, so check the palette against the source image.

What extracting colors from an image means

Extracting colors from an image means reducing thousands of pixels into a small set of values that represent the picture. An image pixel analysis step reads each pixel as a red, green and blue value on a scale from zero to 255. Grouping similar values gives you a palette instead of a noisy list.

The result depends on what the image contains and how you sample it. A photo of a dessert table mixes cake, linen, flowers and background, so the palette reflects all of those areas. Cropping to the part you care about gives a tighter and more useful result.

The extracted set is a summary, not a full record of the file. Two images with similar tones can still produce slightly different values. Treat the output as a starting point you refine by eye.

Read the image with Pillow

Pillow is the standard Python library for opening and converting image files, and it provides the pixel data every other method uses. Open the file, convert it to RGB mode, and then access the pixel list or the raw bytes. Converting first avoids surprises with palette or grayscale files.

Large photos slow down any analysis, so resize the image to a smaller width before you read the pixels. Shrinking keeps the color proportions while cutting the work. A width of a few hundred pixels is enough for a palette.

Pillow alone does not cluster colors, but it handles loading, resizing and pixel access reliably. Pair it with a clustering step or a palette library to finish the job.

Get a quick palette with ColorThief

ColorThief is a small Python library built on Pillow that returns a dominant colour or a short palette without configuration. Pass it an opened image and ask for the main color or a list of colors. The library handles the grouping for you.

A dominant colour result is useful when you need one anchor tone for a palette or a background. A short palette of several values suits a dessert table scheme where you want a main tone and accents. Both come back as RGB tuples.

ColorThief trades control for speed, so you cannot set the exact number of clusters. When you need a specific count or want to test different groupings, move to a clustering method.

Cluster pixels with k-means

K-means clustering groups pixels into a chosen number of clusters and returns the center of each one as a color. You decide how many colors the palette should hold, which makes the method flexible. The centers are the values you keep.

Sampling the pixels before clustering keeps the run fast without changing the outcome much. A random sample of a few thousand pixels from a resized image is enough. Set a fixed random seed so repeated runs give the same palette.

The scikit-learn library offers a ready k-means implementation, and you can also write a short version with NumPy. Label each cluster and count its pixels to see which colors cover the image. Sorting the palette by cluster size puts the most present tone first.

Steps from file to hex output

A reliable flow moves from the file to a cleaned pixel set, then to a palette, then to hex codes. Each step is short and easy to check. Keep the intermediate results so you can compare them with the image.

Reading, resizing and sampling belong together because they all prepare the data. Clustering and sorting belong together because they produce the final order. The conversion to hex is a formatting step that changes nothing about the colors.

Run the whole flow once and look at the palette next to the source image. If a tone is missing or too much background appears, adjust the crop or the number of clusters. The steps repeat cleanly.

  • Open the image with Pillow and convert it to RGB mode.
  • Resize to a small width and collect the pixel values.
  • Sample the pixels so clustering runs fast.
  • Cluster the sample with k-means and read the cluster centers.
  • Sort the centers by cluster size, largest first.
  • Convert each RGB value to a six-character hex code.
  • Compare the palette with the source image and adjust the crop if needed.

Convert RGB values to hex codes

A hex output is a six-character string that encodes red, green and blue in pairs of digits. Convert each channel from 0 to 255 into a two-digit hexadecimal number and join the three pairs after a hash sign. Python formats this with a short string expression.

The conversion is a formatting step, so the color does not change. Write a small function that takes a tuple and returns the string. Use it on every value in the palette to keep the output consistent.

Readable hex values fit design tools, CSS and palette notes without further editing. Keep the RGB tuples alongside the hex strings in case a tool needs the numeric form. Both describe the same color.

Choose colors that suit a celebration palette

An extracted palette is a raw reading of the image, and a celebration palette needs a few roles filled rather than many tones. Pick one anchor color for the dessert table linen or backdrop, then one or two accents and a neutral. Fewer roles make the table read clearly.

Crop the image to the area whose colors you actually want. A crop of the cake and flowers gives a tighter result than the whole room. Background walls and floors pull the palette toward neutral tones.

Adjust the extracted tones by eye when you move them to real materials. Fabric and icing can read darker or lighter than a screen shows. Test the palette against a sample before you commit to a scheme.

Where the method can go wrong

Warm lighting shifts every color in a photo toward yellow or orange, so the extracted palette inherits that cast. Check the image on a neutral screen and compare the tones with something white in the frame. Correcting the white balance before analysis gives a truer result.

Too many clusters split one tone into near-duplicates, while too few merge distinct colors into a muddy average. Start with a small number and add clusters only when a real tone is missing. The labels and cluster sizes help you judge.

Scattered background details can dominate a palette even when they matter little to the subject. Sampling a crop and comparing the cluster sizes shows what drives the result. Refine the crop before you refine the code.

Questions about extracting image colors in Python

How do I extract colors from an image in Python?

You extract colors from an image in Python by loading the file with Pillow, collecting the pixel values and grouping them into a short list of colors. ColorThief does the grouping for you, while k-means clustering lets you set the number of colors. The output is a set of RGB values you can convert to hex codes.

Do I need k-means clustering to get a palette?

No, k-means clustering is optional for a palette. A library such as ColorThief returns a dominant colour or a short set of colors without tuning. K-means gives you control over the exact number of colors and lets you sort them by how much of the image they cover.

Why do my extracted colors look different from the photo?

Extracted colors can differ from the photo because lighting, white balance and background areas all shape the result. The method averages many pixels, so a tone that reads clearly to your eye can blend with neighbors. Correcting the white balance and cropping to the subject brings the palette closer to what you see.

How many colors should I ask for?

A small number of colors keeps the palette useful, and the right count depends on the image and the job. A single dominant colour suits an anchor tone, while a celebration scheme fills a few roles with one anchor, one or two accents and a neutral. Add clusters only when a real tone is clearly missing.

How do I turn the result into hex codes?

The result becomes a hex output by converting each red, green and blue channel from 0 to 255 into a two-digit hexadecimal number. Join the three pairs after a hash sign to make a six-character string. A short Python function applied to each tuple does the job.

Read next

Latest articles