Find Common Colours in an Image

· 211 words · 1 minute 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.

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!