繁体   English   中英

如何使用 Python Pillow 对图像中的像素进行洗牌?

[英]How to shuffle pixels in an image using Python Pillow?

我的目标是洗牌 512x512 Python 枕头图像中的所有像素。 另外,我需要时间表现相对较好。 我试过的:

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 为您提供一维数组的主要问题,而 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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM