python - 将图像编辑为 tensorflow 张量 python
问题描述
我会尽我所能在这里提供一个可重现的例子。
我有一张图片:
Aaron Eckhart 的这张照片是(150, 150)
我的目标是通过对像素进行数学运算来扰乱此图像的 ROI,但是,问题是数学必须作为张量流张量来完成,因为要完成的数学运算是将张量乘以它的缩放梯度(这也是一个大小的张量 (row_pixels, column_pixels, 3))
所以这是我想象的过程:
读入图像为 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
使像素值介于 0 和 1 之间
img = (faces1 - min_pixel) / (max_pixel - min_pixel)
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 张量放回与原始张量相同的位置这是另一部分我不明白该怎么做
这将导致图像中只有一些像素值受到干扰,其余的保持不变
解决方案
给定一张图片:
(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)
(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 示例。
推荐阅读
- php - sqlstate 42s22 列未找到 1054“字段列表”中的未知列
- laravel - 需要从当前调用另一个控制器的功能吗?这是一个正确的方法吗?
- javascript - 我不能返回一个对象,除非花括号放在 return 语句旁边
- android - 在使用 RxJava 的绑定服务中与 UI 通信
- sql - 在sql中查询从xml中提取字符串
- c# - 为流数据类型准备 JSON 数据请求
- aws-amplify - 如何在放大初始化期间配置 AWS 配置文件的使用?
- google-natural-language - Google 自然语言 API - 错误:打开的文件过多
- wso2 - 使用 XACML 启用基于角色的访问控制 - 评估策略时出错
- python - imshow 和 pcolormesh 显示具有相同输入的两个不同输出