在 PIL 中创建棋盘

New*_*101 2 python python-imaging-library

背景

我一直在尝试在 PIL 模块中创建一个棋盘,并且我已经获得了前两行的一般模式,但无法弄清楚如何将其应用于整个棋盘。如您所见,我创建了一个图像:

from PIL import Image

img = Image.new("RGB", (15,15), "white") # create a new 15x15 image
pixels = img.load() # create the pixel map
Run Code Online (Sandbox Code Playgroud)

我对前两行的解决方案

注意 - 我仍在学习 Python,所以这段代码可能看起来效率很低,但请随时提出改进建议。

第二行:

代码:

black_2 = []
for i in range(img.size[0]):
    if i % 2 == 0:
        black_2.append(i)
Run Code Online (Sandbox Code Playgroud)

这为我提供了放置黑色像素的所有水平索引位置。因此,对于我创建的 15x15 板,它返回[0, 2, 4, 6, 8, 10, 12, 14]

第一行:

代码:

然后我使用第二行来计算第一行的水平索引位置

black_1 = [i-1 for i in black_2 if i > 0]
if img.size[0] % 2 == 0: # 'that' if statement
    black_1.append(img.size[0]-1)
Run Code Online (Sandbox Code Playgroud)

对于我创建的 15x15 像素板,它返回[1, 3, 5, 7, 9, 11, 13]. 我创建了 if 语句,因为我意识到最后一个黑色像素没有显示板的长度是否均匀,而这似乎解决了它。

将像素更改为黑色:

# hardcoded to check patterns
for i in black_1:
    pixels[i,0] = (0,0,0)

for k in black_2:
    pixels[k,1] = (0,0,0)

img.show()
Run Code Online (Sandbox Code Playgroud)

无论大小如何,如何将这两种模式应用于电路板的其余部分?

我怀疑for var in range()需要一个循环,但我不确定它会如何根据img.size[1]板的高度()是奇数还是偶数而改变。

到目前为止的总体模式:

棋盘

black_1 适用于第一行

black_2 适用于第二行

She*_*ore 5

A chess board has 64 squares instead of 256. Firstly you need (8,8) and then you can use double for loops to assign the color to all the 8 rows.

任何尺寸的一般示例

from PIL import Image

size = 16
img = Image.new("RGB", (size,size), "white") # create a new 15x15 image
pixels = img.load() # create the pixel map

black_2 = []
for i in range(img.size[0]):
    if i % 2 == 0:
        black_2.append(i)

black_1 = [i-1 for i in black_2 if i > 0]
if img.size[0] % 2 == 0: # 'that' if statement
    black_1.append(img.size[0]-1)


for i in black_1:
    for j in range(0, size, 2):
        pixels[i,j] = (0,0,0)

for k in black_2:
    for l in range(1, size+1, 2):
        pixels[k,l] = (0,0,0)

img.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Mar*_*ell 5

这是一个简单的方法。如果您感到困惑,图像中的一个像素对应于棋盘的整个正方形,如果您愿意,您可以在最后将其放大。

#!/usr/bin/env python3

from PIL import Image

# Create new black image of entire board
w, h = 12, 6
img = Image.new("RGB", (w,h))
pixels = img.load()

# Make pixels white where (row+col) is odd
for i in range(w):
    for j in range(h):
        if (i+j)%2:
            pixels[i,j] = (255,255,255)

img.save('result.png')
Run Code Online (Sandbox Code Playgroud)

如果你想要更大的图像,只需在最后调整大小即可。因此,假设您希望板的每个方块为 15px x 15px:

img = img.resize((15*w,15*h), Image.NEAREST)
Run Code Online (Sandbox Code Playgroud)

代码生成的棋盘

  • 优雅的解决方案 (2认同)