【问题标题】:Replace Color Values in Image with Random Noise用随机噪声替换图像中的颜色值
【发布时间】:2019-04-07 18:56:20
【问题描述】:

我在这里找到了一些与我想要做的相当接近的事情: 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()

【问题讨论】:

  • “现在只是想弄清楚如何将彩色像素与最初的灰度像素分开”:mask = (data == np.repeat(255,3)).all(axis=-1); color_pixels = data[~mask]
  • 当我在上面的代码中使用你的代码 sn-p 时,RAM 使用量超出了图表。
  • 奇怪。据我所知,mask 不应该比你的white_areas 大,如果你发现了原因,我很感兴趣。你可能会比较grey = np.repeat(255,3)mask=(data==grey).all(axis=-1),查看开销是否源于在每个像素处重新计算 np.repeat(255,3)。否则,它似乎是一种更紧凑的计算 white_areas 的方法

标签: python numpy python-imaging-library


【解决方案1】:

你可以试试

col_areas = np.logical_or(np.not_equal(red, blue), np.not_equal(red, green))

【讨论】:

    【解决方案2】:

    您可以使用此像素编辑python module

    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 值都会发生变化,这使得您的代码每次都难以完美运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 2018-05-11
      • 2020-06-18
      • 2010-12-05
      • 1970-01-01
      • 2016-02-07
      相关资源
      最近更新 更多