python - 使用 numpy 绘制圆形渐变

标签 python numpy gradient circular-dependency radial

我有一个用 numpy 绘制径向渐变的代码。到目前为止它看起来像这样:

import numpy as np
import matplotlib.pyplot as plt

arr = np.zeros((256,256,3), dtype=np.uint8)
imgsize = arr.shape[:2]
innerColor = (0, 0, 0)
outerColor = (255, 255, 255)
for y in range(imgsize[1]):
    for x in range(imgsize[0]):
        #Find the distance to the center
        distanceToCenter = np.sqrt((x - imgsize[0]//2) ** 2 + (y - imgsize[1]//2) ** 2)

        #Make it on a scale from 0 to 1innerColor
        distanceToCenter = distanceToCenter / (np.sqrt(2) * imgsize[0]/2)

        #Calculate r, g, and b values
        r = outerColor[0] * distanceToCenter + innerColor[0] * (1 - distanceToCenter)
        g = outerColor[1] * distanceToCenter + innerColor[1] * (1 - distanceToCenter)
        b = outerColor[2] * distanceToCenter + innerColor[2] * (1 - distanceToCenter)
        # print r, g, b
        arr[y, x] = (int(r), int(g), int(b))

plt.imshow(arr, cmap='gray')
plt.show()

有没有办法用numpy函数优化这段代码并提高速度? 之后应该是这样的: Circular gradient

最佳答案

您可以使用矢量化非常有效地计算距离,而无需 for 循环:

x_axis = np.linspace(-1, 1, 256)[:, None]
y_axis = np.linspace(-1, 1, 256)[None, :]

arr = np.sqrt(x_axis ** 2 + y_axis ** 2)

或者你可以使用网格:

x_axis = np.linspace(-1, 1, 256)
y_axis = np.linspace(-1, 1, 256)

xx, yy = np.meshgrid(x_axis, y_axis)
arr = np.sqrt(xx ** 2 + yy ** 2)

并再次使用广播在innerouter 颜色之间进行插值

inner = np.array([0, 0, 0])[None, None, :]
outer = np.array([1, 1, 1])[None, None, :]

arr /= arr.max()
arr = arr[:, :, None]
arr = arr * outer + (1 - arr) * inner

关于python - 使用 numpy 绘制圆形渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55159007/

相关文章:

python - r'\' 不应该是 python 中的有效字符串值吗?

html - 我可以用 css3 和 html5 得到它吗? (渐变背景、边框渐变、透明度)

python - 使用带有特征矩阵的 scikit_learn 的奇怪卡方结果

javascript - 使用 KineticJS 绘制有根树

python - 如何刷新存储的 Google oAuth 凭据

Delphi:GDI+ 和渐变框架/矩形的问题

qt - 具有方向的QML渐变

python - 无法在 Python 中加载以前转储的大型 pickle 文件

python - 从 pandas Python 和 Numpy 将 3D 数组转换为 2d 数组

python - 如何加速嵌套循环?