gpt4 book ai didi

python - 向图像添加高斯噪声

转载 作者:行者123 更新时间:2023-12-02 16:45:21 25 4
gpt4 key购买 nike

我正在尝试使用以下代码向某些图像添加高斯噪声

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)

但它不起作用,它给了我以下错误

noisy_image[:, :, 0] = img[:, :, 0] + gaussian ValueError: operands could not be broadcast together with shapes (315,500) (224,224)

请审阅并提供反馈。

最佳答案

看起来你的图像形状是(315,500),而gaussian的形状是(224,224)。尝试将高斯初始化更改为

gaussian = np.random.normal(mean, sigma, (img.shape[0],img.shape[1])) 

顺便说一句:您可以替换这些行

noisy_image[:, :, 0] = img[:, :, 0] + gaussian
noisy_image[:, :, 1] = img[:, :, 1] + gaussian
noisy_image[:, :, 2] = img[:, :, 2] + gaussian

noisy_image = img + gaussian

这将具有相同的效果:向每个 channel 添加 gaussian

关于python - 向图像添加高斯噪声,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55261087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com