class NoiseGenerator(object): def generated_noise(self, img, num):
print("*****************") for i1, char in enumerate(num): if num[i1] == 0: img
= self.original(img) print("原图") elif num[i1] == 1: img =
self.gaussian_img(img) print("添加了高斯模糊") elif num[i1] == 2: img =
self.salt_img(img) print("添加了椒盐噪声") elif num[i1] == 3: img = self.liner(img,
a=2) print("增加了对比度") elif num[i1] == 4: img = self.liner(img, a=0.5)
print("降低了对比度") return img def gaussian_img(self, img): # 高斯模糊 im =
cv2.GaussianBlur(img, (9, 9), 5) return im def salt_img(self, img): # 椒盐噪声 n =
int(img.shape[0] * img.shape[1] * 0.1) ilist = np.random.randint(0,
img.shape[1], n) jlist = np.random.randint(0, img.shape[0], n) for k in
range(n): i = ilist[k] j = jlist[k] if img.ndim == 2: img[j, i] = 255 elif
img.ndim == 3: img[j:j + 1, i:i + 1, :] = 255 return img def liner(self, img,
a): # 线性变换,增强图像的对比度 out_image = float(a) * img # 进行数据截断, 大于255的值要截断为255
out_image[out_image > 255] = 255 # 数据类型转化 out_image = np.round(out_image)
out_image = out_image.astype(np.uint8) return out_image def original(self,
img): return img if __name__ == '__main__': rd = NoiseGenerator() # 调用创建的随机噪声类
filenames = './positive_sample' # 图像所在文件夹 a = list(range(5)) # 最多2种噪声的叠加,
range(A): 0 ~ A-1 b = [] # 随机抽取两类噪声所有的类型,这里相当于在五个数中随机抽取两个数 for i in
itertools.product(a, repeat=2): b.append(i) for index, char in enumerate(b): #
获取所有可能类型的索引和数值,如index=0, char="0.jpg" i_name = 0 # 保存图像名称 for image_name in
os.listdir(filenames): # image_name = "0.jpg" c = b[index] #
c=char,为了写循环,将char获取的图像名称用取索引的方式得到 img_path = filenames + '/' + image_name #
图像路径 img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) # 读取图像 #
随机产生噪声,例如c=[2,3],则添加椒盐噪声和增加图像对比度 result_image = rd.generated_noise(img, c) #
cv2.imshow("img1", result_image) # cv2.waitKey(0) index += 1 #
在循环一次b中的所有情况后,index取得最大值25,将indedx置为0,继续循环 if index == 25: index = 0
cv2.imwrite('./add_noise_sample/{}.jpg'.format(i_name), result_image) i_name +=
1

技术
下载桌面版
GitHub
Gitee
SourceForge
百度网盘(提取码:draw)
云服务器优惠
华为云优惠券
腾讯云优惠券
阿里云优惠券
Vultr优惠券
站点信息
问题反馈
邮箱:[email protected]
吐槽一下
QQ群:766591547
关注微信