我正在尝试打乱图像中的所有像素,但我对 Knuths 洗牌(以及其他人的)的实现似乎失败了。似乎每一行都在工作。我不知道为什么 - 就是看不到。
这是发生了什么:
这不是很困惑!好吧,它可能更乱,而且需要更乱。
这是我的代码:
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] 是该数组的 View ,而不是内容的副本。
因此,ary[d],ary[e]=ary[e],ary[d]等价于赋值ary[d] = ary[e]; ary[e] = ary[e],因为 RHS 上的 ary[d] 只是指向 ary 的第 (与像素值的副本相对)。d 个元素的指针
要解决这个问题,您可以使用高级索引:
ary[[d,e]] = ary[[e,d]]
