gpt4 book ai didi

python - 将图像编辑为 tensorflow 张量 python

转载 作者:太空狗 更新时间:2023-10-29 21:48:18 24 4
gpt4 key购买 nike

我会尽力在这里提供一个可重现的例子。

我有一张图片:

enter image description here

Aaron Eckhart 的这张图片是 (150, 150)

我的目标是通过对像素进行数学运算来扰乱此图像的 ROI,但是,问题是数学运算必须作为 tensorflow 张量来完成,因为要完成的数学运算是将张量乘以它缩放梯度(这也是一个大小为 (row_pixels, column_pixels, 3) 的张量)

所以这是我想象的过程:

  1. 以 numpy 数组的形式读入图像 RGB 大小:(1, 150, 150, 3) (1 是批处理尺寸)

    w, h = img.shape

    ret = np.empty((w, h, 3), dtype=np.uint8)

    ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img

  2. 使像素值介于0和1之间

    img = (faces1 - min_pixel)/(max_pixel - min_pixel)

  3. 我在范围内(步数):

(a) 提取图像的ROI 这是我不明白该怎么做的部分

(b) 计算较小img ROI张量损失的梯度

loss = utils_tf.model_loss(y, preds, mean=False)
grad, = tf.gradients(loss, x)

(c) 将 img ROI 张量乘以损失梯度

scaled_grad = eps * normalized_grad
adv_img = img + scaled_grad

(d) 将这个新扰动的 ROI 张量放回与原始张量相同的位置 这是我不明白该怎么做的另一部分

这将导致图像中只有一些像素值被扰动而其余的保持不变

最佳答案

给定一张图片:

Full image: two elephants

(a) 从图像中获取感兴趣区域((440, 240), (535, 380)):

roi_slice = tf.slice(
image_in,
[top_left_x, top_left_y, top_left_z],
[roi_len_x, roi_len_y, bottom_right_z]
)

Extracted region of interest: baby elephant

获取与图像大小相同的 ROI 的 bool 掩码

roi_mask = tf.ones_like(roi_slice)
mask_canvas = tf.image.pad_to_bounding_box(
[roi_mask],
top_left_x,
top_left_y,
np_image.shape[0],
np_image.shape[1]
)
bool_mask = tf.cast(mask_canvas, tf.bool)

Mask of ROI

(b) 出于本示例的目的,我使用了假渐变,但您可以替换为您的真实渐变。

fake_gradients = tf.ones_like(image_in) * 0.2

(c) Mask the gradients,得到ROI所在的梯度,否则为0。

masked_gradients = tf.where(bool_mask[0], fake_gradients, mask_canvas[0])

(d) 制作图像的可编辑副本并使用蒙版渐变更新它

# Make an editable copy of the image
editable_image = tf.get_variable(
name='editable_image', shape=image_in.shape, dtype=tf.float32)
init_op = tf.assign(editable_image, image_in)

# Make sure we don't update the image before we've set its initial value.
with tf.control_dependencies([init_op]):
update_roi_op = tf.assign_add(editable_image, masked_gradients)

Highlighted ROI

您可以找到一个完整的 Colab 示例 on GitHub .

关于python - 将图像编辑为 tensorflow 张量 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51698848/

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