2

我试图打乱图像中的所有像素,而我对 Knuths shuffle(以及其他人的)的实现似乎失败了。似乎每行都在工作。我不知道为什么——就是看不到。

这是发生的事情:

在此处输入图像描述在此处输入图像描述

这不是很混乱!好吧,它可能会更加混乱,而且需要更加混乱。

这是我的代码:

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()
4

1 回答 1

1

Whenary是 2D 数组,ary[d]是该数组的视图,而不是内容的副本。

因此,ary[d],ary[e]=ary[e],ary[d]等价于赋值ary[d] = ary[e]; ary[e] = ary[e],因为ary[d]在 RHS 上只是一个指向d第 th 元素的指针ary(而不是像素值的副本)。

为了解决这个问题,您可以使用高级索引

ary[[d,e]] = ary[[e,d]]
于 2012-10-17T03:25:39.733 回答