【问题标题】:Opencv How to Overlay Text on VideoOpencv如何在视频上叠加文本
【发布时间】:2019-07-03 13:59:48
【问题描述】:

我想添加一些文本以显示在我的网络摄像头的视频上,但我似乎无法理解。我之前使用 Opencv 向图像添加了文本,但视频的方法似乎不同,所以我将如何去做。这是我的网络摄像头脚本:

import cv2
import numpy as np

# Create a VideoCapture object and read from input file
# If the input is the camera, pass 0 instead of the video file name
cap = cv2.VideoCapture(0)

# Check if camera opened successfully
if (cap.isOpened()== False): 
  print("Error opening video stream or file")

# Read until video is completed
while(cap.isOpened()):
  # Capture frame-by-frame
  ret, frame = cap.read()
  if ret == True:

    # Display the resulting frame
    cv2.imshow('Frame',frame)

    # Press Q on keyboard to  exit
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break

  # Break the loop
  else: 
    break

# When everything done, release the video capture object
cap.release()

# Closes all the frames
cv2.destroyAllWindows()

【问题讨论】:

    标签: opencv video text overlay


    【解决方案1】:

    看看OpenCV's docs about putText。这是我为显示一些边界框标签所做的快速破解:

    @staticmethod
    def __draw_label(img, text, pos, bg_color):
        font_face = cv2.FONT_HERSHEY_SIMPLEX
        scale = 0.4
        color = (0, 0, 0)
        thickness = cv2.FILLED
        margin = 2
    
        txt_size = cv2.getTextSize(text, font_face, scale, thickness)
    
        end_x = pos[0] + txt_size[0][0] + margin
        end_y = pos[1] - txt_size[0][1] - margin
    
        cv2.rectangle(img, pos, (end_x, end_y), bg_color, thickness)
        cv2.putText(img, text, pos, font_face, scale, color, 1, cv2.LINE_AA)
    

    在您的代码中应该这样做:

    if ret == True:
    
        # draw the label into the frame
        __draw_label(frame, 'Hello World', (20,20), (255,0,0))
    
        # Display the resulting frame
        cv2.imshow('Frame',frame)
    

    您是否以某种方式您调用 imshow 之后进行了绘图?我看不出有什么理由说明视频的行为会有所不同。

    【讨论】:

    • 谢谢,这与我尝试的非常相似,不知道为什么它以前不起作用,但您的脚本运行良好且易于理解。
    • 按预期工作!关于如何将文本显示几秒钟的任何想法?
    • 那么只需引入一个计数器变量。将其设置在捕获循环之外的帧数,以显示标签。 counterVariable -=1 # 如果 counterVariable > 0: _drawLabel.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    相关资源
    最近更新 更多