golang package to find the K most dominant/prominent colors in an image

Overview

Go Report Card GoDoc

prominentcolor

Find the K most dominant colors in an image

The Kmeans function returns the K most dominant colors in the image, ordered in the order of dominance.

To execute it with the default values, call

func Kmeans(orgimg image.Image) (centroids []ColorItem)

which takes an image and returns the K dominant colors, sorted by the most frequent one first.

It uses Kmeans++ to pick K initial centroid values, and goes through all pixels to re-calculate the centroids used.

As default function Kmeans uses these settings:

  • K=3
  • crops the center of the image before resizing (removing 25% on all sides)
  • resizes to 80 pixels
  • uses Kmeans++
  • uses median value to find the color for the centroid
  • mask out white, black or green backgrounds

To have more control, call KmeansWithArgs or KmeansWithAll. Below are the parameters that can be tweaked when calling those functions.

K

As default it has got K=3.

If set to high, it will get too detailed and would separate nuances of the same color in different centroids.

Resizing

As default it resizes the image to 80 pixels wide (and whatever height to preserve aspect ratio).

The higher value, the more time it will take to process since it goes through all pixels.

Arguments

ArgumentSeedRandom : Kmeans++ vs Random

As default it uses Kmeans++.

Kmeans++ will take K points that are as far away from each other as possible, to avoid that the points might be too close to each other and really could be in the same cluster. Hence the initial step takes slightly longer than just randomly picking the initial K starting points.

ArgumentAverageMean : Median vs mean for picking color

As default it uses median.

When the colors are being lumped together in the K clusters, it can pick the mean value, meaning adding all values together and dividing by the number of colors in that cluster. This will make the centroid color to be close to the color of the majority of the pixels in that cluster. Median will take the median value, i.e. just take the one in the middle of all colors in the cluster.

ArgumentNoCropping : Crop to center of image vs not cropping

As default, it crops the center of the image (removing 25% on all sides).

The theory being that the most relevant area in the image is in the middle, so even if the most dominant color in that area is not the most dominant color in the whole image, it might be what the user percieve as most dominant.

The image below contains mostly green color, but since the flower is in the center of the image, we might be interested in perceiving that as the dominant color. When cropping (default) it finds pink to be most dominant, without cropping (by setting ArgumentNoCropping), green is most dominant.

Using cropCenter

ArgumentLAB : RGB vs LAB

As default it uses RGB.

LAB is experimental atm, hence RGB is default.

ArgumentDebugImage : Save temporary image

Saves an image in /tmp/ where the pixels that have been masked out are colored pink. Useful when modifying the values of the masks, so you can observe the result.

Masking; removing background colours

GetDefaultMasks is the function containing the masks used as default, they can be used as a starting point when passing other masks to the function. As default it filters white, black or green backgrounds.

To handle items that are shot against white/black/green background ("isolated" objects / clipart / green screen images), the image is pre-processed to disregard the white/black/green background: If the four corners are in that same color (or close to it), the code will take those as starting points for the areas to be removed.

In the image below, it removes much of the white (the pink pixels are the pixels that have been removed). By removing those areas, "white" will have less of a chance of becoming the dominant color.

Ignoring backgrounds

Sample code

See example/example.go and example2/example2.go for sample calls with different parameters.

The sample images in example/ comes from flickr and are all Public Domain https://creativecommons.org/publicdomain/zero/1.0/

The images used:

Author

Carl Asman (www.edlin.org)

BSD License

See LICENSE

You might also like...
Imaging is a simple image processing package for Go
Imaging is a simple image processing package for Go

Imaging Package imaging provides basic image processing functions (resize, rotate, crop, brightness/contrast adjustments, etc.). All the image process

Go package for decoding and encoding TARGA image format

tga tga is a Go package for decoding and encoding TARGA image format. It supports RLE and raw TARGA images with 8/15/16/24/32 bits per pixel, monochro

Go Perceptual image hashing package

goimagehash Inspired by imagehash A image hashing library written in Go. ImageHash supports: Average hashing Difference hashing Perception hashing Wav

