如何在python中随机化图像像素
我对计算视觉和python还不熟悉,我真的不知道哪里出了问题。我曾尝试将RGB图像中的所有图像像素随机化,但结果证明我的图像完全错误,如下图所示。谁能帮我弄点光吗如何在python中随机化图像像素,python,image,image-processing,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 i
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()
原始图像我尝试随机化图像像素的图像
将
plt.imshow(rdmImg)
更改为plt.imshow(rdmImg.astype(np.uint8))
这可能与此问题有关您不是在洗牌像素,而是在使用
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()
这是随机浣熊,注意颜色。那里没有红色或蓝色。只有原来的,白色,灰色,绿色,黑色
我删除的代码还有一些其他问题:
- 不要使用嵌套for循环,慢
- 不需要使用带有
的预分配(如果需要,只需将np.zero
作为参数传递,无需解压缩单独的值)rgbImg.shape
将输入数据剪裁到带有RGB数据的imshow的有效范围([0..1]表示浮点数,[0..255]表示整数)。
。谷歌它,你会找到问题的答案。谢谢你的输入!我已尝试按照您的建议添加行,并且图像确实发生了变化,但是,我可能会遇到像素混洗的问题,因为图像结果并非仅包含原始图像的颜色。谢谢您的输入!你的意思是我可以只用np.zero(rgbImg.shape)?您能建议我什么时候需要使用np.zero吗?是的,您可以使用np.zero(rgbImg.shape)
,但还有一种更方便的方法:np.zero\u like(rgbImg)
。您的总体想法很好,np。零通常用于预先分配数组,然后填充它。但通常情况下,您不会逐个添加单个元素。你可以有一些for循环并插入整行或整列。嗨,我完全复制了这段代码,但它只显示了原始的racoon图片。它给出了错误ValueError:assignment destination是只读的
。。。我用蟒蛇2。