Gney Habub
Gney Habub

Reputation: 3

How to shuffle pixels in an image using Python Pillow?

My goal is to shuffle all pixels in a 512x512 Python Pillow image. 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. It may be damaged or use a file format that Preview doesn’t recognise.

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.

Upvotes: 0

Views: 1142

Answers (1)

Anton Pomieshchenko
Anton Pomieshchenko

Reputation: 2167

Main problem that getdata provide you 1d array, and fromarray requires 2d or 3d array. see corrected code. You maybe notice two reshapes. So first reshape make array of pixels. Each pixel has 3 values. Than shuffle them, than reshape in image. If you comment np.random.shuffle(orig_px) you will get original image as is.

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')

Upvotes: 2

Related Questions