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:
JavaScript
x
19
19
1
from PIL import Image, ImageDraw
2
3
h = 500
4
w = 500
5
img = Image.new("RGB", (h,w), (255, 0, 0)) # create a new 15x15 image
6
pixels = img.load() # create the pixel map
7
print("1")
8
9
for i in range (h):
10
for j in range(w):
11
if ((i + j)%2) != 0:
12
im = Image.new('RGB', (h//5, w//5), 'black')
13
else:
14
draw = ImageDraw.Draw(img, "RGBA")
15
draw.rectangle(((h//5, w//5), (i+.5, j+.5)), fill="blue")
16
17
print ("done")
18
img.show()
19
Advertisement
Answer
I know it’s already been answered, here’s a way to loop over it differently
JavaScript
1
39
39
1
from PIL import Image
2
3
h = 500
4
w = 500
5
6
# You can also easily set the number of squares per row
7
number_of_square_across = 10
8
9
# You can also easily set the colors
10
color_one = (0, 0, 0)
11
color_two = (0, 0, 255)
12
13
length_of_square = h/number_of_square_across
14
length_of_two_squares = h/number_of_square_across*2
15
16
img = Image.new("RGB", (h, w), (255, 0, 0)) # create a new 15x15 image
17
pixels = img.load() # create the pixel map
18
19
for i in range(h):
20
# for every 100 pixels out of the total 500
21
# if its the first 50 pixels
22
if (i % length_of_two_squares) >= length_of_square:
23
for j in range(w):
24
if (j % length_of_two_squares) < length_of_square:
25
pixels[i,j] = color_one
26
else:
27
pixels[i,j] = color_two
28
29
# else its the second 50 pixels
30
else:
31
for j in range(w):
32
if (j % length_of_two_squares) >= length_of_square:
33
pixels[i,j] = color_one
34
else:
35
pixels[i,j] = color_two
36
37
print("done")
38
img.show()
39