由于需要对我开发别的软件进行使用培训,想到需要个录屏工具,于是用下面简单的几行代码便实现了屏幕录制。
需要安装的几个包是:
pip install numpy Matplotlib
pip install opencv-python
pip install Pillow(python3.x 这样安装; python2.x pip install PIL)
from PIL import ImageGrab
import numpy as np
import cv2
p = ImageGrab.grab()#获得当前屏幕
k=np.zeros((200,200),np.uint8)
a,b=p.size#获得当前屏幕的大小
fourcc = cv2.VideoWriter_fourcc(*'XVID')#编码格式
video = cv2.VideoWriter('test.avi', fourcc, 16, (a, b))#输出文件命名为test.mp4,帧率为16,可以自己设置
while True:
im = ImageGrab.grab()
imm=cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)#转为opencv的BGR格式 video.write(imm)
cv2.imshow('imm', k)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows()
这个demo是输入q退出。
但是总是不能正确的录制出视频文件,显示大小为0KB。最后发现是电脑上没有响应的视频解码库导致的。
将fourcc = cv2.VideoWriter_fourcc(*'XVID')#编码格式
改为 fourcc = cv2.VideoWriter_fourcc(*'MJPG')
FourCC 就是一个4 字节码,用来确定视频的编码格式。可用的编码列表
可以从fourcc.org查到。这是平台依赖的。下面这些编码器对我来说是有用个。
• In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is
more preferable. MJPG results in high size video. X264 gives
very small size video)
• In Windows: DIVX (More to be tested and added)
• In OSX : (I don’t have access to OSX. Can some one fill this?)
FourCC 码以下面的格式传给程序,以MJPG 为例:
cv2.cv.FOURCC('M','J','P','G') 或者cv2.cv.FOURCC(*'MJPG')。
录屏加录音的简单实现demo
import wave
from pyaudioimport PyAudio,paInt16
from PILimport ImageGrab
import numpyas np
import cv2
from moviepy.editorimport *
from moviepy.audio.fximport all
framerate=8000
NUM_SAMPLES=2000
channels=1
sampwidth=2
TIME=2
def save_wave_file(filename,data):
'''save the date to the wavfile'''
wf=wave.open(filename,'wb')
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes(b"".join(data))
wf.close()
def my_record():
pa=PyAudio()
stream=pa.open(format = paInt16,channels=1,
rate=framerate,input=True,
frames_per_buffer=NUM_SAMPLES)
my_buf=[]
p = ImageGrab.grab()# 获得当前屏幕
k = np.zeros((200, 200), np.uint8)
a, b = p.size# 获得当前屏幕的大小
# fourcc = cv2.VideoWriter_fourcc(*'XVID')#编码格式
# fourcc = cv2.VideoWriter_fourcc(*'MJPG')
fourcc = cv2.VideoWriter_fourcc(*'DIVX')# 编码格式
video = cv2.VideoWriter('test.avi', fourcc,3, (a, b))# 输出文件命名为test.mp4,帧率为16,可以自己设置
while True:
string_audio_data = stream.read(NUM_SAMPLES)
my_buf.append(string_audio_data)
im = ImageGrab.grab()
imm = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)# 转为opencv的BGR格式
video.write(imm)
cv2.imshow('wb', k)
# string_audio_data = stream.read(NUM_SAMPLES)
# my_buf.append(string_audio_data)
print('.')
if cv2.waitKey(1) &0xFF ==ord('q'):
break
# video.release()
# cv2.destroyAllWindows()
save_wave_file('01.wav',my_buf)
stream.close()
video.release()
cv2.destroyAllWindows()
if __name__ =='__main__':
my_record()
print('Over!')
audioclip = AudioFileClip("01.wav")
videoclip = VideoFileClip("test.avi")
videoclip2 = videoclip.set_audio(audioclip)
video = CompositeVideoClip([videoclip2])
video.write_videofile("test2.mp4",codec='mpeg4')