【问题标题】:Python Image Shuffle Failure - where have I gone wrong?Python Image Shuffle Failure - 我哪里出错了?
【发布时间】:2012-10-17 02:47:15
【问题描述】:

我正在尝试打乱图像中的所有像素,而我对 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()

【问题讨论】:

  • 那个蒙娜丽莎好像有胡子。此外,在shuffle 中,您正在遍历图像中的每一行。尝试reshape将图像放入一维数组,然后对其进行洗牌。
  • IIRC shape 将是 (height, width, channels),因此他的 reshape 应该已经将其变平了。
  • 这是 Marcel Duchamp 的 LHOOQ。 en.wikipedia.org/wiki/L.H.O.O.Q。行 data = data.reshape((shape[0]*shape[1],shape[2])) 应该按照你说的做。我想打乱像素位置而不是它们的颜色。

标签: python numpy python-imaging-library random-sample


【解决方案1】:

ary 是二维数组时,ary[d] 是该数组的视图,而不是内容的副本。

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

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

ary[[d,e]] = ary[[e,d]]

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 2013-12-25
    • 2018-01-21
    • 1970-01-01
    • 2014-03-01
    相关资源
    最近更新 更多