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

3

我刚接触计算机视觉和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

2个回答

5

使用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作为参数传递即可,不需要拆开)。

谢谢您的输入!您的意思是我可以只使用np.zeros(rgbImg.shape)吗?您能否友好地建议何时需要使用np.zeros的场景? - Kelsey Jamie
1
是的,您可以使用 np.zeros(rgbImg.shape),但还有一种更方便的方法:np.zeros_like(rgbImg)。您的一般想法很好,np.zeros通常用于预分配数组并在之后填充它。但通常您不是逐个添加单个元素。您可以有一些for循环并插入整行或整列。 - Joe
嗨,我完全复制了这段代码,但它只显示原始的浣熊图片。它给出了错误 ValueError: assignment destination is read-only... 我使用的是Python2。 - Aubrey
关于 ValueError: assignment destination is read-only 的问题:https://dev59.com/d1kS5IYBdhLWcg3ws4ck#54308748 - Joe

1

你的原始代码应该在Python控制台中打印出这条消息:“Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).” 谷歌一下,你会找到解决这个问题的答案。 - mJace
谢谢您的输入!我已经尝试按照您的建议添加了这行代码,图像确实发生了变化,但是可能存在像素混乱的问题,因为图像并不仅包含原始图像的颜色。 - Kelsey Jamie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接