生活随笔
收集整理的這篇文章主要介紹了
python实现向图像随机添加高斯白噪声,并修改尺寸
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基于python向圖像隨機添加高斯噪聲,并修改尺寸
噪聲分布設置為(均值為0,方差分布在0~50之間)
"""
Created on Nov Mon 29 14:09:45 2021@author: 瀛臺夜雪
"""
import os
import numpy
as np
import cv2
import glob
def main():src_dir
='./example/'save_dir
= './example/train'src_dir_test
='./example/test'save_dir_test
= './example/test'filepaths
= glob
.glob
(save_dir
+ '/*.jpg')filepaths_test
= glob
.glob
(src_dir_test
+ '/*.jpg')def sortKeyFunc(s
):return int(os
.path
.basename
(s
)[:-4])filepaths_test
.sort
(key
=sortKeyFunc
)filepaths
.sort
(key
=sortKeyFunc
)print("[*] Reading train files...")if not os
.path
.exists
(save_dir
):os
.mkdir
(save_dir
)os
.mkdir
(save_dir_test
)os
.mkdir
('./example/train/noisy')os
.mkdir
('./example/train/original')os
.mkdir
('./example/test/noisy')os
.mkdir
('./example/test/original')print("[*] Applying noise...")sig
= np
.linspace
(0,50,len(filepaths
))np
.random
.shuffle
(sig
)sig_test
= np
.linspace
(0,50,len(filepaths_test
))np
.random
.shuffle
(sig_test
)for i
in range(len(filepaths
)):image
= cv2
.imread
(filepaths
[i
])image
= cv2
.resize
(image
,(180,180), interpolation
= cv2
.INTER_CUBIC
)row
,col
,ch
= image
.shapemean
= 0sigma
= sig
[i
]
gauss
= np
.random
.normal
(mean
,sigma
,(row
,col
,ch
))gauss
= gauss
.reshape
(row
,col
,ch
)noisy
= image
+ gauss
noisy
= np
.clip
(noisy
, 0, 255)
noisy
= noisy
.astype
('uint8')cv2
.imwrite
(os
.path
.join
(save_dir
, "noisy/%04d.png" %i
), noisy
)cv2
.imwrite
(os
.path
.join
(save_dir
, "original/%04d.png" %i
), image
)for i
in range(len(filepaths_test
)):image
= cv2
.imread
(filepaths_test
[i
])image
= cv2
.resize
(image
,(180,180), interpolation
= cv2
.INTER_CUBIC
)row
,col
,ch
= image
.shapemean
= 0sigma
= sig
[i
]gauss
= np
.random
.normal
(mean
,sigma
,(row
,col
,ch
))gauss
= gauss
.reshape
(row
,col
,ch
)noisy
= image
+ gaussnoisy
= np
.clip
(noisy
, 0, 255)noisy
= noisy
.astype
('uint8') cv2
.imwrite
(os
.path
.join
(save_dir_test
, "noisy/%d.png" %i
), noisy
)cv2
.imwrite
(os
.path
.join
(save_dir_test
, "original/%d.png" %i
), image
)print("[*] Noisy and original images saved")if __name__
== "__main__":main
()
原始圖像:
噪聲圖像:
總結
以上是生活随笔為你收集整理的python实现向图像随机添加高斯白噪声,并修改尺寸的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。