Opencv Python tutorial: get images from video files, cameras, and write video files (video capture, video write)

Return to opencv Python tutorial

Original link: http://www.juzicode.com/archives/5380

Opencv Python tutorial: reading images, displaying and writing images This paper introduces how to deal with still image files. This document introduces how to obtain images from cameras, video files and dynamic picture files, and how to write video files.

1. Get images from video files

Use cap = CV2 Videocapture ('File name ') constructs a cap instance of a video file.

cap.read() method extracts video frame by frame, and each frame is an image, cap The read () method returns a binary. The element value of subscript 0 is True or False. If it is False, it indicates that the reading of the file is completed. The element of subscript 1 is an image object, which is also data of numpy array type.

cap. Isepened() is used to check whether the cap instance is open.

cap.release() releases the instance.

In the following example, the video file is read and displayed to achieve the effect of playing. At the same time, the judgment of the return value of waitKey() is added. Press the key 'Q' or 'Q' to exit the cycle. Here, the value returned by waityKey() is compared with 0xff and then with the ord() value of the character to avoid the situation that the value returned by waityKey() is a non-zero value in the high byte in some systems.

import cv2
print('VX official account: Orange code / juzicode.com')
print('cv2.__version__:',cv2.__version__)

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

while cap.isOpened():
    ret, img = cap.read()
    if ret is not True:
        print("Read complete, exit")
        break      
    #Processing img
    cv2.imshow('vedio', img)
    
    #Check key
    key = cv2.waitKey(20) & 0xff
    if  key == ord('q') or key == ord('Q') :
        break
        
print('cap.isOpened():',cap.isOpened())
cap.release()
print('cap.isOpened():',cap.isOpened())

Operation results:

VX official account: Orange code / juzicode.com
cv2.version: 4.5.2
cap.isOpened(): True
cap.isOpened(): False

From the running results, cap Cap before release () The return value of isepened() is always True.

2. Get images from motion pictures

In Let's see how to use OpenCV to deconstruct the visual illusion of Twitter Daniel jagarikin In this article, we can see that gif format pictures can be regarded as video files, and gif format pictures can also be opened by videocapture (file name). The operation process is similar to the above ordinary video files.

 

3. Get image from camera

To open the camera, you need to use the camera's device number (numeric integer) as an input parameter to enter the videocapture (camera number), such as cap = CV2 VideoCapture(0) constructs a camera access instance with number 0, and the second camera passes in 1, and so on. The processing method of subsequent steps is the same as that of reading video files.

import cv2
print('VX official account: Orange code / juzicode.com')
print('cv2.__version__:',cv2.__version__)

cap = cv2.VideoCapture(0)

while cap.isOpened():
    ret, img = cap.read()
    if ret is not True:
        print("Reading failed, exit")
        break      
    #Processing img
    cv2.imshow('vedio', img)
    
    #Check key
    key = cv2.waitKey(20) & 0xff
    if  key == ord('q') or key == ord('Q') :
        break
        
print('cap.isOpened():',cap.isOpened())
cap.release()
print('cap.isOpened():',cap.isOpened())
 

 

4. Write video file

To write a video file, you need to create a VideoWriter object and pass in four input parameters in turn:

  • The first is the file name;
  • The second is the encoding method, in which the encoding method corresponds to the suffix of the file name;
  • The third parameter is the number of frames written per second, and the reference value is 25, which is in line with human eye habits;
  • The fourth parameter is image size, int type;

The correspondence between common file name suffixes and coding methods is as follows:

file extensionCoding mode
aviXVID
aviMJPG
avimp4v (lowercase)
mp4mp4v (lowercase)

Encoding method required to create VideoWriter_fourcc objects, for example, can create MJPG type codes in the following two ways:

fourcc=cv2.VideoWriter_fourcc('M','J','P','G')
fourcc=cv2.VideoWriter_fourcc(*'MJPG')

Image size can be through cat Get (propid) method, but the method obtains the float type, which needs to be converted to int type and then passed into VideoWriter.

cap = cv2.VideoCapture(0)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) 
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
width = int(width)
height = int(height)

The following is an example of creating video files with three encoding modes: XVID, MJPG and mp4v:

import cv2
print('VX official account: Orange code / juzicode.com')
print('cv2.__version__:',cv2.__version__)
 
#Get image width and height
cap = cv2.VideoCapture(0)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) 
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
width = int(width)
height = int(height)
print(width,height)
 
#Create a VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 25.0, (width,  height))
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out2 = cv2.VideoWriter('output2.avi', fourcc, 25.0, (width,  height))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out3 = cv2.VideoWriter('output3.mp4', fourcc, 25.0, (width,  height))

while cap.isOpened():   
    ret, img = cap.read()
    print(img.shape)
    if ret is not True:
        print("Reading failed, exit")
        break      
    #Processing img
    cv2.imshow('vedio', img)
    out.write(img)
    out2.write(img)
    out3.write(img)

    #Check key
    key = cv2.waitKey(1) & 0xff
    if  key == ord('q') or key == ord('Q') :
        break
 
cap.release()
out.release()
out2.release() 
out3.release()

 

Original link: http://www.juzicode.com/archives/5380

 

Extended reading:

  1. Opencv Python tutorial
  2. Opencv Python tutorial: reading images, displaying and writing images

Keywords: image processing opencv-python

Added by cillosis on Mon, 07 Feb 2022 10:14:06 +0200