Go package captcha implements generation and verification of image and audio CAPTCHAs.
Go package captcha implements generation and verification of image and audio CAPTCHAs.

Package captcha ⚠️ Warning: this captcha can be broken by advanced OCR captcha breaking algorithms. import "github.com/dchest/captcha" Package captch

package for convert DataURLs to image

convert base64 DataURLs to image

A Go package converting a monochrome 1-bit bitmap image into a set of vector paths.
A Go package converting a monochrome 1-bit bitmap image into a set of vector paths.

go-bmppath Overview Package bmppath converts a monochrome 1-bit bitmap image into a set of vector paths. Note that this package is by no means a sophi

magicimage is a simple image validation & save with rich feature package for net/http

Installation go get github.com/IndominusByte/magicimage Usage examples A few usage examples can be found below. See the documentation for the full lis

Pbm - Package ppm implements a Portable Bit Map (PBM) image decoder and encoder written in Go

Package pbm import "github.com/slashformotion/pbm" Package pbm implements a Portable Bit Map (PBM) image decoder and encoder. The supported image col

Find out where you fall on the Open-Source Character Alignment Chart

gitaligned Find out where you fall on the Open-Source Character Alignment Chart Binaries available in releases. If you prefer to install from source,

Comments
  • Reworked example

    Reworked example

    First, thank you for your work, your library has been very useful.

    During my tests, I just had to modify the example to avoid rewriting it in order to test a lot of images without editing the code. The main modification is a dynamic listing and use of all '.jpg' files (other extensions can be easily added) within the current working directory. I also changed a bit the strings building, not that was really necessary, just habits.

    I was thinking that this dynamic images lookup could help others so here is a small PR :)

    opened by hekmon 1
  • Panic with completely black image

    Panic with completely black image

    Hi, I'm found a problem while i try to check dominant color on completely black image like the one below.

    black

    This is my code:

    cols := prominentcolor.KmeansWithAll(3, img, prominentcolor.ArgumentNoCropping, 80, []prominentcolor.ColorBackgroundMask{})
    
    col := cols[0].AsString()
    fmt.Println("#"+col)
    

    This is the output that i recive:

    2018/01/21 16:31:05 Failed, k larger than len(allColors): 3 vs 0
    panic: invalid argument to Intn
    
    goroutine 1 [running]:
    math/rand.(*Rand).Intn(0xc042072270, 0x0, 0x3)
    	{GO_PATH}/src/math/rand/rand.go:142 +0xa3
    math/rand.Intn(0x0, 0x0)
    	{GO_PATH}/src/math/rand/rand.go:277 +0x3e
    github.com/EdlinOrg/prominentcolor.kmeansPlusPlusSeed(0x3, 0x8, 0x614528, 0x0, 0x0, 0x0, 0x0, 0x0)
    	{GO_PATH}/src/github.com/EdlinOrg/prominentcolor/kmeans.go:387 +0xd7
    github.com/EdlinOrg/prominentcolor.kmeansSeed(0x3, 0x614528, 0x0, 0x0, 0x8, 0x0, 0xc0429de3c0, 0x5e3700)
    	{GO_PATH}/src/github.com/EdlinOrg/prominentcolor/kmeans.go:357 +0x18e
    github.com/EdlinOrg/prominentcolor.KmeansWithAll(0x3, 0x5e3700, 0xc0429de3c0, 0x8, 0x50, 0xc04296dec4, 0x3, 0x3, 0x501daa, 0xc042002020, ...)
    	{GO_PATH}/src/github.com/EdlinOrg/prominentcolor/kmeans.go:111 +0x104
    github.com/EdlinOrg/prominentcolor.KmeansWithArgs(0x8, 0x5e3700, 0xc0429de3c0, 0xc0429de3c0, 0x0, 0x0)
    	{GO_PATH}/src/github.com/EdlinOrg/prominentcolor/kmeans.go:101 +0x104
    main.main()
    	{PROJECT_PATH}/main.go:38 +0x1d1
    

    At the moment i moved to jakekausler/[email protected] a fork of this project that return errors instead of panic, so i can handle exceptions.

    How can i have #000000 instead of panic?

    opened by Pe46dro 1
  • add ErrNoPixelsFound

    add ErrNoPixelsFound

    I'm currently forced to check for this error by comparing the string content.

    items, err := prominentcolor.Kmeans(m)
    if err != nil {
    	if strings.Contains(err.Error(), "Failed, no non-alpha pixels found") {
    		// special case
    	}
    	return err
    }
    

    This change would allow me to use errors.Is:

    items, err := prominentcolor.Kmeans(m)
    if errors.Is(err, prominentcolor.ErrNoPixelsFound) {
    	// special case
    }
    if err != nil {
    	return err
    }
    
    opened by icholy 0
  • Mask Problem

    Mask Problem

    The following image produce the incorrect result:

    Failed, no non-alpha pixels found (either fully transparent image, or the ColorBackgroundMask removed all pixels)

    resizeSize := uint(prominentcolor.DefaultSize)
    bgmasks := []prominentcolor.ColorBackgroundMask{prominentcolor.MaskWhite}
    colours, err := prominentcolor.KmeansWithAll(
    		5, img, prominentcolor.ArgumentNoCropping|prominentcolor.ArgumentAverageMean|prominentcolor.ArgumentDebugImage,
    		resizeSize, bgmasks)
    

    test

    I believe all single color images have the same problem

    opened by terzano 0
