【问题标题】:How can i reproduce an image out of randomly shuffled pixels?如何从随机打乱的像素中再现图像?
【发布时间】:2021-11-08 16:10:28
【问题描述】:

my outputmy input嗨,我正在使用这个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')

【问题讨论】:

  • 如果我给你洗牌名单87, 43, 32, 29, 34, 200,你能不能告诉我是从什么开始的。
  • 如果您知道确切的随机改组算法/序列以便您可以反转它,那么这应该是可能的。但这不是随机洗牌……
  • 如果您说出您真正想要实现的目标,那将会有所帮助。谢谢。
  • @balmy 所以你能帮我并给我一些关于如何在我的代码上使用精确随机算法的提示吗?
  • @MarkSetchell 你能帮我如何定义手动洗牌算法以及如何扭转整个过程吗?

标签: python image numpy image-processing


【解决方案1】:

首先,请记住 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')

这让莉娜变成了这样:

【讨论】:

  • 非常感谢!这正是我想要的
【解决方案2】:

据我所知,不可能可靠地做到这一点。从理论上讲,您可以通过反复打乱像素并将结果输入 Amazon Rekognition 来强制执行此操作,但您最终会收到巨额 AWS 账单,而且可能只是与原始图片大致相同的东西。

【讨论】:

  • 感谢您的帮助,所以让我们假设在这种情况下我们不是随机地手动打乱该图像,是否仍然无法重现它?如果你的回答是肯定的,请你帮我如何手动洗牌?
  • 如果你以一种非随机的方式洗牌它可能是可逆的。
猜你喜欢
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 2012-09-07
相关资源
最近更新 更多