【发布时间】:2018-08-06 00:48:59
【问题描述】:
我需要在 python 中为多个彩色图像(文件格式为 ppm;来源:http://benchmark.ini.rub.de/Dataset/GTSRB_Final_Training_Images.zip)添加噪声。噪声输出图像应该仍然是彩色的。
我尝试了以下方法:
from scipy import misc
import numpy as np
import cv2
import imageio
# Read image ('00000_00030.ppm') from file system
image = misc.imread('./00000/00000_00030.ppm', mode="RGB")
# Add noise to the input image
noised_image = image + 3 * image.std() * np.random.random(image.shape)
# Plot original and noisy images
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
f, axarr = plt.subplots(2, 2)
axarr[0, 0].imshow(image)
axarr[0, 0].set_title('Original image')
axarr[0, 1].imshow(noised_image)
axarr[0, 1].set_title('Noised image')
plt.show()
# Save noised image to file system
saved_image = cv2.imwrite("./noised.ppm", noised_image)
但首先问题是在 jupyter notebook 中无法正确绘制噪声图像(见图 1):
第二个问题是 RG 通道(红色和绿色)丢失(在保存的文件中):
那么如何在噪声图像中保留所有 RGB 颜色?
搜索了很长时间后,我得到了解决方案 - 保存的文件现在保留了所有 RGB 颜色(参见以下代码中的第 8 行;参见图 3):
from scipy import misc
import numpy as np
import cv2
import imageio
# Read image ('00000_00030.ppm') from file system
# image = misc.imread('./00000/00000_00030.ppm', mode="RGB")
image = cv2.imread('./00000/00000_00030.ppm',1)
# Add noise to the input image
noised_image = image + 3 * image.std() * np.random.random(image.shape)
# Plot original and noisy images
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
f, axarr = plt.subplots(2, 2)
axarr[0, 0].imshow(image)
axarr[0, 0].set_title('Original image')
axarr[0, 1].imshow(noised_image)
axarr[0, 1].set_title('Noised image')
plt.show()
# Save noised image to file system
saved_image = cv2.imwrite("./noised1.ppm", noised_image)
但绘制的数字仍然是错误的:
这是最终代码,用于在 python 中为 RGB 图像添加噪声,并正确绘制它们:
from scipy import misc
import numpy as np
import cv2
import imageio
# Read image ('00000_00030.ppm') from file system
# image = misc.imread('./00000/00000_00030.ppm', mode="RGB")
image = cv2.imread('./00000/00000_00030.ppm',1)
# Add noise to the input image
noised_image = image + 3 * image.std() * np.random.random(image.shape)
RGB_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Plot original and noisy images
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
f, axarr = plt.subplots(2, 2)
axarr[0, 0].imshow(RGB_image)
axarr[0, 0].set_title('Original image')
axarr[0, 1].imshow(noised_image)
axarr[0, 1].set_title('Noised image')
plt.show()
# Save noised image to file system
saved_image = cv2.imwrite("./noised1.ppm", noised_image)
【问题讨论】:
-
你尝试了什么,你在哪里失败了?有几个库可以读取图像,例如几个库。 numpy 生成与图像大小相同的随机数组。您可以简单地将随机矩阵添加到图像中。
-
查看已编辑的初始问题描述
-
我试过你的代码,但我认为它仍然不能解决问题。问题是通过 imwrite 而不是 plot 来解决的