#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))
Python—给图片加椒盐噪声(包含读取写入图片)
最新推荐文章于 2024-04-10 18:09:00 发布