Little_by_little_4 創建一個椒鹽噪聲的pytorch.transform
任務:
為一個圖片加上椒鹽噪聲,創造一個類實現這個功能
源代碼
class AddPepperNoise(object):
"""增加椒鹽噪聲
Args:
snr (float): Signal Noise Rate
p (float): 概率值,依概率執行該操作
"""
#1
def __init__(self, snr, p=0.9):
assert isinstance(snr, float) or (isinstance(p, float))
self.snr = snr
self.p = p
#2
def __call__(self, img):
"""
Args:
img (PIL Image): PIL Image
Returns:
PIL Image: PIL image.
"""
if random.uniform(0, 1) < self.p:#概率的判斷
img_ = np.array(img).copy()#轉化為numpy的形式
h, w, c = img_.shape#獲取圖像的高,寬,channel的數量
signal_pct = self.snr#設置圖像原像素點保存的百分比
noise_pct = (1 - self.snr)#噪聲的百分比
mask = np.random.choice((0, 1, 2), size=(h, w, 1), p=[signal_pct, noise_pct/2., noise_pct/2.])
#random.choice的用法:可以從一個int數字或1維array里隨機選取內容,並將選取結果放入n維array中返回。
#size表示要輸出的numpy的形狀
mask = np.repeat(mask, c, axis=2)#將mask在最高軸上(2軸)上復制channel次。
img_[mask == 1] = 255 # 鹽噪聲
img_[mask == 2] = 0 # 椒噪聲
return Image.fromarray(img_.astype('uint8')).convert('RGB')#轉化成pil_img的形式
else:
return img
#1 分析
def __init__(self, snr, p=0.9):
assert isinstance(snr, float) or (isinstance(p, float))
self.snr = snr
self.p = p
- 初始化一些參數,snr代表保留原像素點的百分比,p代表執行椒鹽噪聲變化的概率。
#2 分析
def __call__(self, img):
"""
Args:
img (PIL Image): PIL Image
Returns:
PIL Image: PIL image.
"""
if random.uniform(0, 1) < self.p:#概率的判斷
img_ = np.array(img).copy()#轉化為numpy的形式
h, w, c = img_.shape#獲取圖像的高,寬,channel的數量
signal_pct = self.snr#設置圖像原像素點保存的百分比
noise_pct = (1 - self.snr)#噪聲的百分比
mask = np.random.choice((0, 1, 2), size=(h, w, 1), p=[signal_pct, noise_pct/2., noise_pct/2.])
#random.choice的用法:可以從一個int數字或1維array里隨機選取內容,並將選取結果放入n維array中返回。
#size表示要輸出的numpy的形狀
#p = 一個一維數組,制定了每個元素被采樣的概率,若為默認的None,則a中每個元素被采樣的概率相同。
mask = np.repeat(mask, c, axis=2)#將mask在最高軸上(2軸)上復制channel次。
img_[mask == 1] = 255 # 鹽噪聲
img_[mask == 2] = 0 # 椒噪聲
return Image.fromarray(img_.astype('uint8')).convert('RGB')#轉化成pil_img的形式
else:
return img
- 為什么要在_call_里面編寫?->因為在transform.compose調用函數的時候是這樣的。
-
if random.uniform(0, 1) < self.p:#概率的判斷 img_ = np.array(img).copy()#轉化為numpy的形式 h, w, c = img_.shape#獲取圖像的高,寬,channel的數量 signal_pct = self.snr#設置圖像原像素點保存的百分比 noise_pct = (1 - self.snr)#噪聲的百分比
一些對接收img的一些前處理。
-
mask = np.random.choice((0, 1, 2), size=(h, w, 1), p=[signal_pct, noise_pct/2., noise_pct/2.])
問題:如果要給原圖片隨機像素點加上黑白噪點,那么如何選取哪些像素點要加噪點?哪些像素點保持原樣呢? 一般都是創建一個原圖相同維度的mask然后里面隨機選點,用這個mask決定原圖哪個像素點要變成黑白噪聲。主要是關注random.choice的用法 -
mask = np.repeat(mask, c, axis=2)
將mask在最高軸上(2軸)上復制channel次。 -
img_[mask == 1] = 255 # 鹽噪聲 img_[mask == 2] = 0 # 椒噪聲
將原圖加上鹽噪聲和椒噪聲