Tuesday, August 23, 2011

Drawing a chessboard with IJ script

Drawing a chessboard is a good exercise because you need all the basic tools of programming language: loops and conditional statement.



2- Algorithm

As shown in Fig.1, a chessboard is a square containing 8x8 = 64 cells colored in  white or black.
In our algorithm, the different cells are numbered by their X-Y coordinates from 0 to 7 (Fig. 1). Thus, the upper left corner is (0,0) and the lower right is (7,7).

Fig.1: Chessboard with the XY coordinates of the cells

What about the cell color?  If you sum the x- and y-coordinates of a cell and if this sum is even then the color is white ... otherwise it is black. Ex: The cell (3,4) is black because 3+4 = 7 which is odd, similarly, cell (7,5) is white (7+5=12, an even number).


3- Script: version 1.0

First, don't type all the code, open the Recorder and create a 512x512 8-bit image with a black background, then click on 'Create' ... and let's go.
Second, we need two loops: a loop to scan the X-coordinate and another one for the Y-coordinates. They are nested (the X-loop is inside the Y-loop).

Third, to draw the cells: 
  1. The drawing function is fillRect(x,y,w,h)
  2. The width and height are equal to 512/8 = 64 pixels
  3. The tricky part is the assignment of the X-Y coordinates of each cell, because they depend of the cell size.
Fourth, to assign the good color, we have to check the parity (even or odd) of the X-Y coords sum. This is done by looking at the remainder after a division by 2. If this remainder is equal to zero, the sum is even, otherwise it's odd. In ImageJ, this operator (modulo) is the percent sign ('%').

+++ IJ snippet: chessboard_v1_imagej.ijm +++

+++ End of IJ snippet +++

4- Conclusion

Of course, there are many different ways to write a script even for a simple task like drawing a chessboard (see Parts 2 and 3).
If you find a shorter, smarter way to draw a chessboard in ImageJ, you are welcome to share your code.


No comments:

Post a Comment