返回
import cv2
cap = cv2.VideoCapture("video/test.mp4")
FPS_show = True # 当前帧是否展示
cv2.namedWindow("video", 0)
# cv2.resizeWindow("video", int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(cap.get(cv2.CAP_PROP_FPS))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('video/watermark_output.avi', fourcc, fps, (frame_width, frame_height))
class WaterText:
text = None # 文字
position = None # 位置
font = None # 字体
font_scale = None # 文本大小
font_color = None # 颜色
font_thickness = None
def __init__(self, img):
self.img = img
def draw(self):
cv2.putText(self.img, WaterText.text, WaterText.position, WaterText.font, WaterText.font_scale,
WaterText.font_color, WaterText.font_thickness)
# 循环读取视频帧
while True:
ret, frame = cap.read() # ret 表示是否成功读取,frame 是帧数据
if not ret: # 读取失败或视频结束
print("Video has ended or cannot be read.")
break
if FPS_show:
cv2.createTrackbar("x", "video", 0, frame.shape[0], lambda x: x)
cv2.createTrackbar("y", "video", 0, frame.shape[1], lambda x: x)
while True:
x = cv2.getTrackbarPos("x", "video")
y = cv2.getTrackbarPos("y", "video")
video_copy = frame.copy()
WaterText.text = "Watermark"
WaterText.position = (y, x)
WaterText.font = cv2.FONT_HERSHEY_TRIPLEX
WaterText.font_scale = 1.5
WaterText.font_color = (255, 255, 255)
WaterText.font_thickness = 2
WaterText(video_copy).draw()
cv2.imshow('video', video_copy)
if cv2.waitKey(1) & 0xFF == 27: # esc
break
FPS_show = False
cv2.destroyWindow("video")
# continue # 打开则跳过首帧显示
WaterText(frame).draw()
cv2.imshow("video", frame)
out.write(frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()