Color quantization: Difference between revisions

m
(Updated second D entry)
m (→‎{{header|Wren}}: Minor tidy)
 
(28 intermediate revisions by 15 users not shown)
Line 8:
Note: the funny color bar on top of the frog image is intentional.
<br clear=left>
 
=={{header|C}}==
[[file:quantum_frog_C.png|C output|thumb|200px]]
Line 15 ⟶ 16:
# Node folding priorities are tracked by a binary heap instead of typical linked list.
The output image is better at preserving textures of the original than Gimp, though it obviously depends on the input image. This particular frog image has the color bar added at the top specifically to throw off some early truncation algorithms, which Gimp is suseptible to.
<langsyntaxhighlight lang="c">typedef struct oct_node_t oct_node_t, *oct_node;
struct oct_node_t{
/* sum of all colors represented by this node. 64 bit in case of HUGE image */
Line 125 ⟶ 126:
node_free();
free(heap.buf);
}</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
{{libheader|opticl}}
Use median cut.
<syntaxhighlight lang="lisp">(defpackage #:quantize
(:use #:cl
#:opticl))
 
(in-package #:quantize)
 
(defun image->pixels (image)
(check-type image 8-bit-rgb-image)
(let (pixels)
(do-pixels (y x) image
(push (pixel* image y x) pixels))
pixels))
 
(defun greatest-color-range (pixels)
(loop for (r g b) in pixels
minimize r into r-min
minimize g into g-min
minimize b into b-min
maximize r into r-max
maximize g into g-max
maximize b into b-max
finally
(return (let* ((r-range (- r-max r-min))
(g-range (- g-max g-min))
(b-range (- b-max b-min))
(max-range (max r-range g-range b-range)))
(cond ((= r-range max-range) 0)
((= g-range max-range) 1)
(t 2))))))
 
(defun median-cut (pixels target-num-colors)
(assert (zerop (mod (log target-num-colors 2) 1)))
(if (or (= target-num-colors 1) (null (rest pixels)))
(list pixels)
(let* ((channel (greatest-color-range pixels))
(sorted (sort pixels #'< :key (lambda (pixel) (nth channel pixel))))
(half (floor (length sorted) 2))
(next-target (/ target-num-colors 2)))
(nconc (median-cut (subseq sorted 0 half) next-target)
(median-cut (subseq sorted half) next-target)))))
 
(defun quantize-colors (pixels target-num-colors)
(let ((color-map (make-hash-table :test #'equal)))
(dolist (bucket (median-cut pixels target-num-colors) color-map)
(loop for (r g b) in bucket
sum r into r-sum
sum g into g-sum
sum b into b-sum
count t into num-pixels
finally (let ((average (list (round r-sum num-pixels)
(round g-sum num-pixels)
(round b-sum num-pixels))))
(dolist (pixel bucket)
(setf (gethash pixel color-map) average)))))))
 
(defun quantize-image (input-file output-file target-num-colors)
(let* ((image (read-png-file input-file))
(pixels (image->pixels image))
(color-map (quantize-colors pixels target-num-colors))
(result-image (with-image-bounds (height width) image
(make-8-bit-rgb-image height width :initial-element 0))))
(set-pixels (y x) result-image
(let* ((original (multiple-value-list (pixel image y x)))
(quantized (gethash original color-map)))
(values-list quantized)))
(write-png-file output-file result-image)))</syntaxhighlight>
 
=={{header|D}}==
Line 131 ⟶ 202:
{{trans|OCaml}}
This code retains the style of the original OCaML code, and uses the bitmap module from the Bitmap Task.
<langsyntaxhighlight lang="d">import core.stdc.stdio, std.stdio, std.algorithm, std.typecons,
std.math, std.range, std.conv, std.string, bitmap;
 
Line 275 ⟶ 346:
const imq = colorQuantize(im, nCols);
imq.savePPM6("quantum_frog_quantized.ppm");
}</langsyntaxhighlight>
 
===Imperative Version===
{{trans|C}}
This code retains part of the style of the original C code.
<langsyntaxhighlight lang="d">import core.stdc.stdlib: malloc, calloc, realloc, free, abort;
import std.stdio: stderr, File;
import std.ascii: isWhite;
Line 288 ⟶ 359:
import std.exception: enforce;
import std.array: empty;
import std.compilertypetuple: version_minorTypeTuple;
 
enum ON_INHEAP = 1;
Line 324 ⟶ 395:
} while (line.length && line[0] == '#');
 
const size = line.split.to!(uint[]);
static if (version_minor < 66) { //*
const enforce(size.length == line.split.to!(uint[]2);
//immutable enforce(size.length == line.split.to!(uint[2]);
} else {
immutable size = line.split.to!(uint[2]);
}
auto img = imageNew(size[0], size[1]);
enforce(fIn.readln.strip == "255");
Line 355 ⟶ 423:
}
 
struct NodeHeapHeapNode {
uint alloc, n;
OctreeNode** buf;
}
 
int cmpNodecmpOctreeNode(in OctreeNode* a, in OctreeNode* b) pure nothrow @safe @nogc
pure nothrow @safe @nogc
in {
assert(a != null);
assert(b != null);
} out(result) {
assert(result == 0-1 || result == 10 || result == -1);
} body {
if (a.nKids < b.nKids)
Line 377 ⟶ 446:
}
 
void downHeap(NodeHeapHeapNode* h, OctreeNode* p) pure nothrow @nogc
in {
assert(h != null);
Line 388 ⟶ 457:
if (m >= h.n)
break;
if (m + 1 < h.n && cmpNodecmpOctreeNode(h.buf[m], h.buf[m + 1]) > 0)
m++;
 
if (cmpNodecmpOctreeNode(p, h.buf[m]) <= 0)
break;
 
Line 403 ⟶ 472:
}
 
void upHeap(NodeHeapHeapNode* h, OctreeNode* p) pure nothrow @nogc
in {
assert(h != null);
Line 412 ⟶ 481:
while (n > 1) {
auto prev = h.buf[n / 2];
if (cmpNodecmpOctreeNode(p, prev) >= 0)
break;
 
Line 424 ⟶ 493:
}
 
void heapAddaddHeap(NodeHeapHeapNode* h, OctreeNode* p) nothrow @nogc
in {
assert(h != null);
Line 450 ⟶ 519:
}
 
OctreeNode* popHeap(NodeHeapHeapNode* h) pure nothrow @nogc
in {
assert(h != null);
Line 470 ⟶ 539:
}
 
OctreeNode* nodeNewoctreeNodeNew(in ubyte idx, in ubyte depth, OctreeNode* p,
ref OctreeNode[] pool) nothrow @nogc
out(result) {
assert(result != null);
Line 494 ⟶ 563:
}
 
void nodeFreeoctreeNodeFree(ref OctreeNode[] poolArrpool) nothrow @nogc
out {
assert(poolArrpool.length == 0empty);
} body {
auto poolpoolPtr = poolArrpool.ptr;
 
while (poolpoolPtr) {
auto p = poolpoolPtr.parent;
free(poolpoolPtr);
poolpoolPtr = p;
}
 
poolArrpool = null;
}
 
OctreeNode* nodeInsertoctreeNodeInsert(OctreeNode* root, in ubyte* pix, ref OctreeNode[] pool)
nothrow @nogc
in {
assert(root != null);
assert(pix != null);
assert(!pool.length != 0empty);
} out(result) {
assert(result != null);
Line 525 ⟶ 594:
!!(pix[2] & bit);
if (!root.kids[i])
root.kids[i] = nodeNewoctreeNodeNew(i, depth, root, pool);
 
root = root.kids[i];
Line 537 ⟶ 606:
}
 
OctreeNode* nodeFoldoctreeNodeFold(OctreeNode* p) nothrow @nogc
in {
assert(p != null);
Line 575 ⟶ 644:
}
 
void errorDiffuse(Image* im, NodeHeapHeapNode* h) nothrow @nogc
in {
assert(im != null);
Line 615 ⟶ 684:
assert(npx != null);
auto pix = im.pix.ptr;
alias triple = TypeTuple!(0, 1, 2);
 
for (auto px = npx, i = 0u; i < im.h; i++) {
for (uint j = 0; j < im.w; j++, pix += 3, px += 3) {
px[0]/*static*/ =foreach cast(int)pix[0]immutable * CTOTALk; triple)
px[1k] = cast(int)pix[1k] * CTOTAL;
px[2] = cast(int)pix[2] * CTOTAL;
}
}
Line 633 ⟶ 702:
for (auto px = npx, i = 0u; i < im.h; i++) {
for (uint j = 0; j < im.w; j++, pix += 3, px += 3) {
px[0] /=*static*/ CTOTALforeach (immutable k; triple)
px[1k] /= CTOTAL;
px[2] /=*static*/ CTOTALforeach (immutable k; triple)
clamp(px[0k]);
clamp(px[1]);
clamp(px[2]);
 
const nd = nearestColor(px);
uint v[3] v = void;
v[0] = cast(uint)(px[0] - nd.r);
v[1] = cast(uint)(px[1] - nd.g);
Line 651 ⟶ 718:
 
if (j < im.w - 1) {
npx[pos/*static*/ foreach (i,immutable jk; + 1triple) + 0] += v[0] * C10;
npx[pos(i, j + 1) + 1k] += v[1k] * C10;
npx[pos(i, j + 1) + 2] += v[2] * C10;
}
 
Line 659 ⟶ 725:
continue;
 
npx[pos/*static*/ foreach (iimmutable +k; 1, jtriple) + 0] += v[0] * C01;
npx[pos(i + 1, j) + 1k] += v[1k] * C01;
npx[pos(i + 1, j) + 2] += v[2] * C01;
 
if (j < im.w - 1) {
npx[pos(i/*static*/ +foreach 1,(immutable jk; + 1triple) + 0] += v[0] * C11;
npx[pos(i + 1, j + 1) + 1k] += v[1k] * C11;
npx[pos(i + 1, j + 1) + 2] += v[2] * C11;
}
 
if (j) {
npx[pos(i/*static*/ +foreach 1,(immutable jk; - 1triple) + 0] += v[0] * C00;
npx[pos(i + 1, j - 1) + 1k] += v[1k] * C00;
npx[pos(i + 1, j - 1) + 2] += v[2] * C00;
}
}
Line 686 ⟶ 749:
} body {
auto pix = im.pix.ptr;
NodeHeapHeapNode heap = { 0, 0, null };
OctreeNode[] pool;
 
auto root = nodeNewoctreeNodeNew(0, 0, null, pool);
for (uint i = 0; i < im.w * im.h; i++, pix += 3)
heapAddaddHeap(&heap, nodeInsertoctreeNodeInsert(root, pix, pool));
 
while (heap.n > nColors + 1)
heapAddaddHeap(&heap, nodeFoldoctreeNodeFold(popHeap(&heap)));
 
foreach (immutable i; 1 .. heap.n) {
Line 712 ⟶ 775:
}
 
pool.nodeFreeoctreeNodeFree;
heap.buf.free;
}
Line 734 ⟶ 797:
im.free;
return 0;
}</langsyntaxhighlight>
Compiled with ldc2, it runs on the quantum_frog image in about 0.20 seconds with dithering and about 0.10 seconds without dithering.
 
=={{header|Go}}==
A very basic median cut algorithm, no dithering.
<langsyntaxhighlight lang="go">package main
 
import (
Line 758 ⟶ 821:
}
img, err := png.Decode(f)
if ec := f.Close(); err != nil {
if err != nil {
log.Fatal(err)
} else if ec != nil {
log.Fatal(ec)
}
fq, err := os.Create("frog256frog16.png")
if err != nil {
log.Fatal(err)
}
if err = png.Encode(fq, quant(img, 25616)); err != nil {
if err != nil {
log.Fatal(err)
}
Line 1,041 ⟶ 1,104:
*pq = q[:n]
return c
}</langsyntaxhighlight>
 
=={{header|MathematicaHaskell}}==
{{libheader|JuicyPixels}}
<lang Mathematica>ColorQuantize[Import["http://rosettacode.org/mw/images/3/3f/Quantum_frog.png"],16,Dithering->False]</lang>
A variation of the median cut algorithm by splitting color space on the nearest to the mean instead. It provides lower error than the Gimp output sample.
<syntaxhighlight lang="haskell">import qualified Data.ByteString.Lazy as BS
import qualified Data.Foldable as Fold
import qualified Data.List as List
import Data.Ord
import qualified Data.Sequence as Seq
import Data.Word
import System.Environment
 
import Codec.Picture
import Codec.Picture.Types
 
type Accessor = PixelRGB8 -> Pixel8
 
-- Getters for pixel components, as the constructor does not
-- provide any public ones.
red, blue, green :: Accessor
red (PixelRGB8 r _ _) = r
green (PixelRGB8 _ g _) = g
blue (PixelRGB8 _ _ b) = b
 
-- Get all of the pixels in the image in list form.
getPixels :: Pixel a => Image a -> [a]
getPixels image =
[pixelAt image x y
| x <- [0..(imageWidth image - 1)]
, y <- [0..(imageHeight image - 1)]]
 
-- Compute the color-space extents of a list of pixels.
extents :: [PixelRGB8] -> (PixelRGB8, PixelRGB8)
extents pixels = (extent minimum, extent maximum)
where
bound f g = f $ map g pixels
extent f = PixelRGB8 (bound f red) (bound f green) (bound f blue)
 
-- Compute the average value of a list of pixels.
average :: [PixelRGB8] -> PixelRGB8
average pixels = PixelRGB8 (avg red) (avg green) (avg blue)
where
len = toInteger $ length pixels
avg c = fromIntegral $ (sum $ map (toInteger . c) pixels) `div` len
 
-- Perform a componentwise pixel operation.
compwise :: (Word8 -> Word8 -> Word8) -> PixelRGB8 -> PixelRGB8 -> PixelRGB8
compwise f (PixelRGB8 ra ga ba) (PixelRGB8 rb gb bb) =
PixelRGB8 (f ra rb) (f ga gb) (f ba bb)
 
-- Compute the absolute difference of two pixels.
diffPixel :: PixelRGB8 -> PixelRGB8 -> PixelRGB8
diffPixel = compwise (\x y -> max x y - min x y)
 
-- Compute the Euclidean distance squared between two pixels.
distPixel :: PixelRGB8 -> PixelRGB8 -> Integer
distPixel x y = (rr ^ 2) + (gg ^ 2) + (bb ^ 2)
where
PixelRGB8 r g b = diffPixel x y
rr = toInteger r
gg = toInteger g
bb = toInteger b
 
-- Determine the dimension of the longest axis of the extents.
longestAccessor :: (PixelRGB8, PixelRGB8) -> Accessor
longestAccessor (l, h) =
snd $ Fold.maximumBy (comparing fst) $ zip [r, g, b] [red, green, blue]
where
PixelRGB8 r g b = diffPixel h l
 
-- Find the index of a pixel to its respective palette.
nearestIdx :: PixelRGB8 -> [PixelRGB8] -> Int
nearestIdx pixel px = ans
where
Just ans = List.findIndex (== near) px
near = List.foldl1 comp px
comp a b = if distPixel a pixel <= distPixel b pixel then a else b
 
-- Sort a list of pixels on its longest axis and then split by the mean.
-- It is intentional that the mean is chosen by all dimensions
-- instead of the given one.
meanSplit :: [PixelRGB8] -> Accessor -> ([PixelRGB8], [PixelRGB8])
meanSplit l f = List.splitAt index sorted
where
sorted = List.sortBy (comparing f) l
index = nearestIdx (average l) sorted
 
-- Perform the Median Cut algorithm on an image producing
-- an index map image and its respective palette.
meanCutQuant :: Image PixelRGB8 -> Int -> (Image Pixel8, Palette)
meanCutQuant image numRegions = (indexmap, palette)
where
extentsP p = (p, extents p)
regions = map (\(p, e) -> (average p, e))
$ search $ Seq.singleton $ extentsP $ getPixels image
palette = snd $ generateFoldImage (\(x:xs) _ _ -> (xs, x))
(map fst regions) numRegions 1
indexmap = pixelMap
(\pixel -> fromIntegral $ nearestIdx pixel $ map fst regions)
image
search queue =
case Seq.viewl queue of
(pixels, extent) Seq.:< queueB ->
let (left, right) = meanSplit pixels $ longestAccessor extent
queueC = Fold.foldl (Seq.|>) queueB $ map extentsP [left, right]
in if Seq.length queueC >= numRegions
then List.take numRegions $ Fold.toList queueC
else search queueC
Seq.EmptyL -> error "Queue should never be empty."
 
quantizeIO :: FilePath -> FilePath -> Int -> IO ()
quantizeIO path outpath numRegions = do
dynimage <- readImage path
case dynimage of
Left err -> putStrLn err
Right (ImageRGB8 image) -> doImage image
Right (ImageRGBA8 image) -> doImage (pixelMap dropTransparency image)
_ -> putStrLn "Expecting RGB8 or RGBA8 image"
where
doImage image = do
let (indexmap, palette) = meanCutQuant image numRegions
case encodePalettedPng palette indexmap of
Left err -> putStrLn err
Right bstring -> BS.writeFile outpath bstring
 
main :: IO ()
main = do
args <- getArgs
prog <- getProgName
case args of
[path, outpath] -> quantizeIO path outpath 16
_ -> putStrLn $ "Usage: " ++ prog ++ " <image-file> <out-file.png>"</syntaxhighlight>
 
=={{header|J}}==
 
Here, we use a simplistic averaging technique to build an initial set of colors and then use k-means clustering to refine them.
 
<syntaxhighlight lang="j">kmcL=:4 :0
C=. /:~ 256 #.inv ,y NB. colors
G=. x (i.@] <.@* %) #C NB. groups (initial)
Q=. _ NB. quantized list of colors (initial
whilst.-. Q-:&<.&(x&*)Q0 do.
Q0=. Q
Q=. /:~C (+/ % #)/.~ G
G=. (i. <./)"1 C +/&.:*: .- |:Q
end.Q
)</syntaxhighlight>
 
The left argument is the number of colors desired.
 
The right argument is the image, with pixels represented as bmp color integers (base 256 numbers).
 
The result is the colors represented as pixel triples (blue, green, red). They are shown here as fractional numbers, but they should be either rounded to the nearest integer in the range 0..255 (and possibly converted back to bmp integer form) or scaled so they are floating point triples in the range 0..1.
 
<syntaxhighlight lang="j"> 16 kmcL img
7.52532 22.3347 0.650468
8.20129 54.4678 0.0326828
33.1132 69.8148 0.622265
54.2232 125.682 2.67713
56.7064 99.5008 3.04013
61.2135 136.42 4.2015
68.1246 140.576 6.37512
74.6006 143.606 7.57854
78.9101 150.792 10.2563
89.5873 148.621 14.6202
98.9523 154.005 25.7583
114.957 159.697 47.6423
145.816 178.136 33.8845
164.969 199.742 67.0467
179.849 207.594 109.973
209.229 221.18 204.513</syntaxhighlight>
 
=={{header|Java}}==
A simple median cut algorithm.
<syntaxhighlight lang="java">
 
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
import javax.imageio.ImageIO;
 
public final class ColorQuantization {
 
public static void main(String[] aArgs) throws IOException {
BufferedImage original = ImageIO.read( new File("quantum_frog.png") );
final int width = original.getWidth();
final int height = original.getHeight();
int[] originalPixels = original.getRGB(0, 0, width, height, null, 0, width);
List<Item> bucket = new ArrayList<Item>();
for ( int i = 0; i < originalPixels.length; i++ ) {
bucket.add( new Item(new Color(originalPixels[i]), i) );
}
int[] resultPixels = new int[originalPixels.length];
medianCut(bucket, 4, resultPixels);
BufferedImage result = new BufferedImage(width, height, original.getType());
result.setRGB(0, 0, width, height, resultPixels, 0, width);
ImageIO.write(result, "png", new File("Quantum_frog16Java.png"));
System.out.println("The 16 colors used in Red, Green, Blue format are:");
for ( Color color : colorsUsed ) {
System.out.println("(" + color.getRed() + ", " + color.getGreen() + ", " + color.getBlue() + ")");
}
}
private static void medianCut(List<Item> aBucket, int aDepth, int[] aResultPixels) {
if ( aDepth == 0 ) {
quantize(aBucket, aResultPixels);
return;
}
int[] minimumValue = new int[] { 256, 256, 256 };
int[] maximumValue = new int[] { 0, 0, 0 };
for ( Item item : aBucket ) {
for ( Channel channel : Channel.values() ) {
int value = item.getPrimary(channel);
if ( value < minimumValue[channel.index] ) {
minimumValue[channel.index] = value;
}
if ( value > maximumValue[channel.index] ) {
maximumValue[channel.index] = value;
}
}
}
int[] valueRange = new int[] { maximumValue[Channel.RED.index] - minimumValue[Channel.RED.index],
maximumValue[Channel.GREEN.index] - minimumValue[Channel.GREEN.index],
maximumValue[Channel.BLUE.index] - minimumValue[Channel.BLUE.index] };
Channel selectedChannel = ( valueRange[Channel.RED.index] >= valueRange[Channel.GREEN.index] )
? ( valueRange[Channel.RED.index] >= valueRange[Channel.BLUE.index] ) ? Channel.RED : Channel.BLUE
: ( valueRange[Channel.GREEN.index] >= valueRange[Channel.BLUE.index] ) ? Channel.GREEN : Channel.BLUE;
Collections.sort(aBucket, switch(selectedChannel) {
case RED -> redComparator;
case GREEN -> greenComparator;
case BLUE -> blueComparator; });
final int medianIndex = aBucket.size() / 2;
medianCut(new ArrayList<Item>(aBucket.subList(0, medianIndex)), aDepth - 1, aResultPixels);
medianCut(new ArrayList<Item>(aBucket.subList(medianIndex, aBucket.size())), aDepth - 1, aResultPixels);
}
private static void quantize(List<Item> aBucket, int[] aResultPixels) {
int[] means = new int[Channel.values().length];
for ( Item item : aBucket ) {
for ( Channel channel : Channel.values() ) {
means[channel.index] += item.getPrimary(channel);
}
}
for ( Channel channel : Channel.values() ) {
means[channel.index] /= aBucket.size();
}
Color color = new Color(means[Channel.RED.index], means[Channel.GREEN.index], means[Channel.BLUE.index]);
colorsUsed.add(color);
 
for ( Item item : aBucket ) {
aResultPixels[item.aIndex] = color.getRGB();
}
}
private enum Channel {
RED(0), GREEN(1), BLUE(2);
private Channel(int aIndex) {
index = aIndex;
}
private final int index;
}
private record Item(Color aColor, Integer aIndex) {
public int getPrimary(Channel aChannel) {
return switch(aChannel) {
case RED -> aColor.getRed();
case GREEN -> aColor.getGreen();
case BLUE -> aColor.getBlue();
};
}
}
private static Comparator<Item> redComparator =
(one, two) -> Integer.compare(one.aColor.getRed(), two.aColor.getRed());
private static Comparator<Item> greenComparator =
(one, two) -> Integer.compare(one.aColor.getGreen(), two.aColor.getGreen());
private static Comparator<Item> blueComparator =
(one, two) -> Integer.compare(one.aColor.getBlue(), two.aColor.getBlue());
private static List<Color> colorsUsed = new ArrayList<Color>();
}
</syntaxhighlight>
{{ out }}
[[Media:Quantum_frog16Java.png]]
<pre>
The 16 colors used in Red, Green, Blue format are:
(8, 36, 0)
(7, 54, 0)
(22, 66, 0)
(51, 99, 3)
(53, 129, 1)
(64, 140, 2)
(67, 142, 5)
(71, 144, 11)
(79, 143, 11)
(99, 139, 14)
(88, 156, 18)
(129, 171, 23)
(127, 165, 53)
(166, 205, 65)
(165, 189, 123)
(205, 226, 159)
</pre>
 
=={{header|Julia}}==
The Images package for Julia uses the ImageMagick libraries by default, but this Julia module does not currently implement ImageMagick's support for color quantization. However, once ImageMagick is installed for the Images Julia module, a direct call to ImageMagick's convert command is possible.
<syntaxhighlight lang="julia">
const execstring =`convert Quantum_frog.png -dither None -colors 16 Quantum_frog_new.png`
run(execstring)
</syntaxhighlight>
 
=={{header|Kotlin}}==
{{works with|Ubuntu 16.04}}
Rather than coding this from scratch, we invoke programatically ImageMagick's 'convert' tool which has all this stuff built in.
<syntaxhighlight lang="scala">// Version 1.2.41
 
import java.io.BufferedReader
import java.io.InputStreamReader
 
fun main(args: Array<String>) {
// convert 'frog' to an image which uses only 16 colors, no dithering
val pb = ProcessBuilder(
"convert",
"Quantum_frog.png",
"-dither",
"None",
"-colors",
"16",
"Quantum_frog_16.png"
)
pb.directory(null)
val proc = pb.start()
proc.waitFor()
 
// now show the colors used
val pb2 = ProcessBuilder(
"convert",
"Quantum_frog_16.png",
"-format",
"%c",
"-depth",
"8",
"histogram:info:-"
)
pb2.directory(null)
pb.redirectOutput(ProcessBuilder.Redirect.PIPE)
val proc2 = pb2.start()
val br = BufferedReader(InputStreamReader(proc2.inputStream))
var clrNum = 0
while (true) {
val line = br.readLine() ?: break
System.out.printf("%2d->%s\n", clrNum++, line)
}
br.close()
}</syntaxhighlight>
 
{{output}}
The resulting image is as expected and details of the 16 colors used are as follows:
<pre>
0-> 37572: ( 9, 53, 0) #093500 srgb(9,53,0)
1-> 7068: ( 13, 26, 0) #0D1A00 srgb(13,26,0)
2-> 31: ( 15,165, 21) #0FA515 srgb(15,165,21)
3-> 19609: ( 42, 96, 1) #2A6001 srgb(42,96,1)
4-> 21753: ( 57,136, 4) #398804 srgb(57,136,4)
5-> 66865: ( 77,147, 10) #4D930A srgb(77,147,10)
6-> 12275: ( 79,111, 9) #4F6F09 srgb(79,111,9)
7-> 836: ( 94,111, 74) #5E6F4A srgb(94,111,74)
8-> 25689: (105,158, 28) #699E1C srgb(105,158,28)
9-> 5095: (113,163, 85) #71A355 srgb(113,163,85)
10-> 1788: (125,129,151) #7D8197 srgb(125,129,151)
11-> 12929: (145,172, 31) #91AC1F srgb(145,172,31)
12-> 13245: (158,200, 51) #9EC833 srgb(158,200,51)
13-> 17024: (175,210, 86) #AFD256 srgb(175,210,86)
14-> 7913: (177,192, 99) #B1C063 srgb(177,192,99)
15-> 12452: (202,217,188) #CAD9BC srgb(202,217,188)
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ColorQuantize[Import["http://rosettacode.org/mw/images/3/3f/Quantum_frog.png"],16,Dithering->False]</syntaxhighlight>
 
=={{header|Nim}}==
{{libheader|nimPNG}}
We use a simple version of the median cut algorithm, with no special optimizations.
 
<syntaxhighlight lang="nim">import algorithm
import nimPNG
 
type
 
Channel {.pure.} = enum R, G, B
 
QItem = tuple
color: array[Channel, byte] # Color of the pixel.
index: int # Position of pixel in the sequential sequence.
 
#---------------------------------------------------------------------------------------------------
 
proc quantize(bucket: openArray[QItem]; output: var seq[byte]) =
## Apply the quantization to the pixels in the bucket.
 
# Compute the mean value on each channel.
var means: array[Channel, int]
for qItem in bucket:
for channel in R..B:
means[channel] += qItem.color[channel].int
for channel in R..B:
means[channel] = (means[channel] / bucket.len).toInt
 
# Store the new colors into the pixels.
for qItem in bucket:
for channel in R..B:
output[3 * qItem.index + ord(channel)] = means[channel].byte
 
#---------------------------------------------------------------------------------------------------
 
proc medianCut(bucket: openArray[QItem]; depth: Natural; output: var seq[byte]) =
## Apply the algorithm on the bucket.
 
if depth == 0:
# Terminated for this bucket. Apply the quantization.
quantize(bucket, output)
return
 
# Compute the range of values for each channel.
var minVal: array[Channel, int] = [1000, 1000, 1000]
var maxVal: array[Channel, int] = [-1, -1, -1]
for qItem in bucket:
for channel in R..B:
let val = qItem.color[channel].int
if val < minVal[channel]: minVal[channel] = val
if val > maxVal[channel]: maxVal[channel] = val
let valRange: array[Channel, int] = [maxVal[R] - minVal[R],
maxVal[G] - minVal[G],
maxVal[B] - minVal[B]]
 
# Find the channel with the greatest range.
var selchannel: Channel
if valRange[R] >= valRange[G]:
if valRange[R] >= valRange[B]:
selchannel = R
else:
selchannel = B
elif valrange[G] >= valrange[B]:
selchannel = G
else:
selchannel = B
 
# Sort the quantization items according to the selected channel.
let sortedBucket = case selchannel
of R: sortedByIt(bucket, it.color[R])
of G: sortedByIt(bucket, it.color[G])
of B: sortedByIt(bucket, it.color[B])
 
# Split the bucket into two buckets.
let medianIndex = bucket.high div 2
medianCut(sortedBucket.toOpenArray(0, medianIndex), depth - 1, output)
medianCut(sortedBucket.toOpenArray(medianIndex, bucket.high), depth - 1, output)
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
const Input = "Quantum_frog.png"
const Output = "Quantum_frog_16.png"
 
let pngImage = loadPNG24(seq[byte], Input).get()
 
# Build the first bucket.
var bucket = newSeq[QItem](pngImage.data.len div 3)
var idx: Natural = 0
for item in bucket.mitems:
item = (color: [pngImage.data[idx], pngImage.data[idx + 1], pngImage.data[idx + 2]],
index: idx div 3)
inc idx, 3
 
# Create the storage for the quantized image.
var data = newSeq[byte](pngImage.data.len)
 
# Launch the quantization.
medianCut(bucket, 4, data)
 
# Save the result into a PNG file.
let status = savePNG24(Output, data, pngImage.width, pngImage.height)
if status.isOk:
echo "File ", Input, " processed. Result is available in file ", Output
else:
echo "Error: ", status.error</syntaxhighlight>
 
=={{header|OCaml}}==
Line 1,050 ⟶ 1,617:
Here we use a simplified method inspired from this paper: [http://www.leptonica.com/papers/mediancut.pdf www.leptonica.com/papers/mediancut.pdf]
 
<langsyntaxhighlight lang="ocaml">let rem_from rem from =
List.filter ((<>) rem) from
 
Line 1,150 ⟶ 1,717:
done;
done;
(res)</langsyntaxhighlight>
 
=={{header|JPerl}}==
<syntaxhighlight lang="perl">use strict;
use warnings;
 
use Imager;
Here, we use a simplistic averaging technique to build an initial set of colors and then use k-means clustering to refine them.
 
my $img = Imager->new;
<lang j>kmcL=:4 :0
$img->read(file => 'frog.png');
C=. /:~ 256 #.inv ,y NB. colors
my $img16 = $img->to_paletted({ max_colors => 16});
G=. x (i.@] <.@* %) #C NB. groups (initial)
$img16->write(file => "frog-16.png")</syntaxhighlight>
Q=. _ NB. quantized list of colors (initial
Compare offsite images: [https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/frog.png frog.png] vs.
whilst.-. Q-:&<.&(x&*)Q0 do.
[https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/frog-16.png frog-16.png]
Q0=. Q
Q=. /:~C (+/ % #)/.~ G
G=. (i. <./)"1 C +/&.:*: .- |:Q
end.Q
)</lang>
 
=={{header|Phix}}==
The left argument is the number of colors desired.
{{libheader|Phix/pGUI}}
{{trans|Tcl}}
Gui app, shows original and modified side-by-side.
<syntaxhighlight lang="phix">-- demo\rosetta\Color_quantization.exw
include pGUI.e
 
function makeCluster(sequence pixels)
The right argument is the image, with pixels represented as bmp color integers (base 256 numbers).
sequence rs = vslice(pixels,1),
gs = vslice(pixels,2),
bs = vslice(pixels,3)
integer n = length(pixels),
rd = max(rs)-min(rs),
gd = max(gs)-min(gs),
bd = max(bs)-min(bs)
atom score = n*rd*gd*bd
-- atom score = n*(rd+gd+bd) -- (this is how/where to experiment)
sequence centroid = sq_round({sum(rs)/n,sum(gs)/n,sum(bs)/n}),
ranges = {rd,gd,bd}
return {score,centroid,ranges,pixels}
end function
function colorQuant(imImage img, integer n)
integer width = im_width(img),
height = im_width(img)
-- Extract the original pixels from the image
sequence original = {}
integer dx = 1
for y=height-1 to 0 by -1 do
for x=0 to width-1 do
original = append(original,im_pixel(img, x, y)&dx)
dx += 1
end for
end for
-- Divide pixels into clusters
sequence cs = {makeCluster(original)}, unsplittable={}, centroid, volume, pixels
while length(cs)<n do
cs = sort(cs)
-- cs = reverse(sort(cs)) -- (to deliberately show a much worse result)
{?,centroid,volume,pixels} = cs[$]
integer {vr,vg,vb} = volume
integer pdx = iff(vr>vg and vr>vb?1:iff(vg>vb?2:3)),
c = centroid[pdx] -- (ie r=1, g=2, b=3)
sequence p1 = {}, p2 = {}
for i=1 to length(pixels) do
sequence p = pixels[i]
if p[pdx]<c then p1 = append(p1,p) else p2 = append(p2,p) end if
end for
if length(p1) and length(p2) then
cs[$] = makeCluster(p1)
cs = append(cs,makeCluster(p2))
else
?"unsplittable"
unsplittable = append(unsplittable,cs[$])
cs = cs[1..$-1]
n -= 1
end if
end while
cs &= unsplittable
-- substitute all pixels with the centroid (aka cluster average)
for i=1 to length(cs) do
{?,centroid,?,pixels} = cs[i]
for p=1 to length(pixels) do
dx = pixels[p][4]
original[dx] = centroid
end for
end for
original = flatten(original) -- (needed for IupImageRGB)
Ihandle new_img = IupImageRGB(width, height, original)
return new_img
end function
 
IupOpen()
The result is the colors represented as pixel triples (blue, green, red). They are shown here as fractional numbers, but they should be either rounded to the nearest integer in the range 0..255 (and possibly converted back to bmp integer form) or scaled so they are floating point triples in the range 0..1.
 
atom pError = allocate(machine_word())
<lang j> 16 kmcL img
imImage im1 = imFileImageLoadBitmap("Quantum_frog.png",0,pError)
7.52532 22.3347 0.650468
if im1=NULL then ?"error opening Quantum_frog.png" abort(0) end if
8.20129 54.4678 0.0326828
-- stolen from simple_paint (else im_pixel crashed):
33.1132 69.8148 0.622265
-- we are going to support only RGB images with no alpha
54.2232 125.682 2.67713
imImageRemoveAlpha(im1)
56.7064 99.5008 3.04013
if im_color_space(im1)!=IM_RGB then
61.2135 136.42 4.2015
imImage new_image = imImageCreateBased(im1, -1, -1, IM_RGB, -1)
68.1246 140.576 6.37512
imConvertColorSpace(im1, new_image)
74.6006 143.606 7.57854
im1 = imImageDestroy(im1)
78.9101 150.792 10.2563
im1 = new_image
89.5873 148.621 14.6202
end if
98.9523 154.005 25.7583
 
114.957 159.697 47.6423
Ihandln image1 = IupImageFromImImage(im1),
145.816 178.136 33.8845
image2 = colorQuant(im1,16),
164.969 199.742 67.0467
label1 = IupLabel(),
179.849 207.594 109.973
label2 = IupLabel()
209.229 221.18 204.513</lang>
IupSetAttributeHandle(label1, "IMAGE", image1)
IupSetAttributeHandle(label2, "IMAGE", image2)
 
Ihandle dlg = IupDialog(IupHbox({label1, label2}))
IupSetAttribute(dlg, "TITLE", "Color quantization")
IupShow(dlg)
 
IupMainLoop()
IupClose()</syntaxhighlight>
 
=={{header|PureBasic}}==
[[file:Compare_16_Quantum_frog_PureBasic.png|comparison|thumb|200px]]
[[file:Compare_16_Quantum_frog_histograms_PureBasic.png|histogram (external application)|thumb|200px]]
<syntaxhighlight lang="purebasic">
<lang PureBasic>
; ColorQuantization.pb
 
Line 1,417 ⟶ 2,059:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
<syntaxhighlight lang="python">from PIL import Image
 
if __name__=="__main__":
im = Image.open("frog.png")
im2 = im.quantize(16)
im2.show()</syntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket/base
(require racket/class
Line 1,747 ⟶ 2,397:
r g b))
(loop child (add1 level))))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.10}}
 
<syntaxhighlight lang="raku" line>use MagickWand;
use MagickWand::Enums;
 
my $frog = MagickWand.new;
$frog.read("./Quantum_frog.png");
$frog.quantize(16, RGBColorspace, 0, True, False);
$frog.write('./Quantum-frog-16-perl6.png');</syntaxhighlight>
See: [https://github.com/thundergnat/rc/blob/master/img/Quantum-frog-16-perl6.png Quantum-frog-16-perl6.png] (offsite .png image)
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">require('Image::Magick')
 
func quantize_image(n = 16, input, output='output.png') {
var im = %O<Image::Magick>.new
im.Read(input)
im.Quantize(colors => n, dither => 1) # 1 = None
im.Write(output)
}
 
quantize_image(input: 'Quantum_frog.png')</syntaxhighlight>
 
=={{header|Tcl}}==
{{trans|OCaml}}
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
package require Tk
 
Line 1,830 ⟶ 2,504:
}
return $newimg
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="tcl">set src [image create photo -file quantum_frog.png]
set dst [colorQuant $src 16]
# Save as GIF now that quantization is done, then exit explicitly (no GUI desired)
$dst write quantum_frog_compressed.gif
exit</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Nim}}
{{libheader|DOME}}
{{libheader|Wren-dynamic}}
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "dome" for Window
import "graphics" for Canvas, Color, ImageData
import "./dynamic" for Struct
import "./sort" for Sort
 
var QItem = Struct.create("QItem", ["color", "index"])
 
var ColorsUsed = []
 
class ColorQuantization {
construct new(filename, filename2) {
Window.title = "Color quantization"
_image = ImageData.load(filename)
_w = _image.width
_h = _image.height
Window.resize(_w * 2 + 20, _h + 30)
Canvas.resize(_w * 2 + 20, _h + 30)
 
// draw original image on left half of canvas
_image.draw(0, 0)
Canvas.print(filename, _w/4, _h + 10, Color.white)
 
// create ImageData object for the quantized image
_qImage = ImageData.create(filename2, _w, _h)
_qFilename = filename2
}
 
init() {
// build the first bucket
var bucket = List.filled(_w * _h, null)
for (x in 0..._w) {
for (y in 0..._h) {
var idx = x * _w + y
bucket[idx] = QItem.new(_image.pget(x, y), idx)
}
}
var output = List.filled(_w * _h, Color.black)
 
// launch the quantization
medianCut(bucket, 4, output)
 
// load the result into the quantized ImageData object
for (x in 0..._w) {
for (y in 0..._h) {
_qImage.pset(x, y, output[x *_w + y])
}
}
 
// draw the quantized image on right half of canvas
_qImage.draw(_w + 20, 0)
Canvas.print(_qFilename, _w * 5/4 + 20, _h + 10, Color.white)
 
// save it to a file
_qImage.saveToFile(_qFilename)
 
// print colors used to terminal
System.print("The 16 colors used in R, G, B format are:")
for (c in ColorsUsed) {
System.print("(%(c.r), %(c.g), %(c.b))")
}
}
 
// apply the quantization to the colors in the bucket
quantize(bucket, output) {
// compute the mean value on each RGB component
var means = List.filled(3, 0)
for (q in bucket) {
var i = 0
for (val in [q.color.r, q.color.g, q.color.b]) {
means[i] = means[i] + val
i = i + 1
}
}
for (i in 0..2) {
means[i] = (means[i]/bucket.count).floor
}
var c = Color.rgb(means[0], means[1], means[2])
ColorsUsed.add(c)
 
// store the new color in the output list
for (q in bucket) output[q.index] = c
}
 
// apply the algorithm to the bucket of colors
medianCut(bucket, depth, output) {
if (depth == 0) { // terminated for this bucket, apply the quantization
quantize(bucket, output)
return
}
 
// compute the range of values for each RGB component
var minVal = [1000, 1000, 1000]
var maxVal = [-1, -1, -1]
for (q in bucket) {
var i = 0
for (val in [q.color.r, q.color.g, q.color.b]) {
if (val < minVal[i]) minVal[i] = val
if (val > maxVal[i]) maxVal[i] = val
i = i + 1
}
}
var valRange = [maxVal[0] - minVal[0], maxVal[1] - minVal[1], maxVal[2] - minVal[2]]
 
// find the RGB component with the greatest range
var greatest = 0
if (valRange[1] > valRange[0]) greatest = 1
if (valRange[2] > greatest) greatest = 2
// sort the quantization items according to the greatest
var cmp
if (greatest == 0) {
cmp = Fn.new { |i, j|
var t = (i.color.r - j.color.r).sign
if (t != 0) return t
return (i.index - j.index).sign
}
} else if (greatest == 1) {
cmp = Fn.new { |i, j|
var t = (i.color.g - j.color.g).sign
if (t != 0) return t
return (i.index - j.index).sign
}
} else {
cmp = Fn.new { |i, j|
var t = (i.color.b - j.color.b).sign
if (t != 0) return t
return (i.index - j.index).sign
}
}
Sort.quick(bucket, 0, bucket.count-1, cmp)
var medianIndex = ((bucket.count-1)/2).floor
medianCut(bucket[0...medianIndex], depth - 1, output)
medianCut(bucket[medianIndex..-1], depth - 1, output)
}
 
update() {}
 
draw(alpha) {}
}
 
var Game = ColorQuantization.new("Quantum_frog.png", "Quantum_frog_16.png")</syntaxhighlight>
 
{{out}}
<pre>
The 16 colors used in R, G, B format are:
(5, 48, 0)
(20, 62, 0)
(24, 64, 0)
(44, 96, 0)
(61, 126, 2)
(64, 135, 3)
(71, 138, 5)
(74, 142, 7)
(80, 146, 9)
(88, 150, 13)
(99, 155, 20)
(114, 163, 30)
(135, 177, 48)
(159, 194, 70)
(173, 202, 102)
(199, 214, 186)
</pre>
 
{{omit from|AWK}}
{{omit from|GUISS}}
9,476

edits