這是一個被放棄的功能代碼蚓土,原因是由于在轉(zhuǎn)碼的時候會有時間庞溜。opencv在抓取屏幕后視頻編碼后過大的問題,使用了ffmpeg來實現(xiàn)二次的轉(zhuǎn)碼丛晦。調(diào)用了命令行,轉(zhuǎn)碼的時間是這個項目無法接受的提陶,所以決定要用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環(huán)境可以運行
- 可以使用pyinstaller構(gòu)建Windows 環(huán)境下的可執(zhí)行文件
- 在完成后會有一段時間的轉(zhuǎn)碼時間
- C++ 可能會復(fù)雜點隙笆,但是有windows系統(tǒng)的API可以調(diào)用