You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Pillow库绘制条纹?

简化实现方案

这里提供两种可行的优化思路,你可以根据使用场景选择:

思路1:用循环简化原有逻辑

你原有代码重复调用draw.line冗余度很高,直接把条纹参数抽离用循环生成即可,调整参数也更方便:

from PIL import Image, ImageDraw

# 可自定义参数
img_size = (100, 100)
bg_color = (255,255,255)
stripe_color = (0,0,0)
stripe_width = 10
stripe_gap = 10  # 两条条纹之间的空白宽度

img = Image.new('RGB', img_size, bg_color)
draw = ImageDraw.Draw(img)
# 按固定间隔生成条纹位置
for y in range(stripe_width//2, img_size[1], stripe_width + stripe_gap):
    draw.line((0, y, img_size[0], y), stripe_color, stripe_width)
img.show()

思路2:用NumPy直接生成像素矩阵(适合大尺寸图像,性能更高)

如果需要生成大尺寸的条纹图,直接操作像素数组的性能比循环绘制高很多:

import numpy as np
from PIL import Image

# 可自定义参数
img_size = (100, 100)
bg_color = [255,255,255]
stripe_color = [0,0,0]
stripe_width = 10
stripe_gap = 10

# 初始化全背景色数组
arr = np.full((img_size[1], img_size[0], 3), bg_color, dtype=np.uint8)
# 生成条纹位置掩码
period = stripe_width + stripe_gap
mask = (np.arange(img_size[1]) % period) < stripe_width
arr[mask] = stripe_color
# 转PIL图像
img = Image.fromarray(arr)
img.show()

如果需要生成竖条纹,只需要调整掩码的生成维度即可,灵活度很高。

内容的提问来源于stack exchange,提问作者project.py

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:15:04