很遗憾,您没有展示您的任何试验,因此人们可以看到,您的结果是什么样子才能给人留下深刻印象,您认为什么“不好”。因此,当您提到存储为 NumPy 数组的图像时,OpenCV 可能是这里的一个选项。
我将遵循上述想法的组合:
- 生成一个与图像尺寸相同的空文本平面,并添加一个额外的 alpha 通道设置为
0(不可见)。
- 放置文本轮廓:所需的背景颜色(比如说黄色),粗细。
- 严重模糊整个文本平面,包括 Alpha 通道。所以,你得到了你的羽毛轮廓。
- 输入实际文本:所需的前景色(比如说黑色),正常粗细。
- 稍微模糊整个文本平面,只是为了平滑生成的文本。 (漂亮的文字不是 OpenCV 的强项之一!)
- 使用平面的 Alpha 通道通过图像和文本平面的线性组合生成输出。
这就是代码:
import cv2
import numpy as np
# Open image, Attention: OpenCV uses BGR ordering by default!
image = cv2.imread('path/your/image.png', cv2.IMREAD_COLOR)
# Set up text properties
loc = (250, 500)
text = 'You were the chosen one!'
c_fg = (0, 255, 255, 255)
c_bg = (0, 0, 0, 255)
# Initialize overlay text plane
overlay = np.zeros((image.shape[0], image.shape[1], 4), np.uint8)
# Put text outline, larger thickness, color of outline (here: black)
cv2.putText(overlay, text, loc, cv2.FONT_HERSHEY_COMPLEX, 1.0, c_bg, 9, cv2.LINE_AA)
# Blur text plane (including alpha channel): Heavy blur
overlay = cv2.GaussianBlur(overlay, (21, 21), sigmaX=10, sigmaY=10)
# Put text, normal thickness, color of overlay (here: yellow)
cv2.putText(overlay, text, loc, cv2.FONT_HERSHEY_COMPLEX, 1.0, c_fg, 2, cv2.LINE_AA)
# Blur text plane (inclusing alpha channel): Very slight blur
overlay = cv2.GaussianBlur(overlay, (3, 3), sigmaX=0.5, sigmaY=0.5)
# Add overlay text plane to image (channel by channel)
output = np.zeros(image.shape, np.uint8)
for i in np.arange(3):
output[:, :, i] = image[:, :, i] * ((255 - overlay[:, :, 3]) / 255) + overlay[:, :, i] * (overlay[:, :, 3] / 255)
cv2.imshow('output', output)
cv2.waitKey(0)
cv2.destroyAllWindows()
模糊的参数是手动设置的。不同的图片和文字大小需要进一步调整。
这是一个示例输出:
即使使用类似于图像背景的前景色,文本仍然是可读的 - 至少从我的角度来看:
那么,现在最大的问题是:这个结果被认为是“坏的”吗?
希望有帮助!