Releases(v1.0.0)
Owner
Carl
First software engineer hired at Pond5, created golangprojects.com, jobhunt.ai and gphangouts (the latter is now dead). More info at https://www.edlin.org
Carl
ColorX is a library to determine the most prominent color in an image written in golang

ColorX is a library to determine the most prominent color in an image. ColorX doesn't use any sort of complex algorithms to calculate the prominent color, it simply loops over the image pixels and returns the color that occurs the most.

Hesham Abourgheba 1 Nov 11, 2021
Image - This repository holds supplementary Go image librariesThis repository holds supplementary Go image libraries

Go Images This repository holds supplementary Go image libraries. Download/Insta

null 0 Jan 5, 2022
A library for playing with colors in go (golang).

go-colorful A library for playing with colors in Go. Supports Go 1.13 onwards. Why? I love games. I make games. I love detail and I get lost in detail

Lucas Beyer 1k Dec 30, 2022
Palette: Just colors with Golang

palette Just colors. Go. Contributing I welcome palettes of all kinds but just to be sure file an issue with the palette(s) you wish to add. Add your

Patricio Whittingslow 0 Dec 18, 2021
darkroom - An image proxy with changeable storage backends and image processing engines with focus on speed and resiliency.

Darkroom - Yet Another Image Proxy Introduction Darkroom combines the storage backend and the image processor and acts as an Image Proxy on your image

Gojek 203 Dec 6, 2022
Easily customizable Social image (or Open graph image) generator

fancycard Easily customizable Social image (or Open graph image) generator Built with Go, Gin, GoQuery and Chromedp Build & Run Simply, Clone this rep

Youngbin Han 4 Jan 14, 2022
An API which allows you to upload an image and responds with the same image, stripped of EXIF data

strip-metadata This is an API which allows you to upload an image and responds with the same image, stripped of EXIF data. How to run You need to have

Cristina Simionescu 0 Nov 25, 2021
Imgpreview - Tiny image previews for HTML while the original image is loading

imgpreview This is a Go program that generates tiny blurry previews for images t

Dmitry Chestnykh 8 May 22, 2022
A note taking app, that you can draw in, syncs to the cloud, and is on most platforms!

About NoteDraw About · How to contribute · How to run Structure Codebase Description SRC The sorce code for the client side (Go) Branches Only Ones th

YummyOreo 1 Jul 11, 2022
Go package for fast high-level image processing powered by libvips C library

bimg Small Go package for fast high-level image processing using libvips via C bindings, providing a simple programmatic API. bimg was designed to be

Tom 2.1k Jan 2, 2023