代码之家  ›  专栏  ›  技术社区  ›  conv3d

将图像编辑为tensorflow tensor python

  •  7
  • conv3d  · 技术社区  · 7 年前

    我将尽我所能在这里提供一个可复制的例子。

    我有一个形象:

    enter image description here

    这张亚伦·埃克哈特的照片 (150, 150)

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

    我想象的过程是这样的:

    1. 以numpy数组RGB大小读入图像:(1150150,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)提取图像的感兴趣区域 这是我不明白该怎么做的部分

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

    这将导致图像中只有部分像素值被扰动,其余的保持不变

    1 回复  |  直到 7 年前
        1
  •  5
  •   kempy    7 年前

    给定图像:

    Full image: two elephants

    (a)从图像中获取感兴趣的区域((440240),(5353380)):

    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的布尔掩码

    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)屏蔽梯度,以获得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 .