Skip to content

Instantly share code, notes, and snippets.

@jcupitt
Last active November 5, 2019 20:49
Show Gist options
  • Save jcupitt/bf233c9efabdb6483dea5c7243777258 to your computer and use it in GitHub Desktop.
Save jcupitt/bf233c9efabdb6483dea5c7243777258 to your computer and use it in GitHub Desktop.
make a solid image of the dominant colour
#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';
use Jcupitt\Vips;
$im = Vips\Image::newFromFile($argv[1], ['access' => 'sequential']);
# 3D histogram ... make 10 x 10 x 10 bins, so 1000 possible colours
$n_bins = 10;
$hist = $im->hist_find_ndim(['bins' => $n_bins]);
# black is usually background or boring, so set that cell to 0 counts
# fetch (0, 0), set the 0th element of that to 0, paste back
$pixel = $hist->getpoint(0, 0);
$pixel[0] = 0;
$pixel = Vips\Image::black(1, 1)->add($pixel);
$hist = $hist->insert($pixel, 0, 0);
# (x, y) pixel with the most counts
[$v, $x, $y] = $hist->maxpos();
$pixel = $hist->getpoint($x, $y);
$z = array_search($v, $pixel);
# convert indexes to rgb ... +0.5 to get the centre of each bin
$r = ($x + 0.5) * 256 / $n_bins;
$g = ($y + 0.5) * 256 / $n_bins;
$b = ($z + 0.5) * 256 / $n_bins;
# make an image with that colour, with the same format / interpretation /
# size / etc. as the original
$patch = $im->newFromImage([$r, $g, $b]);
$patch->writeToFile($argv[2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment