find dominant colour in an 8-bit RGB Image with libvips python
#!/usr/bin/python
import sys
from gi.repository import Vips
im = Vips.Image.new_from_file(sys.argv[1], access = Vips.Access.SEQUENTIAL)
N_BINS = 10
BIN_SIZE = 256 / N_BINS
# make a 3D histogram of the RGB image ... 10 bins in each axis
hist = im.hist_find_ndim(bins = N_BINS)
# find the position of the maximum
v, x, y = hist.maxpos()
# get the pixel at (x, y)
pixel = hist(x, y)
# find the index of the max value in the pixel
band = pixel.index(v)
print "dominant colour:"
print " R = ", x * BIN_SIZE + BIN_SIZE / 2
print " G = ", y * BIN_SIZE + BIN_SIZE / 2
print " B = ", band * BIN_SIZE + BIN_SIZE / 2
#!/usr/bin/python
import sys
from gi.repository import Vips
N_BINS = 10
BIN_SIZE = 256 / N_BINS
im = Vips.Image.new_from_file(sys.argv[1], access = Vips.Access.SEQUENTIAL)
# turn to lab
im = im.colourspace("lab")
# turn to 8-bit unsigned so we can make a histogram
# use 0 - 255 to be -128 - +127 for a/b
# and 0 - 255 for 0 - 100 L
im += [0, 128, 128]
im *= [255.0 / 100, 1, 1]
im = im.cast("uchar")
# make a 3D histogram of the 8-bit LAB image
hist = im.hist_find_ndim(bins = N_BINS)
# find the position of the maximum
v, x, y = hist.maxpos()
# get the pixel at (x, y)
pixel = hist(x, y)
# find the index of the max value in the pixel
band = pixel.index(v)
# scale up for the number of bins
x = x * BIN_SIZE + BIN_SIZE / 2
y = y * BIN_SIZE + BIN_SIZE / 2
band = band * BIN_SIZE + BIN_SIZE / 2
# turn the index back into the LAB colour
L = x * (100.0 / 255)
a = y - 128
b = band - 128
print "dominant colour:"
print " L = ", L
print " a = ", a
print " b = ", b