I am trying to shuffle the pixel positions in image to get encrypted(distorted) image and decrypt the image using the original position in python. This is what i got from GPT and the shuffled images appear to be black.
from PIL import Image
import numpy as np
# Load the image
img = Image.open('test.png')
# Convert the image to a NumPy array
img_array = np.array(img)
# Flatten the array
flat_array = img_array.flatten()
# Create an index array that records the original pixel positions
index_array = np.arange(flat_array.shape[0])
# Shuffle the 1D arrays using the same random permutation
shuffled_index_array = np.random.permutation(index_array)
shuffled_array = flat_array[shuffled_index_array]
# Reshape the shuffled 1D array to the original image shape
shuffled_img_array = shuffled_array.reshape(img_array.shape)
# Convert the NumPy array to PIL image
shuffled_img = Image.fromarray(shuffled_img_array)
# Save the shuffled image
shuffled_img.save('shuffled_image.png')
# Save the shuffled index array as integers to a text file
np.savetxt('shuffled_index_array.txt', shuffled_index_array.astype(int), fmt='%d')
# Load the shuffled index array from the text file
shuffled_index_array = np.loadtxt('shuffled_index_array.txt', dtype=int)
# Rearrange the shuffled array using the shuffled index array
reshuffled_array = shuffled_array[shuffled_index_array]
# Reshape the flat array to the original image shape
reshuffled_img_array = reshuffled_array.reshape(img_array.shape)
# Convert the NumPy array to PIL image
reshuffled_img = Image.fromarray(reshuffled_img_array)
# Save the reshuffled image
reshuffled_img.save('reshuffled_image.png')
I'm trying to shuffle the pixel positions in an image but im stuck with what is wrong going on here.
You are really just missing a reversion of the permutation performed by numpy in the line np.random.permutation(index_array)
. That can be obtained by changing the line creating the reshuffled array to the following
# Rearrange the shuffled array using the shuffled index array
reshuffled_array = shuffled_array[np.argsort(shuffled_index_array)]
An explanation for reversion can be found here: Inverting permutations in Python