Color quantization: Difference between revisions
m
→{{header|Wren}}: Minor tidy
(Added Wren) |
m (→{{header|Wren}}: Minor tidy) |
||
(3 intermediate revisions by 2 users not shown) | |||
Line 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.
<
struct oct_node_t{
/* sum of all colors represented by this node. 64 bit in case of HUGE image */
Line 126:
node_free();
free(heap.buf);
}</
=={{header|Common Lisp}}==
{{libheader|opticl}}
Use median cut.
<
(:use #:cl
#:opticl))
Line 196:
(quantized (gethash original color-map)))
(values-list quantized)))
(write-png-file output-file result-image)))</
=={{header|D}}==
Line 202:
{{trans|OCaml}}
This code retains the style of the original OCaML code, and uses the bitmap module from the Bitmap Task.
<
std.math, std.range, std.conv, std.string, bitmap;
Line 346:
const imq = colorQuantize(im, nCols);
imq.savePPM6("quantum_frog_quantized.ppm");
}</
===Imperative Version===
{{trans|C}}
This code retains part of the style of the original C code.
<
import std.stdio: stderr, File;
import std.ascii: isWhite;
Line 797:
im.free;
return 0;
}</
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.
<
import (
Line 1,104:
*pq = q[:n]
return c
}</
=={{header|Haskell}}==
{{libheader|JuicyPixels}}
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.
<
import qualified Data.Foldable as Fold
import qualified Data.List as List
Line 1,236:
case args of
[path, outpath] -> quantizeIO path outpath 16
_ -> putStrLn $ "Usage: " ++ prog ++ " <image-file> <out-file.png>"</
=={{header|J}}==
Line 1,242:
Here, we use a simplistic averaging technique to build an initial set of colors and then use k-means clustering to refine them.
<
C=. /:~ 256 #.inv ,y NB. colors
G=. x (i.@] <.@* %) #C NB. groups (initial)
Line 1,251:
G=. (i. <./)"1 C +/&.:*: .- |:Q
end.Q
)</
The left argument is the number of colors desired.
Line 1,259:
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.
<
7.52532 22.3347 0.650468
8.20129 54.4678 0.0326828
Line 1,275:
164.969 199.742 67.0467
179.849 207.594 109.973
209.229 221.18 204.513</
=={{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.
<
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.
<
import java.io.BufferedReader
Line 1,327 ⟶ 1,481:
}
br.close()
}</
{{output}}
Line 1,351 ⟶ 1,505:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
=={{header|Nim}}==
Line 1,357 ⟶ 1,511:
We use a simple version of the median cut algorithm, with no special optimizations.
<
import nimPNG
Line 1,457 ⟶ 1,611:
echo "File ", Input, " processed. Result is available in file ", Output
else:
echo "Error: ", status.error</
=={{header|OCaml}}==
Line 1,463 ⟶ 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]
<
List.filter ((<>) rem) from
Line 1,563 ⟶ 1,717:
done;
done;
(res)</
=={{header|Perl}}==
<
use warnings;
Line 1,574 ⟶ 1,728:
$img->read(file => 'frog.png');
my $img16 = $img->to_paletted({ max_colors => 16});
$img16->write(file => "frog-16.png")</
Compare offsite images: [https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/frog.png frog.png] vs.
[https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/frog-16.png frog-16.png]
Line 1,582 ⟶ 1,736:
{{trans|Tcl}}
Gui app, shows original and modified side-by-side.
<
include pGUI.e
Line 1,677 ⟶ 1,831:
IupMainLoop()
IupClose()</
=={{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">
; ColorQuantization.pb
Line 1,905 ⟶ 2,059:
</syntaxhighlight>
=={{header|Python}}==
<
if __name__=="__main__":
im = Image.open("frog.png")
im2 = im.quantize(16)
im2.show()</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket/base
(require racket/class
Line 2,243 ⟶ 2,397:
r g b))
(loop child (add1 level))))))
</syntaxhighlight>
=={{header|Raku}}==
Line 2,249 ⟶ 2,403:
{{works with|Rakudo|2018.10}}
<syntaxhighlight lang="raku"
use MagickWand::Enums;
Line 2,255 ⟶ 2,409:
$frog.read("./Quantum_frog.png");
$frog.quantize(16, RGBColorspace, 0, True, False);
$frog.write('./Quantum-frog-16-perl6.png');</
See: [https://github.com/thundergnat/rc/blob/master/img/Quantum-frog-16-perl6.png Quantum-frog-16-perl6.png] (offsite .png image)
=={{header|Sidef}}==
<
func quantize_image(n = 16, input, output='output.png') {
Line 2,268 ⟶ 2,422:
}
quantize_image(input: 'Quantum_frog.png')</
=={{header|Tcl}}==
{{trans|OCaml}}
{{libheader|Tk}}
<
package require Tk
Line 2,350 ⟶ 2,504:
}
return $newimg
}</
Demonstration code:
<
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</
=={{header|Wren}}==
Line 2,363 ⟶ 2,517:
{{libheader|Wren-dynamic}}
{{libheader|Wren-sort}}
<
import "graphics" for Canvas, Color, ImageData
import "./dynamic" for Struct
Line 2,375 ⟶ 2,529:
construct new(filename, filename2) {
Window.title = "Color quantization"
_image = ImageData.
_w = _image.width
_h = _image.height
Line 2,502 ⟶ 2,656:
}
var Game = ColorQuantization.new("Quantum_frog.png", "Quantum_frog_16.png")</
{{out}}
|