Skip to content

Instantly share code, notes, and snippets.

@JimBobSquarePants
Created February 1, 2018 00:37
Show Gist options
  • Save JimBobSquarePants/fdec46b22a13af3e6cda336629959347 to your computer and use it in GitHub Desktop.
Save JimBobSquarePants/fdec46b22a13af3e6cda336629959347 to your computer and use it in GitHub Desktop.
Algorithm for generating Bayer Matrices of arbitrary dimensions. See https://en.wikipedia.org/wiki/Ordered_dithering
void Main()
{
// Compute the Bayer matrix for the given order.
// 2^1 = 2x2 matrice
// 2^2 = 4x4 matrice
// 2^3 = 8x8 matrice
ComputeBayer(1);
ComputeBayer(2);
ComputeBayer(3);
}
private uint Bayer(uint x, uint y, uint order)
{
uint res = 0;
for (uint i = 0; i < order; ++i)
{
uint xOdd_XOR_yOdd = (x & 1) ^ (y & 1);
uint xOdd = x & 1;
res = ((res << 1 | xOdd_XOR_yOdd) << 1) | xOdd;
x >>= 1;
y >>= 1;
}
return res;
}
private void ComputeBayer(uint order)
{
uint dim = (uint)(1 << (int)order);
uint[,] m = new uint[dim, dim];
uint i = 0;
for (uint y = 0; y < m.GetLength(1); y++)
{
for (uint x = 0; x < m.GetLength(0); x++)
{
m[x, y] = (Bayer(i / dim, i % dim, order));
i++;
}
}
Console.Write(m);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment