Skip to main content
 首页 » 编程设计

python之如何改变渐变的颜色方向

2024年10月24日13落叶

下面从左边缘开始产生渐变。

#!/usr/bin/env python 
 
import math 
from PIL import Image 
 
im = Image.new('RGB', (300, 300)) 
ld = im.load() 
 
# A map of rgb points in your distribution 
# [distance, (r, g, b)] 
# distance is percentage from left edge 
heatmap = [ 
 
    [0.0, (0, 0, 0)], 
    [1.00, (0.8, 0.0, 1.0)], 
] 
 
 
def gaussian(x, a, b, c, d=0): 
    return a * math.exp(-(x - b) ** 2 / (2 * c ** 2)) + d 
 
 
def pixel(x, width=100, map=[], spread=1): 
    width = float(width) 
    r = sum([gaussian(x, p[1][0], p[0] * width, width / (spread * len(map))) for p in map]) 
    g = sum([gaussian(x, p[1][1], p[0] * width, width / (spread * len(map))) for p in map]) 
    b = sum([gaussian(x, p[1][2], p[0] * width, width / (spread * len(map))) for p in map]) 
    return min(1.0, r), min(1.0, g), min(1.0, b) 
 
 
for x in range(im.size[0]): 
    r, g, b = pixel(x, width=300, map=heatmap) 
    r, g, b = [int(256 * v) for v in (r, g, b)] 
    for y in range(im.size[1]): 
        ld[x, y] = r, g, b 
 
im.show() 

如何改变渐变的起始位置,上面是从左到右,但如果我想从上到下怎么办?

请您参考如下方法:

只需反转像素分配中的坐标:

    ld[x, y] = r, g, b 

成为

    ld[y, x] = r, g, b