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

2024-10-03 21:25:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我对计算视觉和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


Tags: thein图像imageimportforasnp
2条回答

你不是在洗牌像素,而是在之后使用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()

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

{a1}

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

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

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

plt.imshow(rdmImg)改为plt.imshow(rdmImg.astype(np.uint8))
这可能与此问题有关https://github.com/matplotlib/matplotlib/issues/9391/

相关问题 更多 >