numpy 打乱像素在图像中的位置,以获得打乱的图像,并将其还原为原始图像

monwx1rj  于 2023-02-16  发布在  其他
关注(0)|答案(1)|浏览(181)

我试图打乱图像中的像素位置,以获得加密(失真)图像,并使用python中的原始位置解密图像。这是我从GPT中得到的,打乱后的图像看起来是黑色的。

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

我试图 Shuffle 的像素位置在一个图像中,但我坚持什么是错误的事情发生在这里。

z0qdvdin

z0qdvdin1#

您实际上只是错过了numpy在np.random.permutation(index_array)行中执行的置换的反转操作,这可以通过将创建重排数组的行更改为以下行来获得

# Rearrange the shuffled array using the shuffled index array
reshuffled_array = shuffled_array[np.argsort(shuffled_index_array)]

有关回复的解释可在此处找到:Inverting permutations in Python

相关问题