我制作了一个小脚本,使用python创建渐变,并将其保存为图像.以下是代码:

from PIL import Image, ImageDraw

# Define the image size and color gradient
width, height = 500, 500
color_start = (255, 0, 0)  # red
color_end = (0, 0, 255)  # blue

# Create a new image with the given size
image = Image.new("RGB", (width, height))

# Draw a gradient background on the image
draw = ImageDraw.Draw(image)
for y in range(height):
    color = tuple(int(color_start[j] + (color_end[j] - color_start[j]) * y) for j in range(3))
    draw.line((0, y, width, y), fill=color)

# Save the image to a PNG file
image.save("gradient.png")

然而,我没有渐变,而是有一个纯色(蓝色)和一条红色的小线在顶部.有什么办法可以解决这个问题吗?

推荐答案

与绘制数百条线相比,您可能会发现使用内置的linear_gradient()函数会更直观,该函数为您提供256x256的线性渐变:

from PIL import Image

# Generate Red, Green and Blue bands individually
G = Image.new('L', (256,256))       # 256x256, black, i.e. 0
B = Image.linear_gradient('L')      # 256x256, black at top, white at bottom
R = B.rotate(180)                   # 256x256, white at top, black at bottom

# Merge and resize
grad = Image.merge("RGB",(R,G,B)).resize((512,512))

enter image description here

Python相关问答推荐

使用mySQL的SQlalchemy过滤重叠时间段

即使在可见的情况下也不相互作用

如何在箱形图中添加绘制线的传奇?

当使用keras.utils.Image_dataset_from_directory仅加载测试数据集时,结果不同

从收件箱中的列中删除html格式

什么相当于pytorch中的numpy累积ufunc

根据二元组列表在pandas中创建新列

Pre—Commit MyPy无法禁用非错误消息

优化器的运行顺序影响PyTorch中的预测

NumPy中条件嵌套for循环的向量化

lityter不让我输入左边的方括号,'

AES—256—CBC加密在Python和PHP中返回不同的结果,HELPPP

从列表中获取n个元素,其中list [i][0]== value''

OpenCV轮廓.很难找到给定图像的所需轮廓

如何使用matplotlib查看并列直方图

解决Geopandas和Altair中的正图和投影问题

我什么时候应该使用帆布和标签?

使用np.fft.fft2和cv2.dft重现相位谱.为什么结果并不相似呢?

Pythonquests.get(Url)返回Colab中的空内容

类型对象';敌人';没有属性';损害';