对原始图像中添加一定的噪声,生成新的图像数据,并存储操作的代码
时间: 2024-02-13 15:02:36 浏览: 30
下面是对原始图像中添加一定的噪声,生成新的图像数据,并存储操作的Python代码:
``` python
import os
import cv2
import numpy as np
# 定义噪声类型和强度
noises = ['gaussian', 'salt_pepper', 'poisson']
strengths = [0.01, 0.02, 0.03]
# 定义原始图像路径和目标文件夹路径
src_path = 'path/to/source/images/'
dst_path = 'path/to/output/folder/'
# 遍历原始图像
for root, dirs, files in os.walk(src_path):
for file in files:
# 读取原始图像
img = cv2.imread(os.path.join(root, file))
# 遍历噪声类型和强度
for noise in noises:
for strength in strengths:
# 添加噪声
if noise == 'gaussian':
noisy_img = np.clip(img + np.random.normal(loc=0, scale=strength * 255, size=img.shape), 0, 255).astype(np.uint8)
elif noise == 'salt_pepper':
noisy_img = img.copy()
salt_pepper = np.random.rand(*img.shape[:2])
noisy_img[salt_pepper < strength / 2] = 0
noisy_img[salt_pepper > 1 - strength / 2] = 255
elif noise == 'poisson':
noisy_img = np.random.poisson(img / 255 * strength) * (255 / strength)
# 保存带噪声的图像
new_file_name = os.path.splitext(file)[0] + '_noisy_' + noise + '_' + str(strength) + os.path.splitext(file)[1]
cv2.imwrite(os.path.join(dst_path, new_file_name), noisy_img)
```
其中,`noises`变量定义了噪声类型列表,`strengths`变量定义了噪声强度列表,`src_path`变量定义了原始图像路径,`dst_path`变量定义了目标文件夹路径。代码通过遍历原始图像,依次添加不同类型和强度的噪声,并将带噪声的图像保存到目标文件夹中。需要注意的是,代码中使用了NumPy和OpenCV库进行图像处理,需要先安装这些库。