opencv-python視頻處理之錄製視頻

錄製一段視頻保存java

import cv2# 建立一個視頻窗口cv2.namedWindow('Video')# cv2.VideoCapture(0)打開攝像頭video_capture = cv2.VideoCapture(0)video_writer = cv2.VideoWriter('test.avi',cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'),video_capture.get(cv2.CAP_PROP_FPS),(int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH)),int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))))# cv2.VideoWriter 分別傳入的參數是路徑 格式,幀率,視頻尺寸success,frame = video_capture.read()# 成功打開攝像頭 直到按esc退出保存視頻while success and not cv2.waitKey(1) == 27:blur_frame = cv2.GaussianBlur(frame[:,::-1], (3,3),0)video_writer.write(blur_frame)cv2.imshow("Video", blur_frame)success, frame = video_capture.read()cv2.destroyWindow('Video')video_capture.release()if __name__ == '__main__':pass

下面是錄製帶有聲音的視頻ide

import wavefrom pyaudio import PyAudio,paInt16from PIL import ImageGrabimport numpy as npimport cv2from moviepy.editor import *from moviepy.audio.fx import allimport time

CHUNK = 1024FORMAT = pyaudio.paInt16
CHANNELS = 2RATE = 44100WAVE_OUTPUT_FILENAME = "output.wav"p = pyaudio.PyAudio()wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')wf.setnchannels(CHANNELS)wf.setsampwidth(p.get_sample_size(FORMAT))wf.setframerate(RATE)audio_record_flag = Truedef callback(in_data, frame_count, time_info, status):wf.writeframes(in_data)if audio_record_flag:return (in_data, pyaudio.paContinue)else:return (in_data, pyaudio.paComplete)stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),input=True,stream_callback=callback)image = ImageGrab.grab()#得到當前屏幕width = image.size[0]height = image.size[1]print("width:", width, "height:", height)print("image mode:",image.mode)k=np.zeros((width,height),np.uint8)fourcc = cv2.VideoWriter_fourcc(*'XVID')#編碼格式video = cv2.VideoWriter('test.mp4', fourcc, 9.5, (width, height))#經實際測試,單線程下最高幀率爲10幀/秒,且會變更,所以選擇9.5幀/秒#若設置幀率與實際幀率不一致,會致使視頻時間與音頻時間不一致print("video recording!!!!!")stream.start_stream()print("audio recording!!!!!")record_count = 0while True:img_rgb = ImageGrab.grab()img_bgr=cv2.cvtColor(np.array(img_rgb), cv2.COLOR_RGB2BGR)#轉爲opencv的BGR格式video.write(img_bgr)record_count += 1if(record_count > 200):breakprint(record_count, time.time())audio_record_flag = Falsewhile stream.is_active():time.sleep(1)stream.stop_stream()stream.close()wf.close()p.terminate()print("audio recording done!!!!!")video.release()cv2.destroyAllWindows()print("video recording done!!!!!")print("video audio merge!!!!!")audioclip = AudioFileClip("output.wav")videoclip = VideoFileClip("test.mp4")videoclip2 = videoclip.set_audio(audioclip)video = CompositeVideoClip([videoclip2])video.write_videofile("test2.mp4",codec='mpeg4')————————————————
版權聲明:本文爲CSDN博主「luke-skyworker」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連接及本聲明。
原文連接:https://blog.csdn.net/zhaoyun_zzz/java/article/details/84341801
相關文章
相關標籤/搜索