Browse Source

*Almost* translated quantizer.

Former-commit-id: c8c139fe7e6cecd77978de44d85287d1658a2828
Former-commit-id: b32ac3200f0943841750e7b4e7d8edb167478a63
Former-commit-id: e5ae0846f3316b14fa3909fc05c3c71d8b3adb67
pull/17/head
James South 11 years ago
parent
commit
d1a69bb3cc
  1. 2
      src/ImageProcessor/Formats/Gif/GifEncoder.cs
  2. 4
      src/ImageProcessor/Formats/Gif/Quantizer/IQuantizer.cs
  3. 493
      src/ImageProcessor/Formats/Gif/Quantizer/OctreeQuantizer.cs
  4. 95
      src/ImageProcessor/Formats/Gif/Quantizer/Quantizer.cs
  5. 8
      src/ImageProcessor/Formats/Jpg/JpegEncoder.cs
  6. 8
      src/ImageProcessor/Formats/Jpg/LibJpeg/BitStream.cs

2
src/ImageProcessor/Formats/Gif/GifEncoder.cs

@ -85,7 +85,7 @@ namespace ImageProcessor.Formats
this.WriteShort(stream, descriptor.Width);
int size = descriptor.GlobalColorTableSize;
int bitdepth = this.GetBitsNeededForColorDepth(size) - 1;
int packed = 0x80 | // 1 : global color table flag = 1 (GCT used)
int packed = 0x80 | // 1 : Global color table flag = 1 (GCT used)
0x70 | // 2-4 : color resolution
0x00 | // 5 : GCT sort flag = 0
bitdepth; // 6-8 : GCT size assume 1:1

4
src/ImageProcessor/Formats/Gif/Quantizer/IQuantizer.cs

@ -18,10 +18,10 @@ namespace ImageProcessor.Formats
/// <summary>
/// Quantize an image and return the resulting output pixels.
/// </summary>
/// <param name="image">The image to quantize.</param>
/// <param name="imageBase">The image to quantize.</param>
/// <returns>
/// A <see cref="T:byte[]"/> representing a quantized version of the image pixels.
/// </returns>
byte[] Quantize(ImageBase image);
byte[] Quantize(ImageBase imageBase);
}
}

493
src/ImageProcessor/Formats/Gif/Quantizer/OctreeQuantizer.cs

@ -11,12 +11,20 @@
namespace ImageProcessor.Formats
{
using System;
using System.Collections.Generic;
/// <summary>
/// Encapsulates methods to calculate the color palette of an image using an Octree pattern.
/// Encapsulates methods to calculate the colour palette if an image using an Octree pattern.
/// <see href="http://msdn.microsoft.com/en-us/library/aa479306.aspx"/>
/// </summary>
public class OctreeQuantizer : Quantizer
{
/// <summary>
/// Stores the tree
/// </summary>
private readonly Octree octree;
/// <summary>
/// Maximum allowed color depth
/// </summary>
@ -50,6 +58,489 @@ namespace ImageProcessor.Formats
: base(false)
{
Guard.LessEquals(maxColors, 255, "maxColors");
Guard.BetweenEquals(maxColorBits, 1, 8, "maxColorBits");
// Construct the Octree
this.octree = new Octree(maxColorBits);
this.maxColors = maxColors;
}
/// <summary>
/// Process the pixel in the first pass of the algorithm
/// </summary>
/// <param name="pixel">
/// The pixel to quantize
/// </param>
/// <remarks>
/// This function need only be overridden if your quantize algorithm needs two passes,
/// such as an Octree quantizer.
/// </remarks>
protected override void InitialQuantizePixel(Bgra pixel)
{
// Add the color to the Octree
this.octree.AddColor(pixel);
}
/// <summary>
/// Override this to process the pixel in the second pass of the algorithm
/// </summary>
/// <param name="pixel">
/// The pixel to quantize
/// </param>
/// <returns>
/// The quantized value
/// </returns>
protected override byte QuantizePixel(Bgra pixel)
{
// The color at [maxColors] is set to transparent
byte paletteIndex = (byte)this.maxColors;
// Get the palette index if this non-transparent
if (pixel.A > 0)
{
paletteIndex = (byte)this.octree.GetPaletteIndex(pixel);
}
return paletteIndex;
}
/// <summary>
/// Retrieve the palette for the quantized image.
/// </summary>
/// <returns>
/// The new color palette
/// </returns>
protected override List<Bgra> GetPalette()
{
// First off convert the Octree to maxColors colors
List<Bgra> palette = this.octree.Palletize(this.maxColors - 1);
// Add empty color for transparency
palette.Add(Bgra.Empty);
return palette;
}
/// <summary>
/// Class which does the actual quantization
/// </summary>
private class Octree
{
/// <summary>
/// Mask used when getting the appropriate pixels for a given node
/// </summary>
private static readonly int[] Mask = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
/// <summary>
/// The root of the Octree
/// </summary>
private readonly OctreeNode root;
/// <summary>
/// Array of reducible nodes
/// </summary>
private readonly OctreeNode[] reducibleNodes;
/// <summary>
/// Maximum number of significant bits in the image
/// </summary>
private readonly int maxColorBits;
/// <summary>
/// Number of leaves in the tree
/// </summary>
private int leafCount;
/// <summary>
/// Store the last node quantized
/// </summary>
private OctreeNode previousNode;
/// <summary>
/// Cache the previous color quantized
/// </summary>
private int previousColor;
/// <summary>
/// Initializes a new instance of the <see cref="Octree"/> class.
/// </summary>
/// <param name="maxColorBits">
/// The maximum number of significant bits in the image
/// </param>
public Octree(int maxColorBits)
{
this.maxColorBits = maxColorBits;
this.leafCount = 0;
this.reducibleNodes = new OctreeNode[9];
this.root = new OctreeNode(0, this.maxColorBits, this);
this.previousColor = 0;
this.previousNode = null;
}
/// <summary>
/// Gets or sets the number of leaves in the tree
/// </summary>
private int Leaves
{
get { return this.leafCount; }
set { this.leafCount = value; }
}
/// <summary>
/// Gets the array of reducible nodes
/// </summary>
private OctreeNode[] ReducibleNodes => this.reducibleNodes;
/// <summary>
/// Add a given color value to the Octree
/// </summary>
/// <param name="pixel">
/// The <see cref="Bgra"/>containing color information to add.
/// </param>
public void AddColor(Bgra pixel)
{
// Check if this request is for the same color as the last
if (this.previousColor == pixel.BGRA)
{
// If so, check if I have a previous node setup. This will only occur if the first color in the image
// happens to be black, with an alpha component of zero.
if (null == this.previousNode)
{
this.previousColor = pixel.BGRA;
this.root.AddColor(pixel, this.maxColorBits, 0, this);
}
else
{
// Just update the previous node
this.previousNode.Increment(pixel);
}
}
else
{
this.previousColor = pixel.BGRA;
this.root.AddColor(pixel, this.maxColorBits, 0, this);
}
}
/// <summary>
/// Convert the nodes in the Octree to a palette with a maximum of colorCount colors
/// </summary>
/// <param name="colorCount">
/// The maximum number of colors
/// </param>
/// <returns>
/// An <see cref="List{Bgra}"/> with the palletized colors
/// </returns>
public List<Bgra> Palletize(int colorCount)
{
while (this.Leaves > colorCount)
{
this.Reduce();
}
// Now palletize the nodes
List<Bgra> palette = new List<Bgra>(this.Leaves);
int paletteIndex = 0;
this.root.ConstructPalette(palette, ref paletteIndex);
// And return the palette
return palette;
}
/// <summary>
/// Get the palette index for the passed color
/// </summary>
/// <param name="pixel">
/// The <see cref="Bgra"/> containing the pixel data.
/// </param>
/// <returns>
/// The index of the given structure.
/// </returns>
public int GetPaletteIndex(Bgra pixel)
{
return this.root.GetPaletteIndex(pixel, 0);
}
/// <summary>
/// Keep track of the previous node that was quantized
/// </summary>
/// <param name="node">
/// The node last quantized
/// </param>
protected void TrackPrevious(OctreeNode node)
{
this.previousNode = node;
}
/// <summary>
/// Reduce the depth of the tree
/// </summary>
private void Reduce()
{
// Find the deepest level containing at least one reducible node
int index = this.maxColorBits - 1;
while ((index > 0) && (null == this.reducibleNodes[index]))
{
index--;
}
// Reduce the node most recently added to the list at level 'index'
OctreeNode node = this.reducibleNodes[index];
this.reducibleNodes[index] = node.NextReducible;
// Decrement the leaf count after reducing the node
this.leafCount -= node.Reduce();
// And just in case I've reduced the last color to be added, and the next color to
// be added is the same, invalidate the previousNode...
this.previousNode = null;
}
/// <summary>
/// Class which encapsulates each node in the tree
/// </summary>
protected class OctreeNode
{
/// <summary>
/// Pointers to any child nodes
/// </summary>
private readonly OctreeNode[] children;
/// <summary>
/// Flag indicating that this is a leaf node
/// </summary>
private bool leaf;
/// <summary>
/// Number of pixels in this node
/// </summary>
private int pixelCount;
/// <summary>
/// Red component
/// </summary>
private int red;
/// <summary>
/// Green Component
/// </summary>
private int green;
/// <summary>
/// Blue component
/// </summary>
private int blue;
/// <summary>
/// The index of this node in the palette
/// </summary>
private int paletteIndex;
/// <summary>
/// Initializes a new instance of the <see cref="OctreeNode"/> class.
/// </summary>
/// <param name="level">
/// The level in the tree = 0 - 7
/// </param>
/// <param name="colorBits">
/// The number of significant color bits in the image
/// </param>
/// <param name="octree">
/// The tree to which this node belongs
/// </param>
public OctreeNode(int level, int colorBits, Octree octree)
{
// Construct the new node
this.leaf = level == colorBits;
this.red = this.green = this.blue = 0;
this.pixelCount = 0;
// If a leaf, increment the leaf count
if (this.leaf)
{
octree.Leaves++;
this.NextReducible = null;
this.children = null;
}
else
{
// Otherwise add this to the reducible nodes
this.NextReducible = octree.ReducibleNodes[level];
octree.ReducibleNodes[level] = this;
this.children = new OctreeNode[8];
}
}
/// <summary>
/// Gets the next reducible node
/// </summary>
public OctreeNode NextReducible { get; }
/// <summary>
/// Add a color into the tree
/// </summary>
/// <param name="pixel">
/// The color
/// </param>
/// <param name="colorBits">
/// The number of significant color bits
/// </param>
/// <param name="level">
/// The level in the tree
/// </param>
/// <param name="octree">
/// The tree to which this node belongs
/// </param>
public void AddColor(Bgra pixel, int colorBits, int level, Octree octree)
{
// Update the color information if this is a leaf
if (this.leaf)
{
this.Increment(pixel);
// Setup the previous node
octree.TrackPrevious(this);
}
else
{
// Go to the next level down in the tree
int shift = 7 - level;
int index = ((pixel.R & Mask[level]) >> (shift - 2)) |
((pixel.G & Mask[level]) >> (shift - 1)) |
((pixel.B & Mask[level]) >> shift);
OctreeNode child = this.children[index];
if (null == child)
{
// Create a new child node & store in the array
child = new OctreeNode(level + 1, colorBits, octree);
this.children[index] = child;
}
// Add the color to the child node
child.AddColor(pixel, colorBits, level + 1, octree);
}
}
/// <summary>
/// Reduce this node by removing all of its children
/// </summary>
/// <returns>The number of leaves removed</returns>
public int Reduce()
{
this.red = this.green = this.blue = 0;
int childNodes = 0;
// Loop through all children and add their information to this node
for (int index = 0; index < 8; index++)
{
if (null != this.children[index])
{
this.red += this.children[index].red;
this.green += this.children[index].green;
this.blue += this.children[index].blue;
this.pixelCount += this.children[index].pixelCount;
++childNodes;
this.children[index] = null;
}
}
// Now change this to a leaf node
this.leaf = true;
// Return the number of nodes to decrement the leaf count by
return childNodes - 1;
}
/// <summary>
/// Traverse the tree, building up the color palette
/// </summary>
/// <param name="palette">
/// The palette
/// </param>
/// <param name="index">
/// The current palette index
/// </param>
public void ConstructPalette(List<Bgra> palette, ref int index)
{
if (this.leaf)
{
// Consume the next palette index
this.paletteIndex = index++;
byte r = (byte)(this.red / this.pixelCount).Clamp(0, 255);
byte g = (byte)(this.green / this.pixelCount).Clamp(0, 255);
byte b = (byte)(this.blue / this.pixelCount).Clamp(0, 255);
// And set the color of the palette entry
palette.Add(new Bgra(b, g, r));
}
else
{
// Loop through children looking for leaves
for (int i = 0; i < 8; i++)
{
if (null != this.children[i])
{
this.children[i].ConstructPalette(palette, ref index);
}
}
}
}
/// <summary>
/// Return the palette index for the passed color
/// </summary>
/// <param name="pixel">
/// The <see cref="Bgra"/> representing the pixel.
/// </param>
/// <param name="level">
/// The level.
/// </param>
/// <returns>
/// The <see cref="int"/> representing the index of the pixel in the palette.
/// </returns>
public int GetPaletteIndex(Bgra pixel, int level)
{
int index = this.paletteIndex;
if (!this.leaf)
{
int shift = 7 - level;
int pixelIndex = ((pixel.R & Mask[level]) >> (shift - 2)) |
((pixel.G & Mask[level]) >> (shift - 1)) |
((pixel.B & Mask[level]) >> shift);
if (null != this.children[pixelIndex])
{
index = this.children[pixelIndex].GetPaletteIndex(pixel, level + 1);
}
else
{
throw new Exception("Didn't expect this!");
}
}
return index;
}
/// <summary>
/// Increment the pixel count and add to the color information
/// </summary>
/// <param name="pixel">
/// The pixel to add.
/// </param>
public void Increment(Bgra pixel)
{
this.pixelCount++;
this.red += pixel.R;
this.green += pixel.G;
this.blue += pixel.B;
}
}
}
}
}

