首页 > 解决方案 > 将图像编辑为 tensorflow 张量 python

问题描述

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

我有一张图片:

在此处输入图像描述

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

我的目标是通过对像素进行数学运算来扰乱此图像的 ROI,但是,问题是数学必须作为张量流张量来完成,因为要完成的数学运算是将张量乘以它的缩放梯度(这也是一个大小的张量 (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. for i in range(steps):

(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 张量放回与原始张量相同的位置这是另一部分我不明白该怎么做

这将导致图像中只有一些像素值受到干扰,其余的保持不变

标签: pythontensorflowimage-processing

解决方案


给定一张图片:

全图:两只大象

(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]
)

提取的感兴趣区域:小象

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

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)

ROI 掩码

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

fake_gradients = tf.ones_like(image_in) * 0.2

(c) 屏蔽梯度,得到 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)

突出的投资回报率

您可以在 GitHub 上找到一个完整的 Colab 示例。


推荐阅读