如何创建棋盘图案?

How do I create a checker board pattern?

我正在尝试编写可以生成棋盘图案的代码。最终图像大小应为 100 x 100,棋盘大小为 5 x 5,这样每个框的尺寸为 h/5w/5。我的代码是错误的:

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()

对于以后阅读本文并正在寻找制作棋盘的通用解决方案的任何人,请参见此处:

M, N = 10, 10
arr = [[0 for _ in range(N)] for _ in range(M)] # an M by N  array
for i in range(M):
    for j in range(N):
        if (i&1)^(j&1): # if (i is odd and j is even) or (j is odd and i is even)
            arr[i][j] = 1 # change the pixel from white to black

专为 OP 的查询量身定制的解决方案请参见此处:

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&1)^(j&1):
            pixels[i,j] = (0, 0, 0)
        else:
            pixels[i,j] = (0, 0, 255)

    
print ("done")
img.show()

# BIGGER BOX SIZE
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")

box_size = 25
for i in range (0, h, box_size):
    for j in range(0, w, box_size):
        y, x = i // box_size, j // box_size
        if (y&1)^(x&1):
            for di in range(box_size):
                for dj in range(box_size):
                    pixels[i+di,j+dj] = (0, 0, 0)
        else:
            for di in range(box_size):
                for dj in range(box_size):
                    pixels[i+di,j+dj] = (0, 0, 255)
    
print ("done")
img.show()

这将为您提供数组的棋盘格图案。

我知道已经有人回答了,这是一种以不同方式循环的方法

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()

我有一种感觉,使用所有这些嵌套循环访问 Pillow 中的单个像素并不是性能方面的最佳想法。

所以,我的想法是使用(嵌套)列表设置一个小型 (m, n) 检查器,使用 putdata, and simply resize it to the desired size using the Image.NEAREST 重采样过滤器从中构建一个 Pillow Image 对象。我增加了一些选择颜色和图像模式的灵活性。

from itertools import chain
from math import ceil
from PIL import Image

m, n = (5, 5)                                   # Checker dimension (x, y)
w, h = (100, 100)                               # Final image width and height

c1 = 0      # (224, 64, 64)                     # First color
c2 = 255    # (128, 128, 128)                   # Second color
mode = 'L' if isinstance(c1, int) else 'RGB'    # Mode from first color

# Generate pixel-wise checker, even x dimension
if m % 2 == 0:
    pixels = [[c1, c2] for i in range(int(m/2))] + \
             [[c2, c1] for i in range(int(m/2))]
    pixels = [list(chain(*pixels)) for i in range(ceil(n/2))]

# Generate pixel-wise checker, odd x dimension
else:
    pixels = [[c1, c2] for i in range(ceil(m*n/2))]

# Generate final Pillow-compatible pixel values
pixels = list(chain(*pixels))[:(m*n)]

# Generate Pillow image from pixel values, resize to final image size, and save
checker = Image.new(mode, (m, n))
checker.putdata(pixels)
checker = checker.resize((w, h), Image.NEAREST)
checker.save('checker.png')

对于显示的配置,输出将是:

切换到 RGB,并改变 mwh,我们可能会得到这样的结果:

正如其他答案中已经指出的那样,如果 wh 不是 mn 的整数因子,那么你会得到某种结果失真输出(m = n = 5w = h = 102):

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
Pillow:        8.1.2
----------------------------------------