Python—给图片加椒盐噪声(包含读取写入图片)

#2021年1月27日
import glob
import os
import cv2
import random

def salt_and_pepper_noise(img, proportion=0.05):
    noise_img =img
    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       #加白点
    return noise_img

file_path = "D:\\pythen\\pythendaima\\YOLO\\Yolo-fruit\\yolo\\VOCdevkit\\VOC2007\\picture\\" #r'D: ' 这种格式最后不能有\,所以用D:\\ 这种格式来写
write_path = "D:\\pythen\\pythendaima\\YOLO\\Yolo-fruit\\yolo\\VOCdevkit\\VOC2007\\picture1\\"
images_path = glob.glob(os.path.join(file_path + '*.jpg')) #os.path.join()函数用于路径拼接文件路径

pictures_number = 0
read_the_pictures_number = 0
erro = 0
for i in images_path:
    pictures_number += 1
    img = cv2.imread(i)   #不能识别图片名字为中文的图片
    while read_the_pictures_number<pictures_number:
        read_the_pictures_number+=1
        c = str(read_the_pictures_number+190)
        try:
            cv2.imwrite(os.path.join(write_path+c+'.jpg'),salt_and_pepper_noise(img))
        except: #当try里有错误时,执行此代码
            erro+=1
            print('erro'+str(erro)+'----'+str(os.path.join(write_path+c+'.jpg')))
            print('--------'+str(i))

print('pictures_number={}'.format(pictures_number))
print('read_the_pictures_number={}'.format(read_the_pictures_number))
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值