由於畢業設計涉及到對視頻的幀處理,所以需要學習一個python的庫來實現對視頻的處理
一、安裝
pip3 install opencv-python
二、讀取圖片
import cv2 img=cv2.imread("/Users/zixiluo/Documents/test.png")#讀取圖片 cv2.imshow("image",img)#打開一個名為“image”的窗口並展示圖片 cv2.waitKey(0)#不加這句窗口會一閃就關閉 cv2.destroyAllWindows()#使用后釋放窗口是好習慣
三、讀取視頻
import cv2 cap=cv2.VideoCapture("/Users/zixiluo/Documents/test.avi") while(1): # get a frame ret, frame = cap.read() # show a frame cv2.imshow("capture", frame) if cv2.waitKey(100) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
四、獲取視頻屬性
print ("W:{}".format(cap.get(3)))#輸出視頻的寬度 print ("H:{}".format(cap.get(4)))#輸出視頻的高度 print ("frames:{}".format(cap.get(7)))#輸出視頻的總幀數
運行結果:
W:1920.0
H:1080.0
frames:912.0
get方法參數按順序對應下表(從0開始編號
propId –
Property identifier. It can be one of the following:
- CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds or video capture timestamp.
- CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.
- CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of the film, 1 - end of the film.
- CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.
- CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.
- CV_CAP_PROP_FPS Frame rate.
- CV_CAP_PROP_FOURCC 4-character code of codec.
- CV_CAP_PROP_FRAME_COUNT Number of frames in the video file.
- CV_CAP_PROP_FORMAT Format of the Mat objects returned by
retrieve()
. - CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode.
- CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).
- CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras).
- CV_CAP_PROP_SATURATION Saturation of the image (only for cameras).
- CV_CAP_PROP_HUE Hue of the image (only for cameras).
- CV_CAP_PROP_GAIN Gain of the image (only for cameras).
- CV_CAP_PROP_EXPOSURE Exposure (only for cameras).
- CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.
- CV_CAP_PROP_WHITE_BALANCE_U The U value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently)
- CV_CAP_PROP_WHITE_BALANCE_V The V value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently)
- CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
- CV_CAP_PROP_ISO_SPEED The ISO speed of the camera (note: only supported by DC1394 v 2.x backend currently)
- CV_CAP_PROP_BUFFERSIZE Amount of frames stored in internal buffer memory (note: only supported by DC1394 v 2.x backend currently)
五、抽幀顯示
import cv2 cap=cv2.VideoCapture("/Users/zixiluo/Documents/test.avi") print ("W:{}".format(cap.get(3))) print ("H:{}".format(cap.get(4))) count=cap.get(7) while(count>0): ret, frame = cap.read() if count%5==0: print(count) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow("capture", gray) if cv2.waitKey(1) & 0xFF == ord('q'): break count+=-1 cap.release() cv2.destroyAllWindows()
此程序實現每讀取五幀顯示一幀