I am trying to write a code that can generate an checker board pattern. The final image size should be 100 x 100
, the checker board size 5 x 5
, such that each box has dimensions h/5
and w/5
. The code I have is wrong:
from PIL import Image, ImageDraw h = 500 w = 500 img = Image.new("RGB", (h,w), (255, 0, 0)) # create a new 15x15 image pixels = img.load() # create the pixel map print("1") for i in range (h): for j in range(w): if ((i + j)%2) != 0: im = Image.new('RGB', (h//5, w//5), 'black') else: draw = ImageDraw.Draw(img, "RGBA") draw.rectangle(((h//5, w//5), (i+.5, j+.5)), fill="blue") print ("done") img.show()
Advertisement
Answer
I know it’s already been answered, here’s a way to loop over it differently
from PIL import Image h = 500 w = 500 # You can also easily set the number of squares per row number_of_square_across = 10 # You can also easily set the colors color_one = (0, 0, 0) color_two = (0, 0, 255) length_of_square = h/number_of_square_across length_of_two_squares = h/number_of_square_across*2 img = Image.new("RGB", (h, w), (255, 0, 0)) # create a new 15x15 image pixels = img.load() # create the pixel map for i in range(h): # for every 100 pixels out of the total 500 # if its the first 50 pixels if (i % length_of_two_squares) >= length_of_square: for j in range(w): if (j % length_of_two_squares) < length_of_square: pixels[i,j] = color_one else: pixels[i,j] = color_two # else its the second 50 pixels else: for j in range(w): if (j % length_of_two_squares) >= length_of_square: pixels[i,j] = color_one else: pixels[i,j] = color_two print("done") img.show()