当前位置:网站首页>批量对数据添加噪声并生成新命名标注文件

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

2022-06-11 10:13:00 naca yu

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

# -*- 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
原网站

版权声明
本文为[naca yu]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43253464/article/details/125207927