如何使用 cv2 在图像上放置文字?

问题描述

我正在尝试使用 cv2 在时间之前添加文本。是否可以不仅添加时间?如果是这样,我该怎么做?

from utils import *
import cv2
import numpy as np
from datetime import datetime,timedelta

def get_black_background():
    return np.zeros((500,500))


start_time = datetime.strptime("2021-01-01","%Y-%m-%d")
end_time = start_time + timedelta(days=1)


def generate_image_with_text(text):
    image = get_black_background()
    font = cv2.FONT_HERShey_SIMPLEX
    cv2.putText(image,text,(int(image.shape[0]*0.35),int(image.shape[1]*0.5)),font,1.5,(255,255,0),2,cv2.LINE_AA)
    return image
    

while start_time < end_time:
    text = convert_time_to_string(start_time)
    image = generate_image_with_text(text)
    cv2.imwrite(f"time_images/{text}.jpg",image)
    start_time += timedelta(minutes=1)

解决方法

如果您在 generate_image_with_text 中更改“text”的内容,它将打印它。 您可以使用其他参数调用 putText,比如上一行(如果您的意思是“上面”?时间字符串?):

~[\]\\]

要么将其添加到该函数中,要么将其放在需要的地方。

如果你的意思是“之前”时间,那么只需检查你需要的时间,如果

此外,您创建画布的代码使灰度成为一个(一个通道),并且全部为白色或灰色;应该是:

beforeTime = "Before Caption![![enter image description here][1]][1]"
upperLineX =  (int(image.shape[0]*0.25) #Adjust multipliers etc. 
upperLineY = (int(image.shape[1]*[![enter image description here][1]][1]0.35)) 
cv2.putText(image,text,(int(image.shape[0]*0.35),int(image.shape[1]*0.5)),font,1.5,(255,255,0),2,cv2.LINE_AA)