最近做了个视频后处理的需求,记录下.
直接上完整代码
import cv2
import numpy
from flask import Flask, request
from PIL import Image, ImageDraw, ImageFont
app = Flask(__name__)
def cv2ImgAddText(img, text, left, top, text_color, text_size):
if isinstance(img, numpy.ndarray):
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
fontText = ImageFont.truetype("msjh.ttc", text_size, encoding="utf-8")
draw.text((left, top), text, text_color, font=fontText)
return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
@app.route('/')
def test():
return "ok"
@app.route('/addFrame')
def video():
x = request.args['x']
y = request.args['y']
str = request.args['str']
video_url = request.args['videoUrl']
video_id = request.args['videoId']
result_video = "/data/docker/%s.mp4" % video_id
cap = cv2.VideoCapture(video_url)
fps_video = cap.get(cv2.CAP_PROP_FPS)
video_fourcc = cv2.VideoWriter_fourcc(*"mp4v")
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
video_writer = cv2.VideoWriter(result_video, video_fourcc, fps_video, (frame_width, frame_height))
num = 1
while cap.isOpened():
ret, frame = cap.read()
num = num + 1
if ret:
if num % 5 == 0:
left_x_up = int(x)
left_y_up = int(y)
right_x_down = int(left_x_up + 150)
right_y_down = int(left_y_up + 150)
word_x = left_x_up - 20
word_y = left_y_up - 50
cv2.rectangle(frame, (left_x_up, left_y_up), (right_x_down, right_y_down), (55, 255, 155), 3)
frame = cv2ImgAddText(frame, str, word_x, word_y, (55, 255, 155), 40)
video_writer.write(frame)
else:
video_writer.release()
break
return result_video
if __name__ == '__main__':
app.run(host="0.0.0.0")
主要用到cv2的两个函数,
# cv2.rectangle(图像, (矩形左上角坐标), (矩形右下角坐标), (矩形颜色), 线条粗细)
cv2.rectangle(frame, (left_x_up, left_y_up), (right_x_down, right_y_down), (55, 255, 155), 3)
这个不支持中文,中文会乱码???
# cv2.putText(图像, 要写入的内容, (文字坐标), 字体, 字号, (字体颜色), 字体粗细)
cv2.putText(frame, 'frame_%s' %frame_id, (word_x, word_y), cv2.FONT_HERSHEY_SIMPLEX, 1, (55,255,155), 2)
用网友封装的cv2ImgAddText(img, text, left, top, text_color, text_size)可以支持中文,具体可以看最后的文章链接.
感谢:
https://www.cnblogs.com/zhenglisai/p/9888096.html
https://www.cnblogs.com/vipstone/p/8998249.html(解决opecv汉字乱码)