Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

OpenCV Video Processing

OpenCV Video Processing

A video is composed of a series of consecutive image frames, each of which is a static image.

The core of video processing is to process these image frames. Common video processing tasks include video reading, video playback, video saving, video frame processing, etc.

Applications of video processing

OpenCV provides the cv2.VideoCapture and cv2.VideoWriter Two classes, used for reading and writing videos respectively. In addition, OpenCV also provides a rich set of image processing functions that can perform various operations on video frames.

Video reading and playback

Read a video file

To read a video file, first create a cv2.VideoCapture object and specify the path of the video file.

Example

import

cv2

Create a VideoCapture object to read the video file

cap

=

cv2.

VideoCapture

(

'example.mp4'

)

Check whether the video opened successfully

if

not

cap.

isOpened

(

)

:

   

print

(

"Error: Could not open video."

)

    exit

(

)

Read a video frame

while

True

:

    ret

,

frame

=

cap.

read

(

)

   

   

If the last frame is reached, exit the loop

   

if

not

ret:

       

break

   

   

Display the current frame

    cv2.

imshow

(

'Video'

,

frame

)

   

   

Press the 'q' key to exit

   

if

cv2.

waitKey

(

25

)

&

0xFF

==

ord

(

'q'

)

:

       

break

Dispose resources

cap.

release

(

)

cv2.

destroyAllWindows

(

)

Read camera video

Besides reading video files, OpenCV can also read video directly from a camera; just set the cv2.VideoCapture parameter to the camera index (usually 0):

Example

import

cv2

Create a VideoCapture object to read camera video

cap

=

cv2.

VideoCapture

(

0

)

Check whether the camera opened successfully

if

not

cap.

isOpened

(

)

:

   

print

(

"Error: Could not open camera."

)

    exit

(

)

Read a video frame

while

True

:

    ret

,

frame

=

cap.

read

(

)

   

   

If the last frame is reached, exit the loop

   

if

not

ret:

       

break

   

   

Display the current frame

    cv2.

imshow

(

'Camera'

,

frame

)

   

   

Press the 'q' key to exit

   

if

cv2.

waitKey

(

25

)

&

0xFF

==

ord

(

'q'

)

:

       

break

Dispose resources

cap.

release

(

)

cv2.

destroyAllWindows

(

)

Video Frame Processing

Basic operations on frames

After reading a video frame, you can perform various image processing operations on each frame.

For example, you can convert a frame to a grayscale image:

Example

import

cv2

cap

=

cv2.

VideoCapture

(

'example.mp4'

)

while

True

:

    ret

,

frame

=

cap.

read

(

)

   

   

if

not

ret:

       

break

   

   

Convert the frame to a grayscale image

    gray_frame

=

cv2.

cvtColor

(

frame

,

cv2.

COLOR_BGR2GRAY

)

   

   

Display the grayscale frame

    cv2.

imshow

(

'Gray Video'

,

gray_frame

)

   

   

if

cv2.

waitKey

(

25

)

&

0xFF

==

ord

(

'q'

)

:

       

break

cap.

release

(

)

cv2.

destroyAllWindows

(

)

Saving frames

When processing video frames, sometimes you need to save the processed frames as a new video file.

You can use the cv2.VideoWriter class to achieve this:

Example

import

cv2

cap

=

cv2.

VideoCapture

(

'example.mp4'

)

Get the frame rate and size of the video

fps

=

int

(

cap.

get

(

cv2.

CAP_PROP_FPS

)

)

width

=

int

(

cap.

get

(

cv2.

CAP_PROP_FRAME_WIDTH

)

)

height

=

int

(

cap.

get

(

cv2.

CAP_PROP_FRAME_HEIGHT

)

)

Create a VideoWriter object to save the processed video

fourcc

=

cv2.

VideoWriter_fourcc

(

'XVID'

)

out

=

cv2.

VideoWriter

(

'output.avi'

,

fourcc

,

fps

,

(

width

,

height

)

)

while

True

:

    ret

,

frame

=

cap.

read

(

)

   

   

if

not

ret:

       

break

   

   

Convert the frame to a grayscale image

    gray_frame

=

cv2.

cvtColor

(

frame

,

cv2.

COLOR_BGR2GRAY

)

   

   

Write the grayscale frame to the output video

    out.

write

(

cv2.

cvtColor

(

gray_frame

,

cv2.

COLOR_GRAY2BGR

)

)

   

   

