Fast pairwise nearest neighbor based algorithm with C# console
nQuant.cs is a C# color quantizer producing high quality 256 color 8 bit PNG images using an algorithm optimized for the highest quality possible.
Another advantage of nQuant.cs is that it is a .net library that you can integrate nicely with your own C# code while many of the popular quantizers only provide command line implementations. nQuant.cs also provides a command line wrapper in case you want to use it from the command line.
Less artifacts by using advanced dithering techniques such as Generalized Hilbert (“gilbert”) space-filling curve and partial Blue noise distribution to diffuse the minimized quantization errors.
If you are using C#, you would call nQuant as follows:
bool dither = true;
var quantizer = new PnnQuant.PnnQuantizer();
using(var bitmap = new Bitmap(sourcePath))
{
try
{
using (var dest = quantizer.QuantizeImage(bitmap, pixelFormat, maxColors, dither))
{
dest.Save(targetPath, ImageFormat.Png);
System.Console.WriteLine("Converted image: " + Path.GetFullPath(targetPath));
}
}
catch (Exception q)
{
System.Console.WriteLine(q.StackTrace);
}
}
More importantly, a parallel genetic algorithm called PNNLAB+ is proposed for converting a sequence of similar images under the same palette.
var alg = new APNsgaIII<PnnLABGAQuantizer>(new PnnLABGAQuantizer(new PnnLABQuantizer(), bitmaps, maxColors));
alg.Run(999, -Double.Epsilon);
using (var pGAq = alg.Result) {
System.Console.WriteLine("\n" + pGAq.Result);
var imgs = pGAq.QuantizeImage(dither);
for (int i = 0; i < imgs.Count; ++i) {
var fname = Path.GetFileNameWithoutExtension(paths[i]);
var destPath = Path.Combine(targetPath, fname) + " - PNNLAB+quant" + maxColors + ".png";
imgs[i].Save(destPath, ImageFormat.Png);
System.Console.WriteLine("Converted image: " + Path.GetFullPath(destPath));
}
}
OTSU method (OTSU) is a global adaptive binarization threshold image segmentation algorithm. This algorithm takes the maximum inter class variance between the background and the target image as the threshold selection rule.
var quantizer = new OtsuThreshold.Otsu();
using(var bitmap = new Bitmap(sourcePath))
{
try
{
using (var dest = quantizer.ConvertGrayScaleToBinary(bitmap))
{
dest.Save(targetPath, ImageFormat.Png);
System.Console.WriteLine("Converted black and white image: " + Path.GetFullPath(targetPath));
}
}
catch (Exception q)
{
System.Console.WriteLine(q.StackTrace);
}
}
Example image:
Resulted image:
If you are using the command line. Assuming you are in the same directory as nQuant.exe and nQuant.Master.dll, you would enter:
nQuant yourImage.jpg /o yourNewImage.png
To switch algorithms, /a otsu
can perform the above black and white conversion.
nQuant will quantize yourImage.jpg and create yourNewImage.png in the same directory.
There are a few configuration arguments you can optionaly use to try and influence how the image gets quantized. These are explained in the console application.