opencv python播放視頻和保存視頻

# -*- coding: utf-8 -*-

import numpy as np
import cv2

def playVideo(videoFile):
	cap = cv2.VideoCapture(videoFile)
	if cap.isOpened():
		print("Open ", videoFile, " success!")
	else:
		print("Open ", videoFile, " failed!")
		return
	#print(cap) # print cap address
	
	# cap.get(propId) 來獲得視頻的一些參數信息
	print("fps: ", cap.get(cv2.CAP_PROP_FPS))
	print("frame counts: ", cap.get(cv2.CAP_PROP_FRAME_COUNT))
	print("frame width: ", cap.get(cv2.CAP_PROP_FRAME_WIDTH))
	print("frame hight: ", cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
	
	#  cap.set(propId,value) 來修改
	
	while True:
		# Capture frame-by-frame
		ret, frame = cap.read()
		
		# cap.read() get a frame, if ret = false then frame is empty
		if not ret:
			break
		
		# Our operations on the frame come here
		gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
		
		# Display the resulting frame
		cv2.imshow(videoFile, frame)
		cv2.imshow('frame',gray)
		
        # q or ESC to exit
		if cv2.waitKey(1) & 0xFF == ord('q') or cv2.waitKey(1) & 0xFF == 27:
			break;
	
	# When everything done, release the capture
	cap.release()
	cv2.destroyAllWindows()

# 確保已經裝了合適版本的 ffmpeg 或者 gstreamer
def saveVideo(videoFile):
	cap = cv2.VideoCapture(videoFile)
	if cap.isOpened():
		print("Open ", videoFile, " success!")
	else:
		print("Open ", videoFile, " failed!")
		return
	#print(cap) # print cap address

	width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
	height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
	# cap.get(propId) 來獲得視頻的一些參數信息
	print("fps: ", cap.get(cv2.CAP_PROP_FPS))
	print("frame counts: ", cap.get(cv2.CAP_PROP_FRAME_COUNT))
	print("frame width: ", width)
	print("frame hight: ", height)
	
	#  cap.set(propId,value) 來修改
	
	# Define the codec and create VideoWriter object
	# fourcc = cv2.VideoWriter_fourcc(*'XVID')
	fourcc = cv2.VideoWriter_fourcc(*'DIVX')
	out = cv2.VideoWriter('output.avi', fourcc, 20.0, (int(width),int(height)))
	if out.isOpened():
		print("Create output video success!")
	else:
		print("Create output video failed!")
	
	while cap.isOpened():
		# Capture frame-by-frame
		ret, frame = cap.read()
		
		# cap.read() get a frame, if ret = false then frame is empty
		if not ret:
			break
		
		# 上下翻轉
		# frame = cv2.flip(frame,0)
		
		# 左右翻轉
		frame = cv2.flip(frame,1)
		
		# write the flipped frame
		out.write(frame)
		
		cv2.imshow("frame", frame)
		if cv2.waitKey(1) & 0xFF == ord('q'):
			break;
	
	# When everything done, release the capture
	cap.release()
	out.release()
	cv2.destroyAllWindows()
	
def main():
	#videoFile = 0
	#videoFile = "F:\\dataSet\\video.avi"
	videoFile = "F:\\dataSet\\opencv33.mp4"
	#playVideo(videoFile)
	saveVideo(videoFile)

if __name__ == '__main__':
	main()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章