使用CIFAR10数据集实现椒盐噪声的图像去噪
时间: 2023-06-13 10:07:54 浏览: 144
基于matlab的椒盐噪声图像去噪方法研究.pdf
5星 · 资源好评率100%
首先,我们需要导入必要的库和数据集:
```python
import torch
import torchvision
import torchvision.transforms as transforms
# 加载CIFAR10数据集
transform = transforms.Compose(
[transforms.ToTensor()])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
shuffle=True, num_workers=2)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
shuffle=False, num_workers=2)
```
接下来,我们可以添加一些椒盐噪声到图像中:
```python
import numpy as np
def add_salt_and_pepper(img, noise_ratio=0.05):
"""
添加椒盐噪声
"""
img = np.array(img)
h, w, c = img.shape
mask = np.random.choice((0, 1, 2), size=(h, w, 1), p=[noise_ratio, noise_ratio, 1-2*noise_ratio])
mask = np.repeat(mask, c, axis=2)
img[mask == 0] = 0
img[mask == 1] = 255
return img
```
然后,我们可以使用 PyTorch 中的卷积神经网络(CNN)来实现图像去噪:
```python
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
```
接下来,我们需要定义损失函数和优化器:
```python
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
```
最后,我们可以训练模型并测试:
```python
for epoch in range(2): # 进行两轮训练
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# 获取输入
inputs, labels = data
# 添加椒盐噪声
inputs = [add_salt_and_pepper(img) for img in inputs]
inputs = torch.from_numpy(np.array(inputs)).float()
labels = torch.from_numpy(np.array(labels)).long()
# 梯度清零
optimizer.zero_grad()
# 正向传播,反向传播,优化
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 打印统计信息
running_loss += loss.item()
if i % 2000 == 1999: # 每2000个小批量数据打印一次
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
# 测试
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
# 添加椒盐噪声
inputs = [add_salt_and_pepper(img) for img in images]
inputs = torch.from_numpy(np.array(inputs)).float()
labels = torch.from_numpy(np.array(labels)).long()
outputs = net(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
```
这样,我们就可以使用 CIFAR10 数据集实现椒盐噪声的图像去噪了。
阅读全文