Python使用CV2庫(kù)捕獲和保存攝像頭視頻
關(guān)于cv2庫(kù)的安裝和使用基礎(chǔ)可參見(jiàn)https://blog.csdn.net/cnds123/article/details/126547307
特別提示:CV2指的是OpenCV2(Open Source Computer Vision Library),安裝的時(shí)候是 opencv_python,但在導(dǎo)入的時(shí)候采用 import cv2。
學(xué)習(xí)本文需要你的計(jì)算機(jī)有攝像頭,筆記本一般內(nèi)置有攝像頭,若是臺(tái)式機(jī)可以連接一個(gè)USB攝像頭。
捕獲視頻幀
使用 OpenCV 可以捕獲攝像頭輸出的視頻流,并且可以對(duì)每一幀視頻進(jìn)行處理。下面是一個(gè)簡(jiǎn)單的示例代碼,演示如何從攝像頭中捕獲視頻幀并顯示到屏幕上:
import cv2
#定義cv2.VideoCapture 類(lèi)型的對(duì)象
cap = cv2.VideoCapture(0)
#isOpened() 用來(lái)判斷是否捕獲到視頻
if not cap.isOpened():
print("無(wú)法打攝像機(jī)")
exit()
while True:
# 如果正確讀取幀,ret為T(mén)rue,cap.read() 方法從攝像頭中讀取一幀視頻
ret, frame = cap.read()
if not ret:
break
# 顯示幀視頻
cv2.imshow('frame', frame)
# 按 'q' 鍵退出程序
if cv2.waitKey(1) == ord('q'):
break
# 釋放攝像頭并關(guān)閉所有窗口
cap.release()
cv2.destroyAllWindows()
說(shuō)明,VideoCapture 對(duì)象傳入了參數(shù) 0,表示設(shè)備索引,設(shè)備索引就是指定哪個(gè)攝像頭的數(shù)字。正常情況下,一個(gè)攝像頭會(huì)被連接(就像我的情況一樣)。所以我簡(jiǎn)單地傳0。你可以通過(guò)傳遞1來(lái)選擇第二個(gè)相機(jī),以此類(lèi)推。
運(yùn)行效果如下:
捕獲視頻幀保存
把視頻保存到本地,可以使用cv2.VideoWriter()方法,需要設(shè)置輸出視頻的文件名、編解碼器、幀速率和幀大小等參數(shù)。VideoWriter() 有5個(gè)參數(shù):
參數(shù)1:輸出文件名,例如: d:/output.mp4。
參數(shù)2:FourCC 代碼,F(xiàn)ourCC 是用于指定視頻編解碼器的4字節(jié)代碼。
參數(shù)3:幀率的數(shù)量。
參數(shù)4:幀大小。
參數(shù)5:顏色標(biāo)志。如果為 True,正常顏色輸出,否則就是灰色圖像輸出。
VideoWriter_fourcc()編碼方法,常見(jiàn)的視頻格式參數(shù):
cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
MPEG-4編碼 .mp4 可指定結(jié)果視頻的大小
cv2.VideoWriter_fourcc('X','2','6','4')
MPEG-4編碼 .mp4 可指定結(jié)果視頻的大小
cv2.VideoWriter_fourcc('I', '4', '2', '0')
該參數(shù)是YUV編碼類(lèi)型,文件名后綴為.avi 廣泛兼容,但會(huì)產(chǎn)生大文件
cv2.VideoWriter_fourcc('P', 'I', 'M', 'I')
該參數(shù)是MPEG-1編碼類(lèi)型,文件名后綴為.avi
cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
該參數(shù)是MPEG-4編碼類(lèi)型,文件名后綴為.avi,可指定結(jié)果視頻的大小
cv2.VideoWriter_fourcc('T', 'H', 'E', 'O')
該參數(shù)是Ogg Vorbis,文件名后綴為.ogv
cv2.VideoWriter_fourcc('F', 'L', 'V', '1')
該參數(shù)是Flash視頻,文件名后綴為.flv
下面是一個(gè)簡(jiǎn)單的例子:
import cv2
# 打開(kāi)攝像頭
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("無(wú)法打攝像機(jī)")
exit()
# 設(shè)置輸出視頻的參數(shù)
fourcc = cv2.VideoWriter_fourcc(*'MP4V') # 其中*'MP4V'和 'M', 'P', '4', 'V'等效
out = cv2.VideoWriter('d:/output.mp4', fourcc, 20.0, (640, 480))
while True:
# 讀取視頻幀
ret, frame = cap.read()
if not ret:
break
# 顯示視頻幀——播放視頻
cv2.imshow('frame',frame)
# 將視頻幀寫(xiě)入輸出視頻
out.write(frame)
# 按 'q' 鍵退出循環(huán)
if cv2.waitKey(1) == ord('q'):
break
# 釋放資源
cap.release()
out.release()
cv2.destroyAllWindows()
運(yùn)行后,將在你指定的路徑產(chǎn)生找到生成的文件,我這里是d:/output.mp4。
最后,給出一個(gè)Python使用CV2庫(kù)捕獲攝像頭視頻,并使用tkinter做界面含有“抓拍”、“開(kāi)始錄制”、“停止錄制”按鈕的例子,
?源碼如下:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-571234.html
import cv2
import tkinter as tk
from PIL import Image, ImageTk
# 創(chuàng)建主窗口
root = tk.Tk()
root.title("Camera App")
# 創(chuàng)建畫(huà)布,用于顯示視頻幀
canvas = tk.Canvas(root, width=640, height=480)
canvas.pack()
# 創(chuàng)建按鈕框架
button_frame = tk.Frame(root)
button_frame.pack(pady=10)
# 拍照函數(shù)
def take_snapshot():
ret, frame = cap.read() # 讀取當(dāng)前幀
if ret:
cv2.imwrite("snapshot.jpg", frame) # 保存為圖片名稱(chēng)snapshot.jpg
print("Snapshot taken!")
# 開(kāi)始錄像函數(shù)
def start_recording():
global is_recording, out
ret, frame = cap.read() # 讀取當(dāng)前幀
if ret:
height, width, channels = frame.shape
fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter("recording.avi", fourcc, 20.0, (width, height)) # 創(chuàng)建VideoWriter對(duì)象,視頻名稱(chēng)recording.avi
is_recording = True
print("Recording started!")
# 停止錄像函數(shù)
def stop_recording():
global is_recording, out
is_recording = False
out.release() # 釋放VideoWriter對(duì)象
print("Recording stopped!")
# 創(chuàng)建按鈕
snapshot_btn = tk.Button(button_frame, text="抓拍", command=take_snapshot)
snapshot_btn.grid(row=0, column=0, padx=10)
start_btn = tk.Button(button_frame, text="開(kāi)始錄制", command=start_recording)
start_btn.grid(row=0, column=1, padx=10)
stop_btn = tk.Button(button_frame, text="停止錄制", command=stop_recording)
stop_btn.grid(row=0, column=2, padx=10)
# 打開(kāi)攝像頭
cap = cv2.VideoCapture(0)
is_recording = False
# 更新視頻幀函數(shù)
def update_frame():
global is_recording
ret, frame = cap.read() # 讀取當(dāng)前幀
if ret:
if is_recording:
out.write(frame) # 寫(xiě)入視頻幀
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # 將BGR轉(zhuǎn)換為RGB
img = Image.fromarray(frame) # 創(chuàng)建PIL圖像對(duì)象
img.thumbnail((640, 480)) # 縮放圖像大小以適應(yīng)畫(huà)布
img = ImageTk.PhotoImage(image=img) # 創(chuàng)建Tkinter圖像對(duì)象
canvas.create_image(0, 0, anchor=tk.NW, image=img) # 在畫(huà)布上顯示圖像
canvas.img = img # 保留對(duì)圖像的引用
root.after(10, update_frame) # 每10毫秒更新一次視頻幀
# 啟動(dòng)視頻幀更新
update_frame()
# 運(yùn)行主循環(huán)
root.mainloop()
注意抓拍到的圖片(名稱(chēng)snapshot.jpg)和錄制視頻(名稱(chēng)recording.avi)路徑和源碼在同一目錄中,,下次抓拍到的圖片和錄制視頻,會(huì)覆蓋前面的,你可以改進(jìn)之。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-571234.html
到了這里,關(guān)于Python使用CV2庫(kù)捕獲和保存攝像頭視頻的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!