How can i reproduce an image out of randomly shuffled pixels?

my output my input Hi I am using this python code to generate an shuffle pixel image is there any way to make this process opposite ? for example I give this code output’s photo to the program and it reproduce the original photo again.

I am trying to generate an static style image and reverse it back into the original image and I am open into any other ideas for replacing this code

from PIL import Image
import numpy as np

orig = Image.open('lena.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')

Answer

Firstly, bear in mind that JPEG is lossy – so you will never get back what you write with JPEG – it changes your data! So, use PNG if you want to read back losslessly exactly what you started with.

You can do what you ask like this:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

def shuffleImage(im, seed=42):
    # Get pixels and put in Numpy array for easy shuffling
    pix = np.array(im.getdata())

    # Generate an array of shuffled indices
    # Seed random number generation to ensure same result
    np.random.seed(seed)
    indices = np.random.permutation(len(pix))

    # Shuffle the pixels and recreate image
    shuffled = pix[indices].astype(np.uint8)
 
    return Image.fromarray(shuffled.reshape(im.width,im.height,3))

def unshuffleImage(im, seed=42):

    # Get shuffled pixels in Numpy array
    shuffled = np.array(im.getdata())
    nPix = len(shuffled)

    # Generate unshuffler
    np.random.seed(seed)
    indices = np.random.permutation(nPix)
    unshuffler = np.zeros(nPix, np.uint32)
    unshuffler[indices] = np.arange(nPix)

    unshuffledPix = shuffled[unshuffler].astype(np.uint8)
    return Image.fromarray(unshuffledPix.reshape(im.width,im.height,3))

# Load image and ensure RGB, i.e. not palette image
orig = Image.open('lena.png').convert('RGB')

result = shuffleImage(orig)
result.save('shuffled.png')

unshuffled = unshuffleImage(result)
unshuffled.save('unshuffled.png')

Which turns Lena into this:

enter image description here