使用numpy生成彩色图像渐变

时间:2016-11-14 13:13:46

标签: python arrays python-2.7 numpy

我写了一个生成2个彩色图像块的函数:

def generate_block():
    x = np.ones((50, 50, 3))
    x[:,:,0:3] = np.random.uniform(0, 1, (3,))
    show_image(x)

    y = np.ones((50, 50, 3))
    y[:, :, 0:3] = np.random.uniform(0, 1, (3,))
    show_image(y)

然后我想将这两种颜色组合起来形成一个渐变,即从一种颜色到另一种颜色的1个图像。我不确定如何继续,任何建议?使用np.linspace()我可以形成一维的步骤数组,但那么呢?

2 个答案:

答案 0 :(得分:4)

这是你在找什么?

def generate_block():
    x = np.ones((50, 50, 3))
    x[:, :, 0:3] = np.random.uniform(0, 1, (3,))
    plt.imshow(x)
    plt.figure() 

    y = np.ones((50, 50, 3))
    y[:,:,0:3] = np.random.uniform(0, 1, (3,))
    plt.imshow(y)

    plt.figure()
    c = np.linspace(0, 1, 50)[:, None, None]
    gradient = x + (y - x) * c
    plt.imshow(gradient)
    return x, y, gradient

要按照您的建议使用np.linspace,我已经使用了广播,这是一个非常强大的工具;阅读更多here

c = np.linspace(0, 1, 50)创建一个形状(50,)的数组,其中包含从0到1的50个数字,均匀分布。添加[:, None, None]会使此数组3D形状为(50, 1, 1)。在(x - y) * c中使用它时,由于x - y(50, 50, 3),因此最后2个维度会进行广播。 c被视为一个数组,我们称之为形状(50, 50, 3)的d,这样对于范围(50)中的i,d[i, :, :]是一个形状(50, 3)的数组,其中填充了{{ 1}}。

所以渐变的第一行是c[i],这只是x[0, :, :] + c[0] * (x[0, :, :] - y[0, :, :]) 第二行是x[0, :, :]等。x[1, :, :] + c[1] * (x[1, :, :] - y[1, :, :])行是ix[i]的重心,系数y[i]1 - c[i]

enter image description here

您可以在c。

的定义中使用[None,:,None]进行逐列变化

答案 1 :(得分:0)

感谢卡米列里(P. Camilleri)的出色回答。 我添加了一个列式变化示例,该示例使用给定的RGB值和生成大小为(HEIGHT_LIMIT,WIDTH_LIMIT)的Image。最后,我将其转换为可以保存的图像。

WIDTH_LIMIT = 3200
HEIGHT_LIMIT = 4800
def generate_grad_image(rgb_color=(100,120,140)): # Example value
    x = np.ones((HEIGHT_LIMIT, WIDTH_LIMIT, 3)) 
    x[:, :, 0:3] = rgb_color
    y = np.ones((HEIGHT_LIMIT, WIDTH_LIMIT, 3))
    y[:,:,0:3] = [min(40 + color, 255) for color in rgb_color]
    c = np.linspace(0, 1, WIDTH_LIMIT)[None,:, None]
    gradient = x + (y - x) * c
    im = Image.fromarray(np.uint8(gradient))
    return im

示例输出: gradient example

相关问题