简体   繁体   English

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

[英]How do I put text on image using cv2?

I'm trying to add the text before the time using cv2.我正在尝试在使用 cv2 的时间之前添加文本。 Is it possible to add not only time?是否可以不仅添加时间? If so, how can I do this?如果是这样,我该怎么做?

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)

If you alter the content of "text" in generate_image_with_text it will print it.如果您更改 generate_image_with_text 中“文本”的内容,它将打印它。 You can call putText with other parameters, say for an upper line (if you mean "above"? the time string?):您可以使用其他参数调用 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)

Either add it in that function or put it where it's needed.要么将其添加到 function 中,要么将其放在需要的地方。

If you mean "before" in time, then just check the time however you need and if < etc. call such an alternative text etc.如果您的意思是“之前”,那么只需检查您需要的时间,如果 < 等,请调用此类替代文本等。

Also, that code where you create a canvas makes a grayscale one (one channel) and all is white or gray;此外,您在其中创建 canvas 的代码会生成一个灰度(一个通道),并且全部为白色或灰色; it should be:它应该是:

def get_black_background():
    return np.zeros((500, 500, 3)) #3 channels in order to show colors

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM