[英]How to shuffle pixels in an image using Python Pillow?
My goal is to shuffle all pixels in a 512x512 Python Pillow image.我的目标是洗牌 512x512 Python 枕头图像中的所有像素。 Also, I need the time performance to be relatively good.
另外,我需要时间表现相对较好。 What I've tried:
我试过的:
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()
The Preview app gives me the following error:预览应用程序给我以下错误:
The file “tmp11g28d6z.PNG” could not be opened.无法打开文件“tmp11g28d6z.PNG”。 It may be damaged or use a file format that Preview doesn't recognise.
它可能已损坏或使用了 Preview 无法识别的文件格式。
I cannot figure out, what went wrong.我想不通,出了什么问题。 I would be grateful for any suggestions about fixing this code or trying a different approach to solving this problem.
对于修复此代码或尝试不同方法来解决此问题的任何建议,我将不胜感激。
Main problem that getdata provide you 1d array, and fromarray requires 2d or 3d array. getdata 为您提供一维数组的主要问题,而 fromarray 需要 2d 或 3d 数组。 see corrected code.
请参阅更正的代码。 You maybe notice two reshapes.
您可能会注意到两个重塑。 So first reshape make array of pixels.
所以首先重塑像素数组。 Each pixel has 3 values.
每个像素有 3 个值。 Than shuffle them, than reshape in image.
比洗牌他们,而不是重塑形象。 If you comment np.random.shuffle(orig_px) you will get original image as is.
如果你评论 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.