首页 > 解决方案 > 如何从随机打乱的像素中再现图像?

问题描述

我的输出 我的输入嗨我正在使用这个 python 代码来生成一个随机像素图像有什么办法可以使这个过程相反吗?例如,我将此代码输出的照片提供给程序,它会再次复制原始照片。

我正在尝试生成静态样式图像并将其反转回原始图像,并且我愿意接受任何其他替换此代码的想法

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

标签: pythonimagenumpyimage-processing

解决方案


首先,请记住 JPEG 是有损的 - 所以你永远不会找回你用 JPEG 写的东西 - 它会改变你的数据!所以,如果你想无损地回读你开始的内容,请使用 PNG。

您可以这样做:

#!/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')

这把莉娜变成了这样:

在此处输入图像描述


推荐阅读