Skip to main content
 首页 » 编程设计

python之如何使用 python 在图像上生成随机正弦条纹

2025年02月15日6rubylouvre

我有一张用 python 读入的图像,我希望在此图像上添加一些不同的正弦条纹作为噪声。我希望正弦的频率和旋转度数是完全随机的。我尝试了 numpy 模块,但它可能不是我在这里需要的模型。

谁能告诉我任何 python 模块都有这样的功能来为图像添加随机正弦曲线?

结果应该有点类似于下图:

请您参考如下方法:

最后我发现我可以使用 Numpy 模块完成所有这些:

def sineimg(img, color='black', linewidth=1.5, linestyle="-"): 
''' 
frequency = X / random.uniform(10.0, 20.0) 
amplitude = randint(35, 50) 
phase = random.uniform(1.0, 16.0) 
rotation = random.uniform(-pi / 2, pi / 2) 
''' 
    #Random rotation angle 
    rot = random.randint(-90, 90) 
    x_ = img.shape[0] / np.cos(np.pi * rot / 180) 
    X = np.linspace(-1 * x_, x_, 512) 
    axes = plt.subplot(111) 
    np.cos(np.pi * rot / 180) 
    #Random amplitude 
    amp1 = random.randint(35, 50) 
    amp2 = random.randint(35, 50) 
    #Random frequency 
    frequency1 = X / random.uniform(10.0, 20.0) 
    frequency2 = X / random.uniform(10.0, 20.0) 
    #Random offset phase 
    phase1 = np.pi / random.uniform(1.0, 16.0) + np.pi / 2 
    phase2 = np.pi / random.uniform(1.0, 16.0) + np.pi / 3 
    #random distance between line cluster 
    distance = random.randint(90, 115) 
    #I need roughly 8 times of them 
    for i in range(8): 
        Y1 = amp1 * np.sin(frequency1 + phase1) - 450 + i * distance 
        Y2 = amp2 * np.sin(frequency2 + phase2) - 420 + i * distance 
        x1_trans = X * np.cos(np.pi * rot / 180) - Y1* np.sin(np.pi * rot / 180) 
        y1_trans = X * np.sin(np.pi * rot / 180) + Y1* np.cos(np.pi * rot / 180) 
        x2_trans = X * np.cos(np.pi * rot / 180) - Y2* np.sin(np.pi * rot / 180) 
        y2_trans = X * np.sin(np.pi * rot / 180) + Y2* np.cos(np.pi * rot / 180) 
        #Remove label 
        axes.set_xticks([]) 
        axes.set_yticks([]) 
        axes.spines['right'].set_color('none') 
        axes.spines['top'].set_color('none') 
        axes.spines['bottom'].set_color('none') 
        axes.spines['left'].set_color('none') 
 
        axes.plot(x1_trans, y1_trans, color = color, linewidth=linewidth, linestyle=linestyle) 
        axes.plot(x2_trans, y2_trans, color = color, linewidth=linewidth, linestyle=linestyle) 
    plt.imshow(img, zorder=0, extent=[148, -148, -225, 225]) 

他们:

img=mpimg.imread('me.jpg') 
sineimg(img) 

我得到的图片如下: