作业10:
在视频中显示随机大小的边框,在视频中显示随机大小的边框.
参考链接:
https://www.cnblogs.com/mfryf/p/4556007.html(Python生成随机数的方法)
随机整数:
>>> import random
>>> random.randint(0,99)
21
随机选取0到100间的偶数:
>>> import random
>>> random.randrange(0, 101, 2)
42
随机浮点数:
>>> import random
>>> random.random()
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881
答案:
import cv2 as cv
import numpy as np
import random
capture = cv.VideoCapture(0) # 创建一个VideoCapture对象
result_video = "result.mp4"
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) #获取视频帧率
# 获取视频宽度
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 = random.randint(1,641)
left_y_up = random.randint(1,481)
right_x_down = left_x_up+random.randint(1,640)
right_y_down = left_y_up-random.randint(1,480)
# 文字坐标
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()