python-opencv study three: the video related operations (read video files, show video, save video files)

Copyright: Reprinted please contact: [email protected] https://blog.csdn.net/weixin_40928253/article/details/89786725

       The main functions used are: cv2.VideoCapture (), cv2.VideoWrite ().

 A captured video with a camera

      We often need to use the camera to capture real-time images. OpenCV provides a very simple interface for this application. Let's use the cameras to capture a video and convert it to grayscale video display.

Ado, directly on the code. (Very detailed comments, that much good. :()

import cv2
#从摄像头读取图像
if __name__ == "__main__":
    # 获取摄像头0(本电脑摄像头)
    cap = cv2.VideoCapture(0)

    while (True):
        # 逐帧捕获
        ret, frame = cap.read()
        # 将摄像头获取的图像转为灰度图像
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        # 展示灰度图片
        cv2.imshow('frame', gray)
        # 按下ESC键退出
        k = cv2.waitKey(1)
        if k & k == 27:
            break
    cap.release()
    cv2.destroyAllWindows()

Second, play the video file

      As with the capture from the camera, you just need to change the name of the device index number of the video file. When playback for each frame, using cv2.waiKey () to set an appropriate duration. If set too low, the video will play very fast, if set too high it will play very slow (you can use this method to control the playback speed of the video). Normally it 25 ms.

#从文件中读取图像并显示
if __name__ == "__main__":
    def ReadVideo(self):
        cap = cv2.VideoCapture('1.avi')
        while (cap.isOpened()):
            ret, frame = cap.read()
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            cv2.imshow('frame', gray)
            k = cv2.waitKey(1)
            if k & k == 27:
                break
        cap.release()
        cv2.destroyAllWindows()

Third, read from the video camera is displayed and saved as output.avi

Paste code process is not demonstrated. (This is the entry-level operation, code comments in great detail)

#从摄像头中读取图像并保存为output.avi
if __name__ == "__main__":
    cap = cv2.VideoCapture(0)
    #生成的视频格式设置为.avi(OpenCV只支持avi的格式,而且生成的视频文件不能大于2GB,而且不能添加音频)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    # cv2.VideoWriter(视频名, 格式, 码率(fps), 帧的尺寸等参数)
    out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

    while (cap.isOpened()):
        ret, frame = cap.read()
        if ret == True:
            #进行图像翻转, 1水平翻转、 0垂直翻转、-1水平垂直翻转
            frame = cv2.flip(frame,1)
            out.write(frame)
            cv2.imshow('frame', frame)
            #按下esc键退出
            if cv2.waitKey(1) & cv2.waitKey(1) == 27:
                break
        else:
            break
    cap.release()
    out.release()
    cv2.destroyAllWindows()

okk !!!

 

Guess you like

Origin blog.csdn.net/weixin_40928253/article/details/89786725