python实现给文件夹下图片加入随机噪声并批量保存

import os
import cv2
import numpy as np
import random
proportion=0.0025#加入多少小噪声点,可以调大
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)#读取图片
        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] = 0
            else:
                noise_img[h, w] = 255
        cv2.imwrite(output_dir+'/'+filename,noise_img)
if __name__ == '__main__':
    input_dir = "G:/shuju"#输入数据文件夹
    output_dir = "G:/shuju/xin"#输出数据文件夹
    convert(input_dir, output_dir)

python实现给文件夹下图片加入随机噪声并批量保存_第1张图片
参考

你可能感兴趣的:(图像处理)