% Bayer dithering implementation by Marcelo Jo
%
%   http://marcelojo.org/marcelojoeng/2013/02/image-dithering-octave.html

function [image] = bayer(N, img)

bayer4 = [0 8 2 10; 12 4 14 6; 3 11 1 9; 15 7 13 5];
bayer8 = [1 49 13 61 4 52 16 64; 33 17 45 29 36 20 48 32; 9 57 5 53 12 60 8 56; 41 25 37 21 44 28 40 24;
	  3 51 15 63 2 50 14 62; 35 19 47 31 34 18 46 30; 11 59 7 55 10 58 6 54; 43 27 39 23 42 26 38 22];

if N == 4 
  bayer_matrix = bayer4;
else
  bayer_matrix = bayer8;
end

img_size = size(img);
x_max = img_size(1);
y_max = img_size(2);

for x = 1:x_max,
  for y = 1:y_max,
      if (img(x,y) + bayer_matrix(mod(x,N) + 1, mod(y,N) + 1)) > 128
        image_bayer(x,y) = 255;
      else
        image_bayer(x,y) = 0;
      end
  end
end

image = double(image_bayer);
end