95
src/ImageProcessor/Formats/Gif/Quantizer/Quantizer.cs

@ -10,6 +10,8 @@
namespace ImageProcessor.Formats
{
using System.Collections.Generic;
/// <summary>
/// Encapsulates methods to calculate the color palette of an image.
/// </summary>
@ -39,13 +41,102 @@ namespace ImageProcessor.Formats
/// <summary>
/// Quantize an image and return the resulting output pixels.
/// </summary>
/// <param name="image">The image to quantize.</param>
/// <param name="imageBase">The image to quantize.</param>
/// <returns>
/// A <see cref="T:byte[]"/> representing a quantized version of the image pixels.
/// </returns>
public byte[] Quantize(ImageBase image)
public byte[] Quantize(ImageBase imageBase)
{
// Get the size of the source image
int height = imageBase.Height;
int width = imageBase.Width;
ImageBase copy = new ImageFrame((ImageFrame)imageBase);
// Call the FirstPass function if not a single pass algorithm.
// For something like an Octree quantizer, this will run through
// all image pixels, build a data structure, and create a palette.
if (!this.singlePass)
{
this.FirstPass(copy, width, height);
}
throw new System.NotImplementedException();
}
/// <summary>
/// Execute the first pass through the pixels in the image
/// </summary>
/// <param name="source">The source data</param>
/// <param name="width">The width in pixels of the image.</param>
/// <param name="height">The height in pixels of the image.</param>
protected virtual void FirstPass(ImageBase source, int width, int height)
{
// Loop through each row
for (int y = 0; y < height; y++)
{
// And loop through each xumn
for (int x = 0; x < width; x++)
{
// Now I have the pixel, call the FirstPassQuantize function...
this.InitialQuantizePixel(source[x, y]);
}
}
}
/// <summary>
/// Execute a second pass through the bitmap
/// </summary>
/// <param name="source">The source image.</param>
/// <param name="output">The output pixel array</param>
/// <param name="width">The width in pixels of the image</param>
/// <param name="height">The height in pixels of the image</param>
protected virtual void SecondPass(ImageBase source, byte[] output, int width, int height)
{
Bgra sourcePixel = source[0, 0];
// And convert the first pixel, so that I have values going into the loop
byte pixelValue = this.QuantizePixel(sourcePixel);
output[0] = pixelValue;
for (int y = 0; y < height; y++)
{
// TODO: Translate this from the old method.
}
}
/// <summary>
/// Override this to process the pixel in the first pass of the algorithm
/// </summary>
/// <param name="pixel">
/// The pixel to quantize
/// </param>
/// <remarks>
/// This function need only be overridden if your quantize algorithm needs two passes,
/// such as an Octree quantizer.
/// </remarks>
protected virtual void InitialQuantizePixel(Bgra pixel)
{
}
/// <summary>
/// Override this to process the pixel in the second pass of the algorithm
/// </summary>
/// <param name="pixel">
/// The pixel to quantize
/// </param>
/// <returns>
/// The quantized value
/// </returns>
protected abstract byte QuantizePixel(Bgra pixel);
/// <summary>
/// Retrieve the palette for the quantized image
/// </summary>
/// <returns>
/// The new color palette
/// </returns>
protected abstract List<Bgra> GetPalette();
}
}

