1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Mvtec数据集批量加各种噪声(高斯 椒盐 随机噪声)

Mvtec数据集批量加各种噪声(高斯 椒盐 随机噪声)

时间:2022-03-24 05:13:33

相关推荐

Mvtec数据集批量加各种噪声(高斯 椒盐 随机噪声)

最近想在Mvtec数据集test数据中加一些噪声,参考别人的博客写了一个代码,可以对数据集批量处理(这里只对test数据进行了噪声处理),代码如下:

import cv2import numpy as npimport osimport random# 随机噪声def random_noise(image,noise_num):'''添加随机噪点(实际上就是随机在图像上将像素点的灰度值变为255即白色)param image: 需要加噪的图片param noise_num: 添加的噪音点数目return: img_noise'''# 参数image:,noise_num:img_noise = image# cv2.imshow("src", img)rows, cols, chn = img_noise.shape# 加噪声for i in range(noise_num):x = np.random.randint(0, rows)#随机生成指定范围的整数y = np.random.randint(0, cols)img_noise[x, y, :] = 255return img_noise# 椒盐噪声def sp_noise(noise_img, proportion):'''添加椒盐噪声proportion的值表示加入噪声的量,可根据需要自行调整return: img_noise'''height, width = noise_img.shape[0], noise_img.shape[1]#获取高度宽度像素值num = int(height * width * proportion) #一个准备加入多少噪声小点for i in range(num):w = random.randint(0, width - 1)h = random.randint(0, height - 1)if random.randint(0, 1) == 0:noise_img[h, w] = 0else:noise_img[h, w] = 255return noise_img# 高斯噪声def gaussian_noise(img, mean, sigma):'''此函数用将产生的高斯噪声加到图片上传入:img : 原图mean : 均值sigma : 标准差返回:gaussian_out : 噪声处理后的图片'''# 将图片灰度标准化img = img / 255# 产生高斯 noisenoise = np.random.normal(mean, sigma, img.shape)# 将噪声和图片叠加gaussian_out = img + noise# 将超过 1 的置 1,低于 0 的置 0gaussian_out = np.clip(gaussian_out, 0, 1)# 将图片灰度范围的恢复为 0-255gaussian_out = np.uint8(gaussian_out*255)# 将噪声范围搞为 0-255# noise = np.uint8(noise*255)return gaussian_out# 这里也会返回噪声,注意返回值# 读取并保存def convert(input_dir, output_dir):for filename in os.listdir(input_dir):path = input_dir + "/" + filename # 获取文件路径print("doing... ", path)noise_img = cv2.imread(path)#读取图片# img_noise = gaussian_noise(noise_img, 0, 0.3) # 高斯噪声#img_noise = sp_noise(noise_img, 0.01) # 椒盐噪声img_noise = random_noise(noise_img,3000)# 随机噪声cv2.imwrite(output_dir+'/'+filename,img_noise )# mvtec中所有的类别CLASS_NAMES = ['bottle', 'cable', 'capsule', 'carpet', 'grid','hazelnut', 'leather', 'metal_nut', 'pill', 'screw','tile', 'toothbrush', 'transistor', 'wood', 'zipper'] data_path = "E:\mvtec_noise\\mvtec_random_noise_3000" # 数据集路径if __name__ == '__main__':for class_name in CLASS_NAMES:os_path_class = os.listdir(os.path.join(data_path, class_name, "test")) # 读取文件夹下的所有文件名(test数据集里还有各种类别,这里是为了获取test中所有类别的名称)for name in os_path_class:input_dir = os.path.join(data_path, class_name, "test", name) # 输入数据文件夹output_dir = os.path.join(data_path, class_name, "test", name) # 输出数据文件夹(会覆盖原图)convert(input_dir, output_dir)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。