Python+OpenCV 视频录制


导读:

在视频文件处理的过程中,需要使用OpenCV以及其他开源包中的工具,在GitHub上有很多优秀的项目以及开源的代码,学习他们的解决问题的思路以及源代码,对coding能力有很大帮助。因此,本文记录并总结了前辈的优秀成果,以供学习参考。

实例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/3/7 11:43
# @Author  : HaoWANG
# @Site    : 
# @File    : VideoWrite.py
# @Software: PyCharm

# 加载包
import math
import sys
import cv2

def main():
	# 初始化摄像头
	keep_processing = True;
	camera_to_use = 0;  # 0 if you have one camera, 1 or > 1 otherwise
	cap = cv2.VideoCapture(0)  # 定义视频捕获类cap
	windowName = "Live Video Capture and Write"  # 窗口名
	
	# opencv中视频录制需要借助VideoWriter对象, 将从VideoCapture 中读入图片,不断地写入到VideoWrite的数据流中。
	# 指定视频编解码方式为MJPG
	codec = cv2.VideoWriter_fourcc(*'MJPG')
	fps = 25.0  # 指定写入帧率为25
	frameSize = (640, 480)  # 指定窗口大小
	# # 创建 VideoWriter对象
	output = cv2.VideoWriter('VideoRecord.avi', codec, fps, frameSize)
	
	# 摄像头开启检测
	# error detection #
	if not (((len(sys.argv) == 2) and (cap.open(str(sys.argv[1]))))
	        or (cap.open(camera_to_use))):
		print("ERROR:No video file specified or camera connected.")
		return -1
	
	# Camera Is Open
	# create window by name (note flags for resizable or not)
	cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
	print("按键Q-结束视频录制")
	
	while (cap.isOpened()):
		
		# 00 if video file successfully open then read frame from video
		if (keep_processing):
			
			ret, frame = cap.read()  # 定义read对象ret和frame帧
			# start a timer (to see how long processing and display takes)
			start_t = cv2.getTickCount()
			
			# 不断的从VideoCapture 中读入图片,然后写入到VideoWrite的数据流中。
			output.write(frame)
			
			cv2.imshow(windowName, frame)  # display image
			
			# stop the timer and convert to ms. (to see how long processing and display takes)
			stop_t = ((cv2.getTickCount() - start_t) / cv2.getTickFrequency()) * 1000
			
			# 接收键盘停止指令
			# start the event loop - essential
			# wait 40ms or less depending on processing time taken (i.e. 1000ms / 25 fps = 40 ms)
			
			key = cv2.waitKey(max(2, 40 - int(math.ceil(stop_t)))) & 0xFF
			
			# It can also be set to detect specific key strokes by recording which key is pressed
			# e.g. if user presses "q" then exit
			
			if (key == ord('q')):
				print("Quit Process ")
				keep_processing = False
		else:
			break
	
	print("The display and video write tasks take {} ms".format(stop_t))
	
	# release the camera and close all windows
	# 资源释放,在录制结束后,我们要释放资源:
	# # 释放资源
	cap.release()
	output.release()
	cv2.destroyAllWindows()
# end main()

if __name__ == "__main__":
	main()

 

Python-Digital Image Processing or Computer Vision 开发框架

#####################################################################

# Example : <................................> processing from a video file
# specified on the command line (e.g. python FILE.py video_file) or from an
# attached web camera
# 视频图像处理流程框架
# 1. 加载包,cv2、numpy、sys等
# 2. 定义并初始化参数
# 3. 定义摄像头捕获类变量cap
# 4. 定义显示窗口
# 5. 常规检测:视频打开成功检测、窗口创建成功检测、文件可读取写入检测等
# 6. 计时并调用OpenCV库函数进行视频帧处理
# 7. 结束计时,将文件写入磁盘,关闭窗口回收资源
#####################################################################
# import packages

import math
import sys

import cv2

#####################################################################
# initialization

keep_processing = True;
camera_to_use = 0;  # 0 if you have one camera, 1 or > 1 otherwise

#####################################################################

# define video capture object

cap = cv2.VideoCapture();

# define display window name

windowName = "Live Camera Input";  # window name

# if command line arguments are provided try to read video_name
# otherwise default to capture from attached H/W camera

if (((len(sys.argv) == 2) and (cap.open(str(sys.argv[1]))))
        or (cap.open(camera_to_use))):

    # create window by name (note flags for resizable or not)

    cv2.namedWindow(windowName, cv2.WINDOW_NORMAL);

    while (keep_processing):
        # error detection #
        # 00 if video file successfully open then read frame from video

        if (cap.isOpened):
            ret, frame = cap.read();

        # start a timer (to see how long processing and display takes)

        start_t = cv2.getTickCount();

        # *******************************

        # *** do any processing here ****

        # *******************************

        # display image

        cv2.imshow(windowName, frame);

        # stop the timer and convert to ms. (to see how long processing and display takes)

        stop_t = ((cv2.getTickCount() - start_t) / cv2.getTickFrequency()) * 1000;

        # start the event loop - essential

        # cv2.waitKey() is a keyboard binding function (argument is the time in milliseconds).
        # It waits for specified milliseconds for any keyboard event.
        # If you press any key in that time, the program continues.
        # If 0 is passed, it waits indefinitely for a key stroke.
        # (bitwise and with 0xFF to extract least significant byte of multi-byte response)
        # here we use a wait time in ms. that takes account of processing time already used in the loop

        # wait 40ms or less depending on processing time taken (i.e. 1000ms / 25 fps = 40 ms)

        key = cv2.waitKey(max(2, 40 - int(math.ceil(stop_t)))) & 0xFF;

        # It can also be set to detect specific key strokes by recording which key is pressed

        # e.g. if user presses "x" then exit

        if (key == ord('x')):
            keep_processing = False;

    # close all windows

    cv2.destroyAllWindows()

else:
    print("No video file specified or camera connected.")

#####################################################################

致谢:GitHub

Toby Breckon tobybreckon

 oby Breckon is Professor in Computer Vision & Image Processing within the Department of Engineering & Department of Computer Science at Durham University, UK.

传送门https://github.com/tobybreckon/python-examples-ip

你可能感兴趣的:(OpenCV)