opencv python播放视频和保存视频

10 篇文章 0 订阅
1 篇文章 0 订阅
# -*- 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()

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值