gpt4 book ai didi

Python Image Shuffle Failure - 我哪里出错了?

转载 作者:太空宇宙 更新时间:2023-11-04 06:20:11 25 4
gpt4 key购买 nike

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

这是发生了什么:

enter image description here enter image description here

这不是很困惑!好吧,它可能更乱,而且需要更乱。

这是我的代码:

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]]

关于Python Image Shuffle Failure - 我哪里出错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com