Find Common Colours in an Image

· 251 words · 2 minutes read

This is part 1 of how to find the dominant colours within an image. You might spot this functionality around the internet, as it’s used to give images background colours before the image has loaded.

We use a package to do this - which manages much of the heavy lifting. The package, called prominentcolor, uses the Kmeans++ algorithm to work this out. By default, it will return us the three most popular colours after both cropping and resizing the image.

First, we load the image from file into an Image type. This can them be passed in to be processed. Once we have our three colours, we simply print each one to screen.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package main

import (
    "fmt"
    "image"
    "log"
    "os"

    "github.com/EdlinOrg/prominentcolor"
)

func main() {

    // Step 1: Load the image
    img, err := loadImage("example.jpg")
    if err != nil {
        log.Fatal("Failed to load image", err)
    }

    // Step 2: Process it
    colours, err := prominentcolor.Kmeans(img)
    if err != nil {
        log.Fatal("Failed to process image", err)
    }

    fmt.Println("Dominant colours:")
    for _, colour := range colours {
        fmt.Println("#" + colour.AsString())
    }
}

func loadImage(fileInput string) (image.Image, error) {
    f, err := os.Open(fileInput)
    if err != nil {
        return nil, err
    }
    defer f.Close()
    img, _, err := image.Decode(f)
    return img, err
}

common colours in an image

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!