Display the grayscale frame

    cv2.

imshow

(

'Gray Video'

,

gray_frame

)

   

   

if

cv2.

waitKey

(

25

)

&

0xFF

==

ord

(

'q'

)

:

       

break

cap.

release

(

)

out.

release

(

)

cv2.

destroyAllWindows

(

)

Advanced applications of video processing

Object detection in video

OpenCV provides a variety of object detection algorithms, such as Haar feature classifiers, HOG + SVM, etc.

The following is an example of face detection using a Haar feature classifier:

Example

import

cv2

Load the Haar Feature Classifier

face_cascade

=

cv2.

CascadeClassifier

(

cv2.

data

.

haarcascades

'haarcascade_frontalface_default.xml'

)

cap

=

cv2.

VideoCapture

(

'example.mp4'

)

while

True

:

    ret

,

frame

=

cap.

read

(

)

   

   

if

not

ret:

       

break

   

   

Convert the frame to a grayscale image

    gray_frame

=

cv2.

cvtColor

(

frame

,

cv2.

COLOR_BGR2GRAY

)

   

   

Detect faces

    faces

=

face_cascade.

detectMultiScale

(

gray_frame

,

scaleFactor

=

1.1

,

minNeighbors

=

5

,

minSize

=

(

30

,

30

)

)

   

   

Draw rectangles on the frame to mark faces

   

for

(

x

,

y

,

w

,

h

)

in

faces:

        cv2.

rectangle

(

frame

,

(

x

,

y

)

,

(

x+w

,

y+h

)

,

(

255

,

0

,

0

)

,

2

)

   

   

Display the frame with face markers

    cv2.

imshow

(

'Face Detection'

,

frame

)

   

   

if

cv2.

waitKey

(

25

)

&

0xFF

==

ord

(

'q'

)

:

       

break

cap.

release

(

)

cv2.

destroyAllWindows

(

)

Motion detection in video

Motion detection is an important application in video processing. Moving objects can be detected by computing the difference between frames.

The following is a simple motion detection example:

Example

import

cv2

cap

=

cv2.

VideoCapture

(

'example.mp4'

)

Read the first frame

ret

,

prev_frame

=

cap.

read

(

)

prev_gray

=

cv2.

cvtColor

(

prev_frame

,

cv2.

COLOR_BGR2GRAY

)

while

True

:

    ret

,

frame

=

cap.

read

(

)

   

   

if

not

ret:

       

break

   

   

Convert the current frame to a grayscale image

    gray_frame

=

cv2.

cvtColor

(

frame

,

cv2.

COLOR_BGR2GRAY

)

   

   

Compute the difference between the current frame and the previous frame

    frame_diff

=

cv2.

absdiff

(

prev_gray

,

gray_frame

)

   

   

Binarize the difference image

    _

,

thresh

=

cv2.

threshold

(

frame_diff

,

30

,

255

,

cv2.

THRESH_BINARY

)

   

   

Display the motion detection result

    cv2.

imshow

(

'Motion Detection'

,

thresh

)

   

   

Update the previous frame

    prev_gray

=

gray_frame

   

   

if

cv2.

waitKey

(

25

)

&

0xFF

==

ord

(

'q'

)

:

       

break

cap.

release

(

)

cv2.

destroyAllWindows

(

)


Common functions

Function Function/Method Description
Read the video cv2.VideoCapture() Read a video file or camera.
Read the video frame by frame cap.read() Read the video frame by frame.
Get video properties cap.get(propId) Get the video's properties (such as width, height, frame rate, etc.).
Save video cv2.VideoWriter() Create a video writing object and save the video.
Video Frame Processing Image processing functions (such as cv2.cvtColor()) Perform image processing on video frames.
Target tracking cv2.TrackerKCF_create() Use target tracking algorithms to track objects in the video.
Motion detection cv2.createBackgroundSubtractorMOG2() Use background subtraction algorithms to detect moving objects in the video.

cv2.VideoCapture

define:
cv2.VideoCapture Used to capture video frames from a video file or camera.

Syntax:



cv2.VideoCapture(source)

Parameter Description:

Example

import

cv2

Open the default camera

cap

=

cv2.

VideoCapture

(

0

)

while

True

:

    ret

,

frame

=

cap.

read

(

)

   

if

not

ret:

       

break

    cv2.

imshow

(

'Frame'

,

frame

)

   

if

cv2.

waitKey

(

1

)

&

0xFF

==

ord

(

'q'

)

