opencv+ffmpeg 實現(xiàn)屏幕錄制

這是一個被放棄的功能代碼,原因是由于在轉(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)用
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,228評論 3 119
  • 2018年最潮流的網(wǎng)賺項目店鋪淘客的新玩法分銷模式最先進的技術(shù) 我們應(yīng)該如何解決店鋪的違規(guī)售假乃至封店的問題呢? ...
    尛青蛙閱讀 239評論 0 0
  • 我在前 你在后 我們孤獨的牽著手 在這人間四月天
    水底的黑色瓶蓋閱讀 201評論 0 0
  • 王朝盛世夜北京, 闌珊燈火月照明。 華夏千秋定基業(yè), 國泰家安君圣明。柳 2018.5.30
    逸海飄云閱讀 627評論 8 24
  • 下課了,施嘉琪剛拿出象棋。坐在他前后的我和陳星睿不約而同地用目光“殺”向了那一盤象棋,又不約而同地說:“施...
    徐一軒_7bec閱讀 268評論 1 0

友情鏈接更多精彩內(nèi)容