opencv+ffmpeg 实现屏幕录制
程序员文章站
2022-05-16 14:18:03
...
这是一个被放弃的功能代码,原因是由于在转码的时候会有时间。opencv在抓取屏幕后视频编码后过大的问题,使用了ffmpeg来实现二次的转码。调用了命令行,转码的时间是这个项目无法接受的,所以决定要用C++去重新写一次了。在这里留一个这段代码的墓地。
- 代码如下
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import ImageGrab
import numpy as np
import cv2
import os
import times
import subprocess
# there ae path
original_path = r''
output_path = r''
class ScreenRecord():
""" there are some coding if you don't care the performance """]
def __init__(self):
self.startControl = False
time_now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtim(time.time()))
# because the file name should not be same, so we should change it
self.original_file = original_path + time_now + r'.mov'
self.output_file = output_path + time_now + r'.mp4'
def record(self):
# the core code for recording using opencv pillow and ffmpeg
try:
# I don't find a better way to stop it
print ("Ctrl + c to stop record")
screen = ImageGrab.grab()
length, width = screen.size
video_decode_style = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
video = cv2.VideoWriter(self.original_file, video_decode_style, 12, (length, width), True)
while self.startControl == False:
im = ImageGrab.grab()
imm = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)
video.write(imm)
except KeyboardInterrupt:
# release the buff
video.release()
cv2.destroyAllwindows()
# ffmpeg tanslate the file
command('ffmpeg.exe -i %s -b:v 400k -s 960x540 %s' % (self.original_file, self.output_file))
subprocess.call(commmand)
# if file is exsits, we will del it
if os.path.exists(self.original_file):
os.remove(self.original_file)
print ("finshed")
def start(self):
self.record()
if __name__ == '__main__':
ScreenRecord().start()
- 需要下载ffmpeg 并将bin/ffmpeg 放到文件的目录夹下面
- 在Windows环境可以运行
- 可以使用pyinstaller构建Windows 环境下的可执行文件
- 在完成后会有一段时间的转码时间
- C++ 可能会复杂点,但是有windows系统的API可以调用
上一篇: OpenCV获取视频文件时长
下一篇: java 屏幕录制