python - 如何使用 Python Pillow 打乱图像中的像素?
问题描述
我的目标是洗牌 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 无法识别的文件格式。
我想不通,出了什么问题。对于修复此代码或尝试不同方法来解决此问题的任何建议,我将不胜感激。
解决方案
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')