"Digital Image Processing-OpenCV/Python" Serial (8) Calling the camera to take pictures and record videos

"Digital Image Processing-OpenCV/Python" Serial (8) Calling the camera to take pictures and record videos


This book’s JD discount purchase link: https://item.jd.com/14098452.html
This book’s CSDN exclusive serial column: https://blog.csdn.net/youcans/category_12418787.html

Insert image description here


Chapter 1 Basic Operations of Images

In order to facilitate beginners to learn OpenCV-Python from scratch, this book starts with basic operations such as image reading, saving and display, so that readers can use and understand each routine in this book step by step.


1.4 Reading and saving video files

A video file is composed of a series of images, and each frame of the video is an image.

The VideoCapture class and VideoWriter class in OpenCV handle video streams, both video files and camera devices.

The VideoCapture class is used to read video files, video streams, or capture video from a camera; the VideoWriter class is used to write and save video files. In the Python language, class initialization can be achieved through the functions cv.VideoCapture and cv.VideoWrite.

function prototype

cv.VideoCapture( index[, apiPreference] ) → <VideoCapture object>
cv.VideoCapture(filename[, apiPreference]) → <VideoCapture object>
cv.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) → <VideoWriter object>


Parameter Description

  • Index: The ID number of the camera. Index=0 means that the camera is turned on by the default backend.
  • filename: The path to read or save the video file, including the file extension.
  • apiPreference: Read the property settings of the video stream.
  • fourcc: The character code of the encoder/decoder used to compress the frame.
    • CV_FOURCC('I','4','2','0'): Uncompressed YUV encoding format, extension .avi.
    • CV_FOURCC('P','I','M','1'): MPEG-1 encoding format, extension .avi.
    • CV_FOURCC('X','V','I','D'): MPEG-4 encoding format, extension .avi.
    • CV_FOURCC('F','L','V','I'): Flash encoding format, extension is .flv.
  • fps: Indicates the frame rate of the video stream.
  • frameSize: Tuple (w, h), indicating the width and height of the video frame.
  • isColor: Boolean type, indicating whether it is a color image.

member function

  • cv.VideoCapture.isOpened(): Check whether video capture is initialized successfully.
  • cv.VideoCapture.read(): Reads a video file, video stream, or captured video device.
  • cv.VideoCapture.release(): Close the video file or device and release the object.
  • cv.VideoCapture.get(propId): Get the properties of VideoCapture class object.
  • cv.VideoCapture.set(propId, value): Set the properties of the VideoCapture class object.
  • cv.VideoWriter.fourcc(c1, c2, c3, c4[, ]): Constructs the fourcc code of the encoder/decoder.
  • cv.VideoWriter.write(image[, ]): Write the next frame of video.
  • cv.VideoWriter.release(): Close video writing and release the object.

Pay attention to the problem

(1) When reading a video file or video stream, you can specify the path of the video file or video stream through filename. When using a camera, you can define the camera ID number through index.
(2) When using a camera device, index=0 means that the camera is turned on from the backend by default. For example, the built-in camera of a notebook supports cameras built into the computer or externally connected, as well as IP cameras on the local network or public network.
(3) The parameter frameSize of the video writing class VideoWriter is a tuple (w, h), that is, the width and height of the video frame, and the shape of the OpenCV image is expressed as (h, w). Note that the order of the two is reversed.
(4) The video processing process is relatively complex, and some program settings are related to the specific system environment. This section only introduces basic member functions and general processing methods. For more information, see the OpenCV documentation (link 1-1).
(5) Many problems in the video processing process will involve the hardware equipment and settings of computers and cameras, and need to be analyzed based on the specific system and environment. It is recommended that readers refer to [Routine 0106] and [Routine 0107] to first confirm whether the configuration of the video reading and device capture environment is correct, and then debug and run other video processing programs.


[Routine 0107] Call the camera to take pictures and record videos

This routine is used to call the notebook's built-in camera to capture pictures and record videos. Note: Due to the different configurations and interfaces of the user's computer and camera, the API settings may need to be modified.


# 【0107】调用摄像头拍照和录制视频
import cv2 as cv

if __name__ == '__main__':
    # 创建视频捕获对象,调用笔记本内置摄像头
    # cam = cv.VideoCapture(0)  # 创建捕获对象,0 为笔记本内置摄像头
    cam = cv.VideoCapture(0, cv.CAP_DSHOW)  # 修改 API 设置为视频输入 DirectShow

    # 设置写入视频图像的高、宽、帧速率和总帧数
    fps = 20  # 设置帧速率
    width = int(cam.get(cv.CAP_PROP_FRAME_WIDTH))  # 640
    height = int(cam.get(cv.CAP_PROP_FRAME_HEIGHT))  # 480
    fourcc = cv.VideoWriter_fourcc(*'XVID')  # 编码器设置为 XVID
    # 创建写入视频对象
    vedioPath = "../images/camera.avi"  # 写入视频文件的路径
    capWrite = cv.VideoWriter(vedioPath, fourcc, fps, (width, height))
    print(fourcc, fps, (width, height))

    sn = 0  # 抓拍图像编号
    while cam.isOpened():  # 检查视频捕获是否成功
        success, frame = cam.read()  # 读取下一帧视频图像
        if success is True:
            cv.imshow('vedio', frame)  # 播放视频图像
            capWrite.write(frame)  # 将当前帧写入视频文件
            key = cv.waitKey(1) & 0xFF  # 接收键盘输入
            if key == ord('c'):  # 按 'c' 键抓拍当前帧
                filePath = "../images/photo{:d}.png".format(sn)  # 保存文件名
                cv.imwrite(filePath, frame)  # 将当前帧保存为图片
                sn += 1  # 更新写入图像的编号
                print(filePath)
            elif key == ord('q'):  # 按 'q' 键结束录制视频
                break
        else:
            print("Can't receive frame.")
            break

    cam.release()  # 关闭视频捕获对象
    capWrite.release()  # 关闭视频写入对象
    cv.destroyAllWindows()  # 关闭显示窗口

Insert image description here


JD discount purchase link for this book: https://item.jd.com/14098452.html


Copyright statement:
youcans@xupt original work, reprints must be marked with the original link: (https://blog.csdn.net/youcans/article/details/133243948)
Copyright 2023 youcans, XUPT
Crated: 2023-09-22

Welcome to follow this book's CSDN exclusive serial column
"Digital Image Processing-OpenCV/Python": https://blog.csdn.net/youcans/category_12418787.html

Guess you like

Origin blog.csdn.net/youcans/article/details/133243948