我们如何在 Python 中生成以下灰度图像?
以下代码生成水平图案,但我需要一个倾斜的图案。
import numpy as np
import matplotlib.pyplot as plt
N = 256
x = np.linspace(-np.pi,np.pi, N)
sine1D = 128.0 + (127.0 * np.sin(x * 8.0))
sine1D = np.uint8(sine1D)
sine2D = np.tile(sine1D, (N,1))
print(sine2D.shape)
plt.imshow(sine2D, cmap='gray')
最佳答案
您可以使用 numpy.roll移动一维正弦数据:
import numpy as np
import matplotlib.pyplot as plt
N = 256
x = np.linspace(-np.pi,np.pi, N)
sine1D = 128.0 + (127.0 * np.sin(x * 8.0))
sine1D = np.uint8(sine1D)
sine2D = np.ndarray((N,N), dtype=np.uint8)
for i in range(N):
sine2D[i]= np.roll(sine1D,-i) # shift the 1D sin data by -i, -i increases with rows
plt.imshow(sine2D, cmap='gray')
plt.show()
输出:
如果滚动一维数据,您将获得所需的倾斜图案。如果你想要一个特殊的倾斜角度,你必须滚动更多/更少然后每前进行 1 以使其更平坦/更陡峭。
文档:
关于python - 生成倾斜正弦波的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57534808/