如何更改图像中的噪波颜色?

2024-09-22 16:31:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图生成一个有噪声的图像,如下所示:

enter image description here

我已经知道了如何生成带有随机噪声的图像,但却不知道如何改变噪声的颜色

import numpy as np
import cv2
import matplotlib.pyplot as plt

img = cv2.imread('/home/pourya/face/os.jpg')[...,::-1]/255.0
noise =  np.random.normal(loc=-1, scale=1, size=img.shape)

# noise overlaid over image
noisy = np.clip((img + noise*1.7),0,1)
noisy2 = np.clip((img + noise*1.6),0,1)

# noise multiplied by image:
# whites can go to black but blacks cannot go to white
noisy2mul = np.clip((img*(1 + noise*1.5)),0,1)
noisy4mul = np.clip((img*(1 + noise*1.4)),0,1)

noisy2mul = np.clip((img*(1 + noise*1.8)),0,1)
noisy4mul = np.clip((img*(1 + noise*1.7)),0,1)

# noise multiplied by bottom and top half images,
# whites stay white blacks black, noise is added to center
img2 = img*2
n2 = np.clip(np.where(img2 <= 1, (img2*(1 + noise*0.2)), (1-img2+1)*(1 + noise*0.2)*-1 + 2)/2, 0,1)
n4 = np.clip(np.where(img2 <= 1, (img2*(1 + noise*0.4)), (1-img2+1)*(1 + noise*0.4)*-1 + 2)/2, 0,1)


# norm noise for viz only
noise2 = (noise - noise.min())/(noise.max()-noise.min())
plt.figure(figsize=(20,20))
plt.imshow(np.vstack((np.hstack((img, noise2)),
                  np.hstack((noisy, noisy2)),
                  np.hstack((noisy2mul, noisy4mul)),
                  np.hstack((n2, n4)))))
plt.show()
plt.hist(noise.ravel(), bins=100)
plt.show()

通过上面的代码,我得到了以下结果

enter image description here

如何生成与第一幅图像相似的单色噪波?? 多谢各位


Tags: to图像importimgclipasnpplt
1条回答
网友
1楼 · 发布于 2024-09-22 16:31:42

在Python/OpenCV中有一种方法可以做到这一点。使用numpy作为遮罩创建灰度噪波图像。创建一个彩色图像。使用噪声作为遮罩,按位_和组合omg和蓝色

输入:

enter image description here

import cv2
import numpy as np

# load image and get dimensions
img = cv2.imread("zelda1.jpg")
hh, ww = img.shape[:2]

# create noise image (multiplier increase noise in result)
noise = (800*np.random.random((hh,ww))).clip(0,255).astype(np.uint8)

# make blue image
blue = np.full_like(img, (255,0,0))

# combine img and blue using noise as mask
img_masked = cv2.bitwise_and(img, img, mask=255-noise)
blue_masked = cv2.bitwise_and(blue, blue, mask=noise)
result = cv2.add(img_masked, blue_masked)
    
# write result to disk
cv2.imwrite("noise.jpg", noise)
cv2.imwrite("blue.jpg", blue)
cv2.imwrite("zelda1_blue_noise.jpg", result)

# display it
cv2.imshow("noise", noise)
cv2.imshow("blue", blue)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

噪声图像:

enter image description here

蓝色图像:

enter image description here

结果:

enter image description here

相关问题 更多 >