python - 如何使用 TensorFlow 操作排除图像圆圈之外的所有值?
问题描述
这就是我的意思:使用以下代码,我可以让圆外的值变为 0。代码生成全白图像并将圆外的值设置为零。
import numpy as np
import matplotlib.pyplot as plt
width = 512
all_white_img = np.zeros(shape=[width, width], dtype=np.float)
all_white_img[:] = 1
plt.imshow(all_white_img, cmap='gray', vmax=1.0, vmin=0.0)
plt.show()
[X, Y] = np.mgrid[0:width, 0:width]
xpr = X - int(width) // 2
ypr = Y - int(width) // 2
radius = width // 2
reconstruction_circle = (xpr ** 2 + ypr ** 2) <= radius ** 2 #set circle
all_white_img[~reconstruction_circle] = 0.
plt.imshow(all_white_img, cmap='gray', vmax=1.0, vmin=0.0)
plt.show()
如何有效地使用 TensorFlow 做同样的事情?
因为 numpy 在 CPU 上运行,我需要能够在 GPU 上运行的东西。
该代码只是一个示例,我需要一些不仅适用于圆形而且适用于任何其他形状的东西。
谢谢!
解决方案
该tf.where
功能完全符合我的要求。
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
width = 512
sess = tf.Session()
[X, Y] = np.mgrid[0:width, 0:width]
xpr = X - int(width) // 2
ypr = Y - int(width) // 2
radius = width // 2
reconstruction_circle = (xpr ** 2 + ypr ** 2) <= radius ** 2 #set circle
all_white_img = tf.ones(shape=[width, width], dtype=tf.float32)
plt.imshow(sess.run(all_white_img), cmap='gray', vmax=1.0, vmin=0.0)
plt.show()
reconstruction_circle = tf.cast(reconstruction_circle, tf.bool)
all_white_img = tf.where(reconstruction_circle, all_white_img, tf.zeros_like(all_white_img))
plt.imshow(sess.run(all_white_img), cmap='gray', vmax=1.0, vmin=0.0)
plt.show()
推荐阅读
- c# - 哪个对象用于在内存中对有间隙的查找数据进行排序
- string - 错误“在抛出 'std::length_error' what(): basic_string::_S_create 的实例后调用终止”
- postgresql - 根据数组条件计算平均值
- javascript - 将循环结构转换为 JSON axios 错误
- python - Python:如何删除此“SettingWithCopyWarning(数据框)?
- angular - 无法设置未定义角度的属性“xxxx”
- linux - 使用 ldapsearch 请求 sshPublicKey 失败
- android - How can i get InputConnection in WebView?
- php - Data eager loading in doctrine mongodb
- python - How can I replace the variables by floats in the equations using python