opencv learning two (attached): read video images

Last time we learned how to load and save images, so can we get images by frame through the camera? Of course!

Turn on the camera and get the image

code show as below:

import cv2 as cv  #导入cv模块
import numpy as np #np科学计数的包,通过numpy对数据进行处理


def video_demo():
    capture = cv.VideoCapture(0) #打开和电脑上连接的相机
    while(True):
        ret,frame = capture.read() #ret是返回值,frame是视频中的每一帧
        frame = cv.flip(frame, 1) 
        cv.imshow("video", frame) #将每一帧显示出来
        c = cv.waitKey(1) 
        if c == 27:
            break
    capture.release()

video_demo() #调用获取视频方法
cv.destroyAllWindows()  #释放所有的内存

Run screenshot:
Insert picture description here

Method explanation:

1、capture = cv2.VideoCapture(0)

The parameter in VideoCapture() is 0, which means to open the built-in camera of the notebook, and the parameter is the video file path to open the video, such as capture = cv2.VideoCapture(".../test.avi")

2、ret,frame = capture .read()

capture.read() reads the video frame by frame, ret, frame are the two return values ​​of capture.read() method. Where ret is a boolean value, if the read frame is correct, it returns True, if the file is read to the end, its return value is False. Frame is the image of each frame, which is a three-dimensional matrix.
3. cv::flip()
cv::flip() supports image flipping (up and down, left and right, and both).

0: Flip along the y-axis, 0: Flip along the x-axis, <0: Flip along the x and y axes

Insert picture description hereInsert picture description hereInsert picture description here

4. cv.waitKey(1), waitKey() method itself means waiting for keyboard input,

The parameter is 1, which means to switch to the next frame of image with a delay of 1ms, for video;

The parameter is 0, such as cv.waitKey(0) only displays the current frame image, which is equivalent to video pause;

If the parameter is too large, such as cv.waitKey(1000), it will feel stuck because of the long delay.

c gets the ASCII code entered by the keyboard, the ASCII code corresponding to the esc key is 27, that is, when the esc key is pressed, the if conditional sentence is established

5. Call release() to release the camera, call destroyAllWindows() to close all image windows.

Guess you like

Origin blog.csdn.net/weixin_44145452/article/details/112405354