Skip to content

下载安装

bash
pip install opencv-python
pip install opencv-python==4.9.0.80
# pip install -i https://pypi.doubanio.com/simple/ opencv-python 备用地址

Python调用摄像头

python
import cv2
import numpy

cap = cv2.VideoCapture(0) # 调整参数实现读取视频或调用摄像头

while 1:
    ret, frame = cap.read()
    cv2.imshow("cap", frame)
    if cv2.waitKey(100) & 0xff == ord('q'):
        break
cv2.imwrite("cap", frame)
cap.release()
cv2.destroyAllWindows()

see also:CV之OpenCV:Python下OpenCV的简介、安装、使用方法(常见函数、方法等)最强详细攻略

录制视频

录制AVI视频

python
from PIL import ImageGrab
import cv2
import numpy as np


p = ImageGrab.grab()  # 获得当前屏幕信息
width, height = p.size
print(width, height)
# 录屏文件的编码格式
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# 输出文件命名为test.avi,位置在E盘根目录,帧率为60,可以自己设置
video = cv2.VideoWriter('./test.avi', fourcc, 60, (width, height))


while 1:
    # 获取当前屏幕信息和入口等(每次运行到这里才能获取一帧画面)
    img = ImageGrab.grab()
	# 转为opencv的BGR格式
    img_bgr = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
	# 写入缓存
    video.write(img_bgr)
    # cv2.imshow('img_bgr', img_bgr)
# 释放
video.release()
cv2.destroyAllWindows()

录制MP4格式视频

下面的示例,录制大约5秒钟左右的MP4视频。

python
import cv2
import numpy as np
from PIL import ImageGrab
from threading import Thread

a = False

def f2():
    p = ImageGrab.grab()  # 获得当前屏幕信息
    width, height = p.size
    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
    video = cv2.VideoWriter('./test.mp4', fourcc, 8, (width, height), True)
    while 1:
        img = ImageGrab.grab()
        img_bgr = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
        video.write(img_bgr)
        if a:
            break
    video.release()
def f3():
    global a
    import time
    time.sleep(3)
    a = True

if __name__ == '__main__':
    Thread(target=f3).start()
    f2()

但有个问题,在windows平台下,本地可以正常播放,但无法扔到前端播放。因为这么录制的是mpeg4编码格式的视频,而浏览器的video标签识别的是h264编码格式的视频。

所以,想要浏览器也能用,就要用到FFmpeg转编码格式了。

FFmpeg:https://www.cnblogs.com/Neeo/articles/11677715.html

完整示例

需要下载的库:

pip install numpy
pip install ffmpy3

代码:

python
import cv2
import numpy as np
from PIL import ImageGrab
from threading import Thread
import ffmpy3

a = False


def f1():
    ffmpy3.FFmpeg(inputs={'./test.mp4': None}, outputs={'test1.mp4': None}).run()


def f2():
    p = ImageGrab.grab()
    width, height = p.size
    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
	# 这里有点问题,帧数越大,感觉录制时间就越短,你可以根据自己的环境测试
    video = cv2.VideoWriter('./test.mp4', fourcc, 8, (width, height), True)
    while 1:
        img = ImageGrab.grab()
        img_bgr = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
        video.write(img_bgr)
        if a:
            break
    video.release()
    f1()

def f3():
    global a
    import time
    time.sleep(3)
    a = True


if __name__ == '__main__':
    Thread(target=f3).start()
    f2()

常见报错

TypeError: Expected Ptrcv::UMat for argument '%s'

在上面录制MP4视频的示例中,运行发现一个问题,执行会报错:

TypeError: Expected Ptr<cv::UMat> for argument '%s'

经过查询发现,可能由于版本不对:

Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.__version__
'4.1.1'

故要卸载重装一个低版本的:

pip uninstall opencv-python  # 卸载
pip install -i https://pypi.doubanio.com/simple/ opencv-python==3.4.2.16

see also:Python录屏(无声)