作业9:
在视频上添加logo
参考链接:
https://blog.csdn.net/san1156/article/details/76854307(OpenCV图像处理--为图像添加Logo)
%s 字符串 (采用str()的显示)
%r 字符串 (采用repr()的显示)
%c 单个字符
%b 二进制整数
%d 十进制整数
%i 十进制整数
%o 八进制整数
%x 十六进制整数
%e 指数 (基底写为e)
%E 指数 (基底写为E)
%f 浮点数
%F 浮点数,与上相同
%g 指数(e)或浮点数 (根据显示长度)
%G 指数(E)或浮点数 (根据显示长度)
%% 字符"%"
答案:
import cv2 as cv
import numpy as np
capture = cv.VideoCapture(0) # 创建一个VideoCapture对象
result_video = "result.mp4"
img_logo = cv.imread("ali-movie.png", cv.IMREAD_COLOR)
img_logo = cv.resize(img_logo, (0, 0), fx=0.2, fy=0.2, interpolation=cv.INTER_NEAREST)
img_logo_gray = cv.cvtColor(img_logo, cv.COLOR_BGR2GRAY)
ret, img_logo_mask = cv.threshold(img_logo_gray, 200, 255, cv.THRESH_BINARY) # 二值化函数
img_logo_mask1 = cv.bitwise_not(img_logo_mask)
while(True):
ret, frame = capture.read() # 一帧一帧读取视频
#gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # 对每一帧做处理,设置为灰度图
# 设置写入视频的编码格式
fourcc = cv.VideoWriter_fourcc(*"mp4v")
fps_video = capture.get(cv.CAP_PROP_FPS) #获取视频帧率
# 获取视频宽度
rows, cols, channel = img_logo.shape
rows1, cols1, channel1 = frame.shape
img_roi = frame[:rows, cols1 - cols:cols1].copy()
img_res0 = cv.bitwise_and(img_roi, img_roi, mask=img_logo_mask)
img_res1 = cv.bitwise_and(img_logo, img_logo, mask=img_logo_mask1)
img_res2 = cv.add(img_res0, img_res1)
# img_res2 = img_res0 + img_res1
frame[:rows, cols1 - cols:cols1] = img_res2[:, :]
frame_width = int(capture.get(cv.CAP_PROP_FRAME_WIDTH))
# 获取视频高度
frame_height = int(capture.get(cv.CAP_PROP_FRAME_HEIGHT))
videoWriter = cv.VideoWriter(result_video, fourcc, fps_video, (frame_width, frame_height))
frame += 1
#left_x_up = int(369)
#left_y_up = int(328)
#right_x_down = int(469)
#right_y_down = int(200)
# 文字坐标
#word_x = 369
#word_y = 328
#cv.rectangle(frame, (left_x_up, left_y_up), (right_x_down, right_y_down), (55, 255, 155), 5)
#cv.putText(frame, 'frame_%s' % frame, (word_x, word_y), cv.FONT_HERSHEY_SIMPLEX, 1, (55, 255, 155), 2)
videoWriter.write(frame)
cv.imshow('frame ', frame) # 显示结果
if cv.waitKey(1) &0xFF == ord('q'): # 按q停止
break
capture.release() # 释放cap,销毁窗口
cv.destroyAllWindows()