【问题标题】:How to shuffle pixels in an image using Python Pillow?如何使用 Python Pillow 打乱图像中的像素?
【发布时间】:2020-04-05 20:19:30
【问题描述】:

我的目标是随机播放 512x512 Python Pillow 图像中的所有像素。另外,我需要时间表现相对较好。我试过的:

from PIL import Image
import numpy as np

orig = Image.open('img/input2.jpg')
orig_px = orig.getdata()

np_px = np.asarray(orig_px)
np.random.shuffle(np_px)
res = Image.fromarray(np_px.astype('uint8')).convert('RGB')

res.show()

预览应用程序给我以下错误:

无法打开文件“tmp11g28d6z.PNG”。 它可能已损坏或使用了 Preview 无法识别的文件格式。

我不知道出了什么问题。对于修复此代码或尝试不同方法来解决此问题的任何建议,我将不胜感激。

【问题讨论】:

    标签: python image python-imaging-library


    【解决方案1】:

    getdata 为您提供 1d 数组的主要问题,而 fromarray 需要 2d 或 3d 数组。请参阅更正的代码。您可能会注意到两个重塑。所以首先重塑像素数组。每个像素有 3 个值。比洗牌他们,而不是重塑形象。如果你评论 np.random.shuffle(orig_px) 你会得到原始图像。

    from PIL import Image
    import numpy as np
    
    orig = Image.open('test.jpg')
    orig_px = orig.getdata()
    
    orig_px = np.reshape(orig_px, (orig.height * orig.width, 3))
    np.random.shuffle(orig_px)
    
    orig_px = np.reshape(orig_px, (orig.height, orig.width, 3))
    
    res = Image.fromarray(orig_px.astype('uint8'))
    res.save('out.jpg')
    

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 2015-11-20
      • 2021-11-08
      • 1970-01-01
      • 2018-10-18
      • 2014-09-04
      • 2013-12-20
      • 1970-01-01
      • 2018-08-17
      相关资源
      最近更新 更多