[OpenCV-Python] 5 videos

OpenCV-Python: II Gui features in OpenCV

5 videos

Goals
  • Learn to read video files, display videos, save video files
  • Learn to get and display videos from the camera
  • You will learn these functions: cv2.VideoCapture(), cv2.VideoWrite()

5.1 Capture video with camera

We often need to use a camera to capture real-time images. OpenCV provides a very simple interface for this application. Let's use the camera to capture a video and convert it to grayscale video for display. Let's start with this simple task.
  In order to get the video, you should create a VideoCapture object. His parameter can be the index number of the device, or a video file. The device index number is to specify the camera to be used. The general laptop computer has a built-in camera. So the parameter is 0. You can select other cameras by setting it to 1 or others. After that, you can capture the video frame by frame. But in the end, don't forget to stop capturing the video.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

cap.read() returns a Boolean value (True/False). If the frame read is correct, it is True. So in the end, you can check whether the video file has reached the end by checking its return value.
  Sometimes cap may not be able to successfully initialize the camera device. In this case, the above code will report an error. You can use cap.isOpened() to check whether the initialization is successful. If the return value is True, there is no problem. Otherwise, use the function cap.open().
You can use the function cap.get(propId) to get some parameter information of the video. Here propId can be any integer between 0 and 18. Each number represents an attribute of the video, see the table below

Some of these values ​​can be modified using cap.set(propId,value), and value is the new value you want to set.
  For example, I can use cap.get(3) and cap.get(4) to see the width and height of each frame.
  The value obtained by default is 640X480. But I can use ret=cap.set(3,320) and ret=cap.set(4,240) to change the width and height to 320X240. Note: When your program reports an error, the first thing you should check is whether your camera can work normally in other programs (such as Cheese under Linux).

5.2 Play video from file

As with capturing from the camera, you only need to change the device index number to the name of the video file. When playing each frame, use cv2.waiKey() to set an appropriate duration. If the setting is too low, the video will play very fast, if the setting is too high, it will play very slowly (you can use this method to control the speed of the video). Normally 25 milliseconds is sufficient.

import numpy as np
import cv2

cap = cv2.VideoCapture('vtest.avi')

while(cap.isOpened()):
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Note: You should make sure that you have installed the appropriate version of ffmpeg or gstreamer. If you make a mistake, it will be a headache.

5.3 Save video

After we capture the video and process each frame, we want to save the video. When the picture comes, it is very simple and just use cv2.imwrite(). But for video, more work must be done.
  This time we are going to create a VideoWriter object. We should determine the name of an output file. Next, specify the FourCC code (described below). The playback frequency and frame size also need to be determined. The last one is the isColor tag. If it is True, each frame is a color image, otherwise it is a grayscale image.
FourCC is a 4-byte code used to determine the encoding format of the video. The list of available codes can be found at fourcc.org. This is platform dependent. The following encoders are useful to me.
  • In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is more preferable. MJPG results in high size video. X264 givesvery small size video)
  • In Windows: DIVX (More to be tested and added)
  • In OSX: (I don't have access to OSX. Can some one fill this?)

The FourCC code is passed to the program in the following format, taking MJPG as an example:

cv2.cv.FOURCC('M','J','P','G') or cv2.cv.FOURCC(*'MJPG').

The following code is to capture video from the camera, rotate each frame in the horizontal direction and save it.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
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)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

For more information, please pay attention to the official account:
img

Guess you like

Origin blog.csdn.net/yegeli/article/details/113405345