python - 如何在Python中随机化图像像素

标签 python image image-processing

我是计算视觉和Python的新手,我无法真正弄清楚出了什么问题。我尝试随机化 RGB 图像中的所有图像像素,但结果证明我的图像完全错误,如下所示。有人可以解释一下吗?

from scipy import misc

import numpy as np
import matplotlib.pyplot as plt

#Loads an arbitrary RGB image from the misc library
rgbImg = misc.face()     

%matplotlib inline

#Display out the original RGB image 
plt.figure(1,figsize = (6, 4))
plt.imshow(rgbImg)
plt.show()

#Initialise a new array of zeros with the same shape as the selected RGB image 
rdmImg = np.zeros((rgbImg.shape[0], rgbImg.shape[1], rgbImg.shape[2]))
#Convert 2D matrix of RGB image to 1D matrix
oneDImg = np.ravel(rgbImg)

#Randomly shuffle all image pixels
np.random.shuffle(oneDImg)

#Place shuffled pixel values into the new array
i = 0 
for r in range (len(rgbImg)):
    for c in range(len(rgbImg[0])):
        for z in range (0,3):
            rdmImg[r][c][z] = oneDImg[i] 
            i = i + 1

print rdmImg
plt.imshow(rdmImg) 
plt.show()

原图
image

我尝试随机化图像像素的图像
image

最佳答案

您不是在打乱像素,而是在之后使用 np.ravel()np.shuffle() 时打乱所有内容。

当你打乱像素时,你必须确保颜色、RGB 元组保持不变。

from scipy import misc

import numpy as np
import matplotlib.pyplot as plt

#Loads an arbitrary RGB image from the misc library
rgbImg = misc.face()

#Display out the original RGB image
plt.figure(1,figsize = (6, 4))
plt.imshow(rgbImg)
plt.show()

# doc on shuffle: multi-dimensional arrays are only shuffled along the first axis
# so let's make the image an array of (N,3) instead of (m,n,3)

rndImg2 = np.reshape(rgbImg, (rgbImg.shape[0] * rgbImg.shape[1], rgbImg.shape[2]))
# this like could also be written using -1 in the shape tuple
# this will calculate one dimension automatically
# rndImg2 = np.reshape(rgbImg, (-1, rgbImg.shape[2]))



#now shuffle
np.random.shuffle(rndImg2)

#and reshape to original shape
rdmImg = np.reshape(rndImg2, rgbImg.shape)

plt.imshow(rdmImg)
plt.show()

这是随机的浣熊,注意颜色。那里没有红色或蓝色。只是原来的,白色,灰色,绿色,黑色。

enter image description here

我删除的代码还存在一些其他问题:

  • 不要使用嵌套的for循环,速度慢。

  • 不需要使用np.zeros进行预分配(如果您需要它,只需传递rgbImg.shape作为参数,无需解压单独的值)

关于python - 如何在Python中随机化图像像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52436652/

相关文章:

image - 典型 PSNR 值

python - Pandas 选择包含两个值(包括)的行

python - 基于多种条件的新列

python - 如何使用 Python 抓取具有动态生成的 URL 的页面?

html - 如何使用 HTML 和 CSS 将 14 张图片放在两个垂直列中,每张图片下方都有一个标题,并且图片也排在每一行上?

html - Bootstrap 图像卡在屏幕顶部

python - 后向差分编码

css - 在 CSS 中定义 <img> 的 src 属性

java - 如何在 Processing 中点对点画线

linux - 如何创建 PDF 的 JPG 预览(使用 Linux 命令行)?