:

       

break

cap.

release

(

)

cv2.

destroyAllWindows

(

)

cv2.VideoWriter

define:
cv2.VideoWriter Used to write video frames to a video file.

Syntax:



cv2.VideoWriter(filename, fourcc, fps, frameSize)

Parameter Description:

Example

import

cv2

cap

=

cv2.

VideoCapture

(

0

)

fourcc

=

cv2.

VideoWriter_fourcc

(

'XVID'

)

out

=

cv2.

VideoWriter

(

'output.avi'

,

fourcc

,

20.0

,

(

640

,

480

)

)

while

cap.

isOpened

(

)

:

    ret

,

frame

=

cap.

read

(

)

   

if

not

ret:

       

break

    out.

write

(

frame

)

    cv2.

imshow

(

'Frame'

,

frame

)

   

if

cv2.

waitKey

(

1

)

&

0xFF

==

ord

(

'q'

)

:

       

break

cap.

release

(

)

out.

release

(

)

cv2.

destroyAllWindows

(

)

cv2.cvtColor

define:
cv2.cvtColor Used to convert an image from one color space to another.

Syntax:



cv2.cvtColor(src, code)

Parameter Description:

Example

import

cv2

img

=

cv2.

imread

(

'image.jpg'

)

gray

=

cv2.

cvtColor

(

img

,

cv2.

COLOR_BGR2GRAY

)

cv2.

imshow

(

'Gray Image'

,

gray

)

cv2.

waitKey

(

0

)

cv2.

destroyAllWindows

(

)

cv2.resize

define:
cv2.resize Used to resize an image.

Syntax:



cv2.resize(src, dsize)

Parameter Description:

Example

import

cv2

img

=

cv2.

imread

(

'image.jpg'

)

resized

=

cv2.

resize

(

img

,

(

320

,

240

)

)

cv2.

imshow

(

'Resized Image'

,

resized

)

cv2.

waitKey

(

0

)

cv2.

destroyAllWindows

(

)

cv2.Canny

define:
cv2.Canny Used for edge detection.

Syntax:



cv2.Canny(image, threshold1, threshold2)

Parameter Description:

Example

import

cv2

img

=

cv2.

imread

(

'image.jpg'

,

0

)

edges

=

cv2.

Canny

(

img

,

100

,

200

)

cv2.

imshow

(

'Edges'

,

edges

)

cv2.

waitKey

(

0

)

cv2.

destroyAllWindows

(

)

cv2.findContours

define:
cv2.findContours Used to find contours in an image.

Syntax:



cv2.findContours(image, mode, method)

Parameter Description:

Example

import

cv2

img

=

cv2.

imread

(

'image.jpg'

,

0

)

contours

,

_

=

cv2.

findContours

(

img

,

cv2.

RETR_TREE

,

cv2.

CHAIN_APPROX_SIMPLE

)

cv2.

drawContours

(

img

,

contours

,

1

,

(

0

,

255

,

0

)

,

3

)

cv2.

imshow

(

'Contours'

,

img

)

cv2.

waitKey

(

0

)

cv2.

destroyAllWindows

(

)

cv2.drawContours

define:
cv2.drawContours Used to draw contours in an image.

Syntax:



cv2.drawContours(image, contours, contourIdx, color, thickness)

Parameter Description:

Example

import

cv2

img

=

cv2.

imread

(

'image.jpg'

,

0

)

contours

,

_

=

cv2.

findContours

(

img

,

cv2.

RETR_TREE

,

cv2.

CHAIN_APPROX_SIMPLE

)

cv2.

drawContours

(

img

,

contours

,

1

,

(

0

,

255

,

0

)

,

3

)

cv2.

imshow

(

'Contours'

,

img

)

cv2.

waitKey

(

0

)

cv2.

destroyAllWindows

(

)

cv2.putText

define:
cv2.putText Used to draw text on an image.

Syntax:



cv2.putText(image, text, org, fontFace, fontScale, color, thickness)

Parameter Description:

Example

import

cv2

img

=

cv2.

imread

(

'image.jpg'

)

cv2.

putText

(

img

,

'Hello, OpenCV!'

,

(

50

,

50

)

,

cv2.

FONT_HERSHEY_SIMPLEX

,

1

,

(

255

,

0

,

0

)

,

2

)

cv2.

imshow

(

'Text'

,

img

)

cv2.

waitKey

(

0

)

cv2.

destroyAllWindows

(

)