[英]adding gaussian noise to image
I'm trying to add gaussian noise to some images using the following code 我正在尝试使用以下代码向一些图像添加高斯噪声
import numpy as np
import cv2
import glob
mean = 0
var = 10
sigma = var ** 0.5
gaussian = np.random.normal(mean, sigma, (224, 224))
for image in glob.glob('/home/aub/myflower/flower_photos/dandelion/*.jpg'):
img = cv2.imread(image)
noisy_image = np.zeros(img.shape, np.float32)
if len(img.shape) == 2:
noisy_image = img + gaussian
else:
noisy_image[:, :, 0] = img[:, :, 0] + gaussian
noisy_image[:, :, 1] = img[:, :, 1] + gaussian
noisy_image[:, :, 2] = img[:, :, 2] + gaussian
cv2.normalize(noisy_image, noisy_image, 0, 255, cv2.NORM_MINMAX, dtype=-1)
noisy_image = noisy_image.astype(np.uint8)
cv2.imshow("img", img)
cv2.imshow("gaussian", gaussian)
cv2.imshow("noisy", noisy_image)
cv2.waitKey(0)
but it doesn't work and it gives me the following error 但它不起作用,它给我以下错误
noisy_image[:, :, 0] = img[:, :, 0] + gaussian ValueError: operands could not be broadcast together with shapes (315,500) (224,224)
noisy_image [:,:,0] = img [:,:,0] +高斯ValueError:操作数不能与形状一起广播(315,500)(224,224)
Kindly review and give feedback. 请检查并提供反馈。
It looks like your image shape is (315,500)
, while the shape of gaussian
is (224,224)
. 看起来您的图像形状为
(315,500)
,而gaussian
形状为(224,224)
。 Try changing your gaussian initialization to 尝试将您的高斯初始化更改为
gaussian = np.random.normal(mean, sigma, (img.shape[0],img.shape[1]))
By the way: You can replace these lines 顺便说一句:您可以替换这些行
noisy_image[:, :, 0] = img[:, :, 0] + gaussian
noisy_image[:, :, 1] = img[:, :, 1] + gaussian
noisy_image[:, :, 2] = img[:, :, 2] + gaussian
with 与
noisy_image = img + gaussian
which will have the same effect: adding gaussian
to each channel. 效果相同:将
gaussian
添加到每个通道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.