这是 Vince Gatto 提出的方法的一个小改进。我们可以tf.py_func用来避免创建额外的占位符和做额外的session.run.
首先,我们定义这些函数(你需要opencv-python安装):
import cv2
import tensorflow as tf
def put_text(imgs, texts):
result = np.empty_like(imgs)
for i in range(imgs.shape[0]):
text = texts[i]
if isinstance(text, bytes):
text = text.decode()
# You may need to adjust text size and position and size.
# If your images are in [0, 255] range replace (0, 0, 1) with (0, 0, 255)
result[i, :, :, :] = cv2.putText(imgs[i, :, :, :], str(text), (0, 30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 1), 2)
return result
def tf_put_text(imgs, texts):
return tf.py_func(put_text, [imgs, texts], Tout=imgs.dtype)
现在我们可以tf_put_text在顶部图像上打印标签,然后将它们提供给图像摘要:
annotated_images = tf_put_text(images, labels)
tf.summary.image('annotated_images', annotated_images, 4)