本文介绍了向图像添加高斯噪声的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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] + 高斯值错误:操作数无法与形状一起广播 (315,500) (224,224)

请查看并提供反馈.

推荐答案

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

It looks like your image shape is (315,500), while the shape of gaussian is (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

noisy_image = img + gaussian

这将产生相同的效果:将 gaussian 添加到每个通道.

which will have the same effect: adding gaussian to each channel.

这篇关于向图像添加高斯噪声的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 10:00