批量对数据添加噪声并生成新命名标注文件

该博客介绍了如何在图像处理中添加椒盐噪声和高斯噪声来增强数据集。通过随机选择并应用这两种噪声类型,创建了新的带有噪声的图像,并相应地更新了标注文件,用于训练机器学习模型,提高其鲁棒性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

比赛中,通过随机添加高斯噪声和椒盐噪声并生成新命名的标注文件:

# -*- coding: utf-8 -*-

import cv2
import numpy as np
import os.path
import copy
import random
import shutil

# 椒盐噪声
def SaltAndPepper(src,percetage):
    SP_NoiseImg=src.copy()
    SP_NoiseNum=int(percetage*src.shape[0]*src.shape[1])
    for i in range(SP_NoiseNum):
        randR=np.random.randint(0,src.shape[0]-1)
        randG=np.random.randint(0,src.shape[1]-1)
        randB=np.random.randint(0,3)
        if np.random.randint(0,1)==0:
            SP_NoiseImg[randR,randG,randB]=0
        else:
            SP_NoiseImg[randR,randG,randB]=255
    return SP_NoiseImg

# 高斯噪声
def addGaussianNoise(image,percetage):
    G_Noiseimg = image.copy()
    w = image.shape[1]
    h = image.shape[0]
    G_NoiseNum=int(percetage*image.shape[0]*image.shape[1])
    for i in range(G_NoiseNum):
        temp_x = np.random.randint(0,h)
        temp_y = np.random.randint(0,w)
        G_Noiseimg[temp_x][temp_y][np.random.randint(3)] = np.random.randn(1)[0]
    return G_Noiseimg

# 图片文件夹路径
file_dir = r'./images/' 
label_dir = r'/home/ubuntu/workspace/tao-experiments/data/data_augmentation/labels/'

cnt = 1

for img_name in os.listdir(file_dir):
    img_path = file_dir + img_name
    label_raw_name = './labels/' + img_name[:-4] + '.txt'
    label_new_name = label_dir + img_name[:-4]+ '_noise' + '.txt'
    img = cv2.imread(img_path)
    rand_num = random.randint(1,10)
    if rand_num >=5:
        img_gauss = addGaussianNoise(img, 0.3)
    else:
        img_gauss = SaltAndPepper(img, 0.3)
    cv2.imwrite(r'./data_augmentation/images/' + img_name[0:-4] + '_noise.jpg',img_gauss)
    shutil.copyfile(label_raw_name, label_new_name)
    if cnt == 210:
        break
    else:
        cnt += 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

naca yu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值