python - 用随机噪声替换图像中的颜色值
问题描述
我在这里找到了一些与我想要做的相当接近的东西: Python: PIL replace a single RGBA color
但是,在我的场景中,我的图像最初是灰度图像,并在图像中添加了颜色注释(带有彩色注释的 X 射线)。我想用随机噪声替换任何不是灰度的像素。我的主要问题是用噪声而不是单一颜色替换值。
编辑:我想出了随机噪声部分,现在只是想弄清楚如何将彩色像素与最初的灰度像素分开。
from PIL import Image
import numpy as np
im = Image.open('test.jpg')
data = np.array(im) # "data" is a height x width x 3 numpy array
red, green, blue = data.T # Temporarily unpack the bands for readability
# Replace white with random noise...
white_areas = (red == 255) & (blue == 255) & (green == 255)
Z = random.random(data[...][white_areas.T].shape)
data[...][white_areas.T] = Z
im2 = Image.fromarray(data)
im2.show()
解决方案
你可以使用这个 Pixel Editing python 模块
from PixelMenu import ChangePixels as cp
im = Image.open('test.jpg')
grayscalergb=(128, 128, 128) #RGB value of gray in your image
noise=(100,30,5) #You can adjust the noise based upon your requirements
outputimg=cp(im, col=grayscalergb, col2=noise, save=False,tolerance=100) #Adjust the tolerance until you get the right amount of noise in your image
还:
我建议您使用 png 图像而不是 jpg 图像,因为 JPEG 是为压缩而设计的,每次加载图像时,RGB 值都会发生变化,从而使您的代码每次都难以完美运行