8
src/ImageProcessor/Formats/Jpg/JpegEncoder.cs

@ -87,8 +87,8 @@ namespace ImageProcessor.Formats
Guard.NotNull(image, "image");
Guard.NotNull(stream, "stream");
int pixelWidth = image.PixelWidth;
int pixelHeight = image.PixelHeight;
int pixelWidth = image.Width;
int pixelHeight = image.Height;
byte[] sourcePixels = image.Pixels;
@ -101,7 +101,7 @@ namespace ImageProcessor.Formats
for (int x = 0; x < pixelWidth; x++)
{
int start = x * 3;
int source = (y * pixelWidth + x) * 4;
int source = ((y * pixelWidth) + x) * 4;
samples[start] = sourcePixels[source + 2];
samples[start + 1] = sourcePixels[source + 1];
@ -112,7 +112,7 @@ namespace ImageProcessor.Formats
}
JpegImage jpg = new JpegImage(rows, Colorspace.RGB);
jpg.WriteJpeg(stream, new CompressionParameters { Quality = Quality });
jpg.WriteJpeg(stream, new CompressionParameters { Quality = this.Quality });
}
#endregion

8
src/ImageProcessor/Formats/Jpg/LibJpeg/BitStream.cs

@ -91,13 +91,7 @@ namespace ImageProcessor.Formats
/// <summary>
/// Gets the underlying stream.
/// </summary>
public Stream UnderlyingStream
{
get
{
return this.stream;
}
}
public Stream UnderlyingStream => this.stream;
/// <summary>
/// Disposes the object and frees resources for the Garbage Collector.

Loading…
Cancel
Save