Skip to content

Instantly share code, notes, and snippets.

@gizmo98
Created February 17, 2020 18:18
Show Gist options
  • Save gizmo98/e64064d41ae2344487b4907f6cf36ed5 to your computer and use it in GitHub Desktop.
Save gizmo98/e64064d41ae2344487b4907f6cf36ed5 to your computer and use it in GitHub Desktop.
CSharp dithering example
private void BayerDithering32to16(ref BGRAPixelArray ba)
{
int[,] matrix = new int[4, 4] {
{0,8,2,10},
{12,4,14,6},
{3,11,1,9},
{15,7,13,5}
};
double[,] rbMatrix = new double[4, 4];
double[,] gMatrix = new double[4, 4];
double rbSpread = 255.0 / (Math.Pow(2, 5) - 1);
double gSpread = 255.0 / (Math.Pow(2, 6) - 1);
// Precalculate rb an g matrix values
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 4; i++)
{
double threshold = (matrix[i, j] / 16.0 - 0.5);
rbMatrix[i, j] = threshold * rbSpread;
gMatrix[i, j] = threshold * gSpread;
}
}
for (int y = 0; y < ba.height; y++)
{
for (int x = 0; x < ba.width; x++)
{
byte r, g, b;
// Dither
r = (byte)Math.Max(Math.Min(ba.GetR(x, y) + rbMatrix[x % 4, y % 4], 255.0), 0.0);
g = (byte)Math.Max(Math.Min(ba.GetG(x, y) + gMatrix[x % 4, y % 4], 255.0), 0.0);
b = (byte)Math.Max(Math.Min(ba.GetB(x, y) + rbMatrix[x % 4, y % 4], 255.0), 0.0);
// Quantize
r = (byte)(r >> 3);
g = (byte)(g >> 2);
b = (byte)(b >> 3);
// RGB16 color
byte color = (byte)(r << 11 + g << 5 + b);
// write rgb16 value col to 16Bit buffer
// ....
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment