opencv+ffmpeg 实现屏幕录制

这是一个被放弃的功能代码,原因是由于在转码的时候会有时间。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可以调用
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,023评论 3 119
  • 2018年最潮流的网赚项目店铺淘客的新玩法分销模式最先进的技术 我们应该如何解决店铺的违规售假乃至封店的问题呢? ...
    尛青蛙阅读 233评论 0 0
  • 我在前 你在后 我们孤独的牵着手 在这人间四月天
    水底的黑色瓶盖阅读 184评论 0 0
  • 王朝盛世夜北京, 阑珊灯火月照明。 华夏千秋定基业, 国泰家安君圣明。柳 2018.5.30
    逸海飘云阅读 619评论 8 24
  • 下课了,施嘉琪刚拿出象棋。坐在他前后的我和陈星睿不约而同地用目光“杀”向了那一盘象棋,又不约而同地说:“施...
    徐一轩_7bec阅读 245评论 1 0