Monday, February 10, 2014

MATLAB Code to Generate a Chessboard



In the last 2 years, the writer attended a lecture on Linear Filters in Image Processing. Among the various assignments was to write a function which generates a chessboard/checkerboard, which then can be visualized as a conventional 2D image. This is a tutorial on how to apply a function called 'schachbrett' (the German word for chessboard) in MATLAB [1].



Why chessboard?
Figure 1: An artificially generated image of chessboard (256 x 256 pixel)

The chessboard (Figure 1) was deemed an interesting object to investigate frequencies after applying Fourier Transform. The test would looked like Figure 2 and Figure 3 below.

Figure 2: The real part of the Fourier Transform of lohSchahmat

Figure 3: The real part of the Fourier Transform of lohSchahmat (as a 3D-mesh plot)
The results would look finer if the writer had applied:
  1. a higher number of pixel and/or
  2. a higher number of fields. 

The function schachbrett()

This function takes 2 arguments - namely the no. of pixel and and the no. of fields to be displayed.

function [chessBoard] = schachbrett(noPxl,noField)

And the output is - chessBoard.

For security, the writer set default values as follows:


% Setting the default no. of pixels
if noPxl <= 0
    noPxl = 10;
end

% Dimension of the board => noField x noField
if noField <= 0
    noField = 2;
end

The here is where the magic happens:

boardTemp = 255*[ones(noPxl) zeros(noPxl); zeros(noPxl) ones(noPxl)];
chessBoard = repmat(boardTemp,noField/2,noField/2);

Firstly a 2x2 board of ones and zeros are generated, which resembles an identity matrix, except that this matrix is NOT an identity matrix. Then it is multiplied by the value of 255, so that all values of 1 become 255 (the color white in 8-bit grayscale).

Then the matrix is replicated with the help of a built-in MATLAB function called repmat() - replicated as half as the number of fields given as the argument noField in schachbrett() above.

How to apply the function schachbrett()

This step is very easy just like below, which has generated the image in Figure 1 above:


noPixel = 2^5;
noLineColumn = 2^3;
lohSchahmat = schachbrett(noPixel, noLineColumn);
figure('Name', 'BetHaMikdash'),
imshow(lohSchahmat)
title('Rosfah Schlomo')

That is all. Have fun with coding in MATLAB!

Remarks:

[1]. MATLAB is a registered trademark of The Mathworks, Inc. The code above was strictly used for academical and research purpose.

1 comment:

Unknown said...

i need the matlab programming code for this chessboard