python opencv 学习笔记

目录

  • python opencv 学习笔记
  • 一.使用摄像头捕获视频并保存
  • 1.使用摄像头捕获视频并显示
  • 2.使用摄像头捕获视频并保存
  • 二、opencv按帧提取视频中的图片
  • 三、计算视频总帧数以及FPS


一.使用摄像头捕获视频并保存

1.使用摄像头捕获视频并显示

代码如下:

import cv2
cap = cv2.VideoCapture(0)         # 第一参数为0,代表使用的是电脑的内置摄像头,如果有多个可以输入1,2,3····
while(1):
    ret, frame = cap.read()       # read函数读取视频的某帧,并显示
    cv2.imshow("capture", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):   # 等待1个单位时间,如果期间检测到了键盘输入q,则退出,即关闭窗口
        break
cap.release()                # 释放摄像头
cv2.destroyAllWindows()       # 关闭所有图像窗口
  • cap.read()是按帧读取,其会返回一个元组(两个值):ret,frame
  • 第一个参数ret是布尔值,值为True或False,代表有没有读到图片(如果读取帧是正确的则返回True,如果文件读取到结尾,它的返回值就为False);
  • 第二个参数是frame,是捕获的每一帧的画面(截取一帧的图片的三维矩阵BGR形式)。

2.使用摄像头捕获视频并保存

视频保存可以用cv2.VideoWriter这个函数,需要参数有视频名, 格式, 码率(fps), 帧的尺寸等参数

代码如下:

import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        # frame = cv2.flip(frame,0)       # 横向翻转
        out.write(frame)                # 写入帧
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
out.release()
cv2.destroyAllWindows()       # 完成后释放

创建一个VideoWriter对象,指定输出文件名(例如:output.avi)。之后指定FourCC代码(FourCC是用于指定视频编解码器的4字节代码。可用代码列表)。接下来传递每秒帧数(fps)和帧大小。最后一个是isColor标志,如果它为True,编码器编码成彩色帧,否则编码成灰度框帧。

或代码如下(显示时间版):

import cv2
import datetime
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        text = 'Width: ' + str(cap.get(3)) + ' Height:' + str(cap.get(4))
        datet = str(datetime.datetime.now())
        cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
        cv2.putText(frame, datet, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
        out.write(frame)                # 写入帧
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
out.release()
cv2.destroyAllWindows()       # 完成后释放

其中cv2.putText (图像,添加的文字,左上角坐标,字体,字体大小, 颜色,字体粗细)

字体颜色:
(0, 0, 255) ~红色
(0, 255, 0) ~绿色
(255, 0, 0) ~深蓝色
(0, 255, 255) ~黄色
(255, 255, 0) ~浅蓝色

字体粗细:(整数)
1~细
2~粗

font 字体选择 :
 FONT_HERSHEY_SIMPLEX
 Python: cv.FONT_HERSHEY_SIMPLEX
 normal size sans-serif font(标准大小无衬线字体)
 ~
 FONT_HERSHEY_PLAIN
 Python: cv.FONT_HERSHEY_PLAIN
 small size sans-serif font(小型无衬线字体)
 ~
 FONT_HERSHEY_DUPLEX
 Python: cv.FONT_HERSHEY_DUPLEX
 normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX)
 ~
 FONT_HERSHEY_COMPLEX
 Python: cv.FONT_HERSHEY_COMPLEX
 normal size serif font(标准大小衬线字体)
 ~
 FONT_HERSHEY_TRIPLEX
 Python: cv.FONT_HERSHEY_TRIPLEX
 normal size serif font (more complex than FONT_HERSHEY_COMPLEX)
 ~
 FONT_HERSHEY_COMPLEX_SMALL
 Python: cv.FONT_HERSHEY_COMPLEX_SMALL
 smaller version of FONT_HERSHEY_COMPLEX
 ~
 FONT_HERSHEY_SCRIPT_SIMPLEX
 Python: cv.FONT_HERSHEY_SCRIPT_SIMPLEX
 hand-writing style font
 ~
 FONT_HERSHEY_SCRIPT_COMPLEX
 Python: cv.FONT_HERSHEY_SCRIPT_COMPLEX
 more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX
 ~
 FONT_ITALIC
 Python: cv.FONT_ITALIC
 flag for italic font
 ~
 字体大小,数值越大,字体越大
 字体粗细,越大越粗,数值表示线占有直径像素个数

二、opencv按帧提取视频中的图片

代码如下:

import cv2
import logging

# log information settings
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s: %(message)s')


def save_image(num, image):
    image_path = 'D:\CODE\keras-face-recognition\jietu/{}.jpg'.format(str(num))
    cv2.imwrite(image_path, image)

vc = cv2.VideoCapture('1.avi')

if vc.isOpened():
    ret, frame = vc.read()
else:
    ret = False

count = 0               # 照片排序
frame_interval = 10     # 隔10帧取图片
frame_interval_count = 0

while ret:
    ret, frame = vc.read()
    if frame_interval_count % frame_interval == 0:
        save_image(count, frame)
        logging.info("num:" + str(count) + ", frame: " +
                     str(frame_interval_count))
        count += 1
    frame_interval_count += 1
    cv2.waitKey(1)

vc.release()

三、计算视频总帧数以及FPS

代码如下:

import cv2

def read_video(file_path):
    video_cap = cv2.VideoCapture(file_path)
    video_frameNum = 0
    # all_frames = []
    while (True):
        ret, frame = video_cap.read()
        if ret is False:
            break
        # all_frames.append(frame)
        video_frameNum = video_frameNum + 1

    ### 获取视频的FPS ###
    (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')  # Find OpenCV version

    if int(major_ver) < 3:
        video_FPS = video_cap.get(cv2.cv.CV_CAP_PROP_FPS)
    # print("Frames per second using video_cap.get(cv2.cv.CV_CAP_PROP_FPS): {0}".format(fps))
    else:
        video_FPS = video_cap.get(cv2.CAP_PROP_FPS)
    # print("Frames per second using video_cap.get(cv2.CAP_PROP_FPS) : {0}".format(fps))

    video_cap.release()

    return video_frameNum, video_FPS


video_path = 'test.mp4'
video_frameNum, video_FPS = read_video(video_path)  # 获取视频帧数
print(video_frameNum)
print(video_FPS)

仅计算FPS:

import cv2

cap = cv2.VideoCapture('1.avi')
fps = cap.get(cv2.CAP_PROP_FPS)
success,image = cap.read()
count = 0
success = True
while success:
    success,frame = cap.read()
    count+=1
    print("time stamp current frame:",count/fps)