我是靠谱客的博主 俊秀酒窝,这篇文章主要介绍Pytorch图像noise,blur增强前言二、使用步骤总结,现在分享给大家,希望可以做个参考。

前言

pytorch中的transform没有加噪声和模糊的数据增强方法。结合网上现有的代码整合了一个小工具

二、使用步骤

1.引入库

代码如下(示例):

复制代码
1
2
3
4
import numpy as np import random from PIL import Image,ImageFilter

2.代码

代码如下(示例):

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#添加椒盐噪声 class AddSaltPepperNoise(object): def __init__(self, density=0,p=0.5): self.density = density self.p = p def __call__(self, img): if random.uniform(0, 1) < self.p: # 概率的判断 img = np.array(img) # 图片转numpy h, w, c = img.shape Nd = self.density Sd = 1 - Nd mask = np.random.choice((0, 1, 2), size=(h, w, 1), p=[Nd / 2.0, Nd / 2.0, Sd]) # 生成一个通道的mask mask = np.repeat(mask, c, axis=2) # 在通道的维度复制,生成彩色的mask img[mask == 0] = 0 # 椒 img[mask == 1] = 255 # 盐 img = Image.fromarray(img.astype('uint8')).convert('RGB') # numpy转图片 return img else: return img #添加Gaussian噪声 class AddGaussianNoise(object): ''' mean:均值 variance:方差 amplitude:幅值 ''' def __init__(self, mean=0.0, variance=1.0, amplitude=1.0): self.mean = mean self.variance = variance self.amplitude = amplitude def __call__(self, img): img = np.array(img) h, w, c = img.shape N = self.amplitude * np.random.normal(loc=self.mean, scale=self.variance, size=(h, w, 1)) N = np.repeat(N, c, axis=2) img = N + img img[img > 255] = 255 # 避免有值超过255而反转 img = Image.fromarray(img.astype('uint8')).convert('RGB') return img #添加模糊 class Addblur(object): def __init__(self, p=0.5,blur="normal"): # self.density = density self.p = p self.blur= blur def __call__(self, img): if random.uniform(0, 1) < self.p: # 概率的判断 #标准模糊 if self.blur== "normal": img = img.filter(ImageFilter.BLUR) return img #高斯模糊 if self.blur== "Gaussian": img = img.filter(ImageFilter.GaussianBlur) return img #均值模糊 if self.blur== "mean": img = img.filter(ImageFilter.BoxBlur) return img else: return img

3.食用方法

复制代码
1
2
3
4
5
6
7
8
9
10
transform = transforms.Compose([ Addblur(p=1,blur="Gaussian"), #注意要加这两个东西 transforms.ToTensor(), transforms.ToPILImage(), AddSaltPepperNoise(0.05,1), transforms.ToTensor(), transforms.RandomVerticalFlip(), ])

总结

直接加到里面就可以使用啦

最后

以上就是俊秀酒窝最近收集整理的关于Pytorch图像noise,blur增强前言二、使用步骤总结的全部内容,更多相关Pytorch图像noise内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(121)

评论列表共有 0 条评论

立即
投稿
返回
顶部