python - 如何从随机打乱的像素中再现图像?
问题描述
我的输出 我的输入嗨我正在使用这个 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')
解决方案
首先,请记住 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')
这把莉娜变成了这样:
推荐阅读
- javascript - 如何在 jsfiddle 中显示控制台
- matlab - 如何绘制此波形
- html - 屏幕阅读器在导航时读取额外内容
- apache-kafka - 您如何设置 Hyperledger Fabric OSN 以通过 SSL 与 Kafka 集群通信?
- python - Apache Python 内部服务器错误 500
- openjpa - 与 TomEE+ 中的 JDBC 驱动程序和连接 URL 相关的 OpenJPA 异常
- database - Laravel 多对多关系连接表问题
- android - 使用 mp4Parser 修剪音频。或者有其他选择吗?
- angular - 使用多个插座的 Angular 6 路由
- c# - Console.Read() 在输入两位/多位数字时是否将第一位数字作为输入?