gpt4 book ai didi

python - 使用 extract_image_patches 后重建图像

转载 作者:太空狗 更新时间:2023-10-29 20:13:27 26 4
gpt4 key购买 nike

我有一个自动编码器,它将图像作为输入并生成新图像作为输出。

输入图像 (1x1024x1024x3) 在被馈送到网络之前被分成 block (1024x32x32x3)。

一旦我有了输出,还有一批大小为 1024x32x32x3 的补丁,我希望能够重建一个 1024x1024x3 的图像。我以为我只是通过简单的 reshape 就怀疑了这一点,但事实是这样的。

首先,Tensorflow 读取的图像: Input image

我用下面的代码修补了图像

patch_size = [1, 32, 32, 1]
patches = tf.extract_image_patches([image],
patch_size, patch_size, [1, 1, 1, 1], 'VALID')
patches = tf.reshape(patches, [1024, 32, 32, 3])

下面是这张图片的几个补丁:

Patched input #168 Patched input #169

但是当我将这个补丁数据 reshape 回图像时,事情就变成了梨形。

reconstructed = tf.reshape(patches, [1, 1024, 1024, 3])
converted = tf.image.convert_image_dtype(reconstructed, tf.uint8)
encoded = tf.image.encode_png(converted)

Reconstructed output

在这个例子中,在修补和重建之间没有进行任何处理。我做了一个version of the code你可以用来测试这种行为。要使用它,请运行以下命令:

echo "/path/to/test-image.png" > inputs.txt
mkdir images
python3 image_test.py inputs.txt images

该代码将为每个输入图像中的 1024 个补丁中的每一个创建一个输入图像、一个补丁图像和一个输出图像,因此如果您只关心保存所有图像,请注释掉创建输入和输出图像的行补丁。

有人,请解释发生了什么:(

最佳答案

由于我也为此苦苦挣扎,所以我发布了一个可能对其他人有用的解决方案。诀窍是要意识到 tf.extract_image_patches 的倒数是它的梯度,如 suggested here .由于此操作的梯度是在 Tensorflow 中实现的,因此很容易构建重建函数:

import tensorflow as tf
from keras import backend as K
import numpy as np

def extract_patches(x):
return tf.extract_image_patches(
x,
(1, 3, 3, 1),
(1, 1, 1, 1),
(1, 1, 1, 1),
padding="VALID"
)

def extract_patches_inverse(x, y):
_x = tf.zeros_like(x)
_y = extract_patches(_x)
grad = tf.gradients(_y, _x)[0]
# Divide by grad, to "average" together the overlapping patches
# otherwise they would simply sum up
return tf.gradients(_y, _x, grad_ys=y)[0] / grad

# Generate 10 fake images, last dimension can be different than 3
images = np.random.random((10, 28, 28, 3)).astype(np.float32)
# Extract patches
patches = extract_patches(images)
# Reconstruct image
# Notice that original images are only passed to infer the right shape
images_reconstructed = extract_patches_inverse(images, patches)

# Compare with original (evaluating tf.Tensor into a numpy array)
# Here using Keras session
images_r = images_reconstructed.eval(session=K.get_session())

print (np.sum(np.square(images - images_r)))
# 2.3820458e-11

关于python - 使用 extract_image_patches 后重建图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44047753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com