您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關opencv如何實現調用攝像頭并顯示,讀取視頻文件并顯示,保存視頻等操作,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
調用攝像頭,并顯示視頻:
import numpy as npimport cv2 as cv# cap = cv.VideoCapture(-1)# cap = cv.VideoCapture(1)cap = cv.VideoCapture(0) # 傳入一個設備索引,代表不同的攝像頭,或者傳入一個視頻文件名# cap = cv.VideoCapture('testVideo.mp4')if not cap.isOpened():print("Cannot open camera")exit()width = cap.get(cv.CAP_PROP_FRAME_WIDTH)height = cap.get(cv.CAP_PROP_FRAME_HEIGHT)print('寬度和高度分別是:', width, height) # 寬度和高度分別是: 640.0 480.0ret = cap.set(cv.CAP_PROP_FRAME_WIDTH,320) # 設定寬度ret = cap.set(cv.CAP_PROP_FRAME_HEIGHT,240) # 設定高度while True:# Capture frame-by-frameret, frame = cap.read() # 返回True或者False,如果讀取正確是True,可以用False來判斷是否到達視頻的末尾 # if frame is read correctly ret is Trueif not ret:print("Can't receive frame (stream end?). Exiting ...")break# Our operations on the frame come heregray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)# Display the resulting framecv.imshow('LinMaZi-frame-LinZuQuan', gray) # 設定顯示窗口標題文字if cv.waitKey(1) == ord('q'): # 判斷用戶是否輸入q鍵break# When everything done, release the capturecap.release() # 釋放資源cv.destroyAllWindows()
讀取視頻文件并顯示:
import numpy as npimport cv2 as cv cap = cv.VideoCapture('畢業晚會.MP4')# cap = cv.VideoCapture(0)while cap.isOpened():ret, frame = cap.read()# if frame is read correctly ret is Trueif not ret:print("Can't receive frame (stream end?). Exiting ...")breakgray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)cv.imshow('frame', gray)if cv.waitKey(25) == ord('q'): # 選擇合適的刷新時間間隔,25毫秒還不錯breakcap.release()cv.destroyAllWindows()
調用攝像頭并顯示,保存為視頻文件:
import numpy as npimport cv2 as cvimport time cap = cv.VideoCapture(0)# Define the codec and create VideoWriter objectfourcc = cv.VideoWriter_fourcc(*'XVID') # 兩者等效# fourcc = cv.VideoWriter_fourcc('X','V','I','D') # 兩者等效saveTime = time.strftime("%Yy-%mm-%dd@%Hh%Mm%Ss", time.localtime())out = cv.VideoWriter('output_' + saveTime + '.mp4', fourcc, 20.0, (640, 480)) # 參數說明 output file name, FourCC code, frames per second (fps), frame sizewhile cap.isOpened():ret, frame = cap.read()if not ret:print("Can't receive frame (stream end?). Exiting ...")break# frame = cv.flip(frame, 1) # 左右橫向翻轉frame = cv.flip(frame, 0) # 上下縱向翻轉# write the flipped frameout.write(frame)cv.imshow('LinMaZi-frame-LinZuQuan', frame)if cv.waitKey(1) == ord('q'):break# Release everything if job is finishedcap.release()out.release()cv.destroyAllWindows()
關于“opencv如何實現調用攝像頭并顯示,讀取視頻文件并顯示,保存視頻等操作”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。