Python图像洗牌失败-我哪里出错了?
我试图对图像中的所有像素进行置乱,而我的Knuths shuffle(以及其他人的)实现似乎失败了。似乎每排都有效果。我不明白为什么——只是看不见而已 发生的情况如下: 这可不是很糟糕!好吧,它可以更简陋,也需要更简陋 这是我的密码:Python图像洗牌失败-我哪里出错了?,python,numpy,python-imaging-library,random-sample,Python,Numpy,Python Imaging Library,Random Sample,我试图对图像中的所有像素进行置乱,而我的Knuths shuffle(以及其他人的)实现似乎失败了。似乎每排都有效果。我不明白为什么——只是看不见而已 发生的情况如下: 这可不是很糟糕!好吧,它可以更简陋,也需要更简陋 这是我的密码: import Image from numpy import * file1 = "lhooq" file2 = "kandinsky" def shuffle(ary): a=len(ary) b=a-1 for d in rang
import Image
from numpy import *
file1 = "lhooq"
file2 = "kandinsky"
def shuffle(ary):
a=len(ary)
b=a-1
for d in range(b,0,-1):
e=random.randint(0,d)
ary[d],ary[e]=ary[e],ary[d]
return ary
for filename in [file1, file2]:
fid = open(filename+".jpg", 'r')
im = Image.open(fid)
data = array(im)
# turn into array
shape = data.shape
data = data.reshape((shape[0]*shape[1],shape[2]))
# Knuth Shuffle
data = shuffle(data)
data = data.reshape(shape)
imout = Image.fromarray(data)
imout.show()
fid.close()
当
ary
是二维数组时,ary[d]
是该数组的视图,而不是内容的副本
因此,ari[d],ari[e]=ari[e],ari[d]
相当于赋值ari[d]=ari[e];ary[e]=ary[e]
,因为RHS上的ary[d]
只是指向ary
第th元素的指针(与像素值的副本相反)
要解决此问题,可以使用高级索引:
那个蒙娜丽莎好像有胡子。此外,在shuffle
中,您将迭代图像中的每一行。尝试重塑
将图像放入一维数组,然后将其洗牌。IIRC塑造
将是(高度、宽度、通道)
,因此他的重塑
应该已经将其展平。这是Marcel Duchamp的LHOOQ。线条数据=数据。重塑((形状[0]*形状[1],形状[2])应该按照你说的做。我想扰乱像素位置,而不是它们的颜色。
ary[[d,e]] = ary[[e,d]]