Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

Pillowでチェッカーボード画像を生成する

from PIL import Image, ImageDraw

# チェッカーボードの設定
cell_size = 50  # 一辺の長さ
num_cells = 10  # セルの数

# 新しい画像の作成
image_size = cell_size * num_cells
image = Image.new("L", (image_size, image_size))

# ドローイングコンテキストを作成
draw = ImageDraw.Draw(image)

# チェッカーボードの描画
for y in range(num_cells):
    for x in range(num_cells):
        if (x + y) % 2 == 0:  # x+yが偶数の場合は黒色で塗る
            draw.rectangle([x * cell_size, y * cell_size, (x + 1) * cell_size, (y + 1) * cell_size], fill=0)
        else:  # x+yが奇数の場合は白色で塗る
            draw.rectangle([x * cell_size, y * cell_size, (x + 1) * cell_size, (y + 1) * cell_size], fill=255)

# 画像の保存
image.save("chessboard.jpg")