Photoshop-style checkboard background in MATLAB

Alec Jacobson

February 10, 2014

weblog/

Here's a gnarly one-liner to produce a checkerboard image ch with the same dimensions as you image im in matlab:

ch = repmat(1-0.2*xor((mod(repmat(0:size(im,2)-1,size(im,1),1),8*2)>7),(mod(repmat((0:size(im,1)-1)',1,size(im,2)),8*2)>7)),[1 1 3]);

This is useful for alpha-compositing. So suppose you had an alpha-map A to extract the star from this colorful image im. Then you could composite the star over ch:

imshow([ ...
  ch; ...
  repmat(A,[1 1 3]); ...
  im; ...
  bsxfun(@times,ch,1-A)+bsxfun(@times,im,A)])

checkboard background matlab compositing

Update: Here's an even gnarlier anonymous function which takes an image im and an alpha map A and produces an image of the composite over the checkboard:

checker = @(im,A) bsxfun(@times,1-A,repmat(1-0.2xor((mod(repmat(0:size(im,2)-1,size(im,1),1),82)>7),(mod(repmat((0:size(im,1)-1)',1,size(im,2)),8*2)>7)),[1 1 3])) + bsxfun(@times,A,im);

Then you can quickly display your checkboard background images with:

imshow(checker(im,A))

checkboard image matlab