我刚接触计算机视觉和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()
np.zeros(rgbImg.shape)
,但还有一种更方便的方法:np.zeros_like(rgbImg)
。您的一般想法很好,np.zeros
通常用于预分配数组并在之后填充它。但通常您不是逐个添加单个元素。您可以有一些for循环并插入整行或整列。 - JoeValueError: assignment destination is read-only
... 我使用的是Python2。 